Repository navigation
Expand file tree
/
Copy pathdocs-site.mjs
More file actions
232 lines (230 loc) · 14.2 KB
/
Copy pathdocs-site.mjs
File metadata and controls
232 lines (230 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { readFile, writeFile, mkdir, rm, cp, access } from "node:fs/promises";
import { dirname, resolve, relative, posix, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { fromMarkdown } from "mdast-util-from-markdown";
import { databaseInventory, documentLinks, expectedSkillReferences, headingIds, headingText, markdownFiles, repositoryTarget } from "./lib/documentation.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const docs = resolve(root, "docs");
const output = resolve(root, ".cache/docs-site");
const navigation = JSON.parse(await readFile(resolve(docs, "site/navigation.json"), "utf8"));
const editions = JSON.parse(await readFile(resolve(docs, "site/languages.json"), "utf8"));
const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
const languages = Object.keys(editions);
const currentRelease = `releases/${manifest.version}`;
const pages = [{ id: "README", group: "", labels: {} }];
for (const group of navigation) {
for (const [id, en, zh, translatedRelease] of group.pages) {
pages.push({ id, group: group.id, translatedRelease, labels: { en, "zh-cn": zh } });
}
}
const hasEdition = (page, lang) =>
page.group !== "releases" || page.translatedRelease || lang === "en" || lang === "zh-cn";
const source = (page, lang) => `${page.id}${editions[lang].suffix}.md`;
const route = (page, lang) => `/${lang}/${page.group ? `${page.group}/` : ""}${page.id === "README" ? "" : posix.basename(page.id)}`;
const sourcePages = new Map();
const problems = [];
for (const page of pages) {
for (const lang of languages) {
if (!hasEdition(page, lang)) continue;
const path = resolve(docs, source(page, lang));
if (sourcePages.has(path)) throw new Error(`Duplicate documentation source: ${path}`);
sourcePages.set(path, { page, lang });
try { await access(path); } catch { problems.push(`Missing ${lang} document: ${relative(root, path)}`); }
}
}
if (problems.length) throw new Error(problems.join("\n"));
const repository = "https://github.com/workhold/doca/blob/main/";
const documents = new Map();
for (const path of await markdownFiles(root)) {
const markdown = await readFile(path, "utf8");
const tree = fromMarkdown(markdown);
documents.set(path, { markdown, tree, headings: headingIds(tree), sourceHeadings: headingIds(tree, "github") });
}
let linkCount = 0;
for (const [path, { tree }] of documents) {
for (const { href, node } of documentLinks(tree)) {
let target;
try { target = repositoryTarget(root, path, href); }
catch { problems.push(`${relative(root, path)}:${node.position.start.line} has malformed link encoding: ${href}`); continue; }
if (!target) continue;
linkCount++;
if (target.outside) problems.push(`${relative(root, path)} links outside the repository: ${href}`);
else {
try { await access(target.destination); } catch { problems.push(`${relative(root, path)}:${node.position.start.line} has a missing target: ${href}`); }
const document = documents.get(target.destination);
if (target.fragment && document && !document.headings.has(target.fragment) && !document.sourceHeadings.has(target.fragment)) {
problems.push(`${relative(root, path)}:${node.position.start.line} has a missing heading: ${href}`);
}
}
}
}
for (const [target, expected] of await expectedSkillReferences(root)) {
if (documents.get(resolve(root, "skills", target))?.markdown !== expected) problems.push(`Stale skill reference: skills/${target}; run node scripts/sync-docs-skills.mjs`);
}
if (navigation.find(group => group.id === "releases")?.pages[0]?.[0] !== currentRelease) problems.push("The release navigation does not start with the current host version");
for (const lang of languages) {
const suffix = editions[lang].suffix;
const home = documents.get(resolve(docs, `README${suffix}.md`))?.markdown;
const current = `${currentRelease}${suffix}.md`;
if (!home?.includes(current)) problems.push(`The ${lang} documentation home does not link to ${current}`);
const editor = documents.get(resolve(docs, `editor-integration${suffix}.md`))?.markdown;
for (const name of ["slate", "markdown", "sheet", "canvas", "slides"]) {
const pkg = `@smartdoca/${name}`;
if (!editor?.includes(`| ${pkg} ${manifest.dependencies[pkg]} |`)) problems.push(`The ${lang} editor matrix disagrees with package.json: ${pkg}`);
}
}
const inventory = databaseInventory(root);
const payloadSource = await readFile(resolve(root, "packages/db/src/book-payload-schema.ts"), "utf8");
const generation = payloadSource.match(/export const BOOK_PAYLOAD_BASELINE = "([^"]+)"/)?.[1];
if (!generation) throw new Error("Cannot determine the current database compatibility generation");
for (const name of ["database.md", "database.zh-CN.md"]) {
const markdown = documents.get(resolve(docs, name))?.markdown ?? "";
const baseline = markdown.split("\n").find(line => /^(The current compatibility generation|当前兼容代际)/.test(line));
if (!baseline?.includes(`\`${generation}\``)) problems.push(`${name} has a stale database compatibility generation`);
const rows = new Map([...markdown.matchAll(/^\| `([^`]+)` \| (.*?) \|$/gm)].map(match => [match[1], [...match[2].matchAll(/`([^`]+)`/g)].map(field => field[1])]));
if (rows.size !== inventory.length) problems.push(`${name} table count disagrees with Schema (${inventory.length})`);
for (const table of inventory) {
if (rows.get(table.name)?.join(",") !== table.fields.join(",")) problems.push(`${name} has stale fields for ${table.name}`);
}
}
const publishedRoutes = new Set(Array.from(sourcePages.values(), ({ page, lang }) => route(page, lang)));
const pagesUrl = "https://workhold.github.io/doca/#";
for (const lang of languages) {
const name = `README${editions[lang].suffix}.md`;
const markdown = await readFile(resolve(root, name), "utf8");
const homeLanguages = lang === "en" || lang === "zh-cn" ? languages : [lang];
const homeRoutes = homeLanguages.map(code => `/${code}/`);
const links = documentLinks(fromMarkdown(markdown));
for (const home of homeRoutes) {
if (!links.some(({ href }) => href === pagesUrl + home)) problems.push(`${name} is missing the documentation entrance ${home}`);
}
const screenshots = ["workspace", "rich-text", "markdown", "spreadsheet", "slides", "canvas"];
for (const image of screenshots) {
const path = `docs/images/${lang}/${image}.jpg`;
if (!links.some(({ href }) => href === path)) problems.push(`${name} is missing its screenshot ${path}`);
}
for (const { href } of links) {
if (href.startsWith(`${pagesUrl}/`)) {
const path = new URL(href).hash.slice(1).split("?")[0];
if (!publishedRoutes.has(path) || (!path.startsWith(`/${lang}/`) && !homeRoutes.includes(path))) {
problems.push(`${name} has an invalid ${lang} documentation link: ${href}`);
}
}
}
}
function checkFragment(path, destination, fragment) {
if (fragment && !documents.get(destination)?.headings.has(decodeURIComponent(fragment))) {
problems.push(`${relative(root, path)} has a missing heading: ${relative(root, destination)}#${fragment}`);
}
}
const languageLabels = new Set(["中文", "简體中文", ...Object.values(editions).map(edition => edition.name)]);
const files = [];
for (const page of pages) {
for (const lang of languages) {
if (!hasEdition(page, lang)) continue;
const path = resolve(docs, source(page, lang));
const { markdown, tree } = documents.get(path);
if ((lang === "en" || lang === "zh-cn") && languages.every(code => hasEdition(page, code))) {
const title = tree.children.findIndex(node => node.type === "heading" && node.depth === 1);
const languageLinks = title >= 0 ? tree.children[title + 1] : undefined;
for (const code of languages.filter(code => code !== lang)) {
const sibling = relative(dirname(path), resolve(docs, source(page, code))).split(sep).join("/");
const url = pagesUrl + route(page, code);
const found = languageLinks?.type === "paragraph" && languageLinks.children.some(node =>
node.type === "link" && headingText(node) === editions[code].name && (node.url === sibling || node.url === url),
);
if (!found) problems.push(`${relative(root, path)} needs a ${code} edition link immediately after the title`);
}
}
const replacements = [];
async function visit(node) {
if (["link", "image", "definition"].includes(node.type)) {
const href = node.url;
if (href?.startsWith("#") && !href.startsWith("#/")) checkFragment(path, path, href.slice(1));
if (href && !/^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(href)) {
const [local, ...fragmentParts] = href.split("#");
const fragment = fragmentParts.length ? `#${fragmentParts.join("#")}` : "";
const destination = resolve(dirname(path), decodeURI(local));
const repoPath = relative(root, destination).split("\\").join("/");
if (repoPath.startsWith("../") || repoPath === "..") {
problems.push(`${relative(root, path)} links outside the repository: ${href}`);
} else {
try { await access(destination); } catch { problems.push(`${relative(root, path)} has a missing target: ${href}`); }
const target = sourcePages.get(destination);
let replacement;
if (target && node.type !== "image") {
// Language-switch links select a language; ordinary links stay in the current language.
const label = (node.children ?? []).map(child => child.value ?? "").join("").trim();
const targetLang = languageLabels.has(label) || !hasEdition(target.page, lang) ? target.lang : lang;
checkFragment(path, resolve(docs, source(target.page, targetLang)), fragment.slice(1));
replacement = `${route(target.page, targetLang)}${fragment}`;
} else if (node.type === "image" && repoPath.startsWith("docs/images/")) {
replacement = `assets/${repoPath.slice("docs/".length)}${fragment}`;
} else {
const base = node.type === "image" ? "https://raw.githubusercontent.com/workhold/doca/main/" : repository;
replacement = `${base}${repoPath}${fragment}`;
}
const start = node.position.start.offset;
const segment = markdown.slice(start, node.position.end.offset);
const urlOffset = segment.indexOf(href, segment.indexOf("]") + 1);
if (urlOffset < 0) problems.push(`${relative(root, path)} has an unsupported link spelling: ${href}`);
else replacements.push({ start: start + urlOffset, end: start + urlOffset + href.length, value: replacement });
}
}
}
for (const child of node.children ?? []) await visit(child);
}
await visit(tree);
let published = markdown;
for (const edit of replacements.sort((a, b) => b.start - a.start)) published = published.slice(0, edit.start) + edit.value + published.slice(edit.end);
files.push({ path: `${route(page, lang).slice(1)}${page.id === "README" ? "README" : ""}.md`, content: published });
}
}
if (problems.length) throw new Error(problems.join("\n"));
if (process.argv[2] === "check") {
console.log(`Documentation verified: ${documents.size} repository documents, ${linkCount} repository links, ${files.length} editions in ${languages.length} languages; headings, release/editor versions, ${inventory.length} schema tables and skill references agree.`);
} else if (process.argv[2] === "build") {
await rm(output, { recursive: true, force: true });
await mkdir(output, { recursive: true });
await cp(resolve(docs, "site/assets"), resolve(output, "assets"), { recursive: true });
await cp(resolve(docs, "images"), resolve(output, "assets/images"), { recursive: true, filter: path => !path.endsWith(".md") });
await cp(resolve(docs, "site/index.html"), resolve(output, "index.html"));
await writeFile(resolve(output, ".nojekyll"), "");
for (const file of files) {
await mkdir(dirname(resolve(output, file.path)), { recursive: true });
await writeFile(resolve(output, file.path), file.content);
}
for (const lang of languages) {
const edition = editions[lang];
const sidebar = [`- [${edition.home}](/${lang}/)`];
for (const group of navigation) {
sidebar.push(`- ${edition.groups[group.id]}`);
for (const page of pages.filter(page => page.group === group.id && hasEdition(page, lang))) {
const heading = documents.get(resolve(docs, source(page, lang))).tree.children.find(node => node.type === "heading");
const title = page.labels[lang] ?? (heading ? headingText(heading) : posix.basename(page.id));
sidebar.push(` - [${title.replaceAll("[", "\\[").replaceAll("]", "\\]")}](${route(page, lang)})`);
}
if (group.id === "releases" && lang !== "en" && lang !== "zh-cn") {
const precedingRelease = pages.find(page => page.group === "releases" && page.id !== currentRelease);
if (precedingRelease) sidebar.push(` - [${edition.archive}](${route(precedingRelease, "en")})`);
}
}
await writeFile(resolve(output, lang, "_sidebar.md"), `${sidebar.join("\n")}\n`);
const navbar = [`- ${edition.switchLanguage}`, ...languages.map(code => ` - [${editions[code].name}](/${code}/)`), "- [GitHub](https://github.com/workhold/doca)"];
await writeFile(resolve(output, lang, "_navbar.md"), `${navbar.join("\n")}\n`);
}
await writeFile(resolve(output, "README.md"), files.find(file => file.path === "en/README.md").content);
await writeFile(resolve(output, "_404.md"), "# Page not found / 页面不存在\n\n[English](/en/) · [简体中文](/zh-cn/)\n");
const pageIndex = pages.map(page => Object.fromEntries(languages
.filter(lang => hasEdition(page, lang))
.map(lang => [lang, { route: route(page, lang), source: source(page, lang) }])));
const uiLanguages = Object.fromEntries(languages.map(lang => {
const { suffix, groups, ...ui } = editions[lang];
return [lang, ui];
}));
await writeFile(resolve(output, "assets/pages.json"), JSON.stringify(pageIndex));
await writeFile(resolve(output, "assets/languages.js"), `window.docaDocsLanguages = ${JSON.stringify(uiLanguages).replaceAll("<", "\\u003c")};\n`);
console.log(`Docsify site prepared: ${relative(root, output)} (${files.length} editions).`);
} else {
throw new Error("Usage: node scripts/docs-site.mjs check|build");
}