返回 CodeWhale
derive-docs-preview.mjs
根目录 / web / scripts / derive-docs-preview.mjs
1 #!/usr/bin/env node
2 import { createHash } from "node:crypto";
3 import { existsSync, readFileSync, writeFileSync } from "node:fs";
4 import { createCssVariablesTheme, createHighlighter } from "shiki";
5 import { buildInstallGuide } from "./install-guide-lib.mjs";
6 import { runtimeRouteInventory } from "./check-runtime-routes.mjs";
7
8 const docsDir = new URL("../../docs/", import.meta.url);
9 const routeSource = new URL("../../crates/app-server/src/runtime_api.rs", import.meta.url);
10 const target = new URL("../lib/docs-preview.generated.ts", import.meta.url);
11
12 const PAGES = [
13 { slug: "install", source: "INSTALL.md" },
14 { slug: "quickstart", source: "GUIDE.md" },
15 { slug: "modes", source: "MODES.md" },
16 ];
17 const LANGUAGES = [
18 { key: "en", lang: "en", dir: "", tableLabel: "Table" },
19 { key: "zh", lang: "zh-Hans", dir: "zh_hans/", tableLabel: "表格" },
20 ];
21 const FENCES = { bash: "bash", sh: "bash", shell: "bash", powershell: "powershell", toml: "toml", json: "json", gitignore: "ini" };
22 const SITE_PATHS = new Map(PAGES.flatMap((page) => LANGUAGES.map((language) => [`${language.dir}${page.source}`, `/docs-preview/${page.slug}`])));
23
24 const theme = createCssVariablesTheme({ name: "codewhale", variablePrefix: "--tk-", fontStyle: false });
25 const highlighter = await createHighlighter({ themes: [theme], langs: [...new Set(Object.values(FENCES))] });
26
27 const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
28
29 function highlight(code, fence) {
30 const lang = FENCES[fence];
31 if (!lang) return null;
32 return highlighter.codeToTokensBase(code, { lang, theme: "codewhale" }).map((line) => line.map((token) => {
33 const role = token.color?.match(/^var\(--tk-token-([a-z-]+)\)$/)?.[1];
34 return role ? `<span class="tk-${role}">${escapeHtml(token.content)}</span>` : escapeHtml(token.content);
35 }).join("")).join("\n");
36 }
37
38 function renderPage(page, language) {
39 const sourcePath = `${language.dir}${page.source}`;
40 const url = new URL(sourcePath, docsDir);
41 if (!existsSync(url)) return null;
42 const source = readFileSync(url, "utf8");
43 const title = source.match(/^# (.+)$/m)?.[1];
44 if (!title) throw new Error(`[docs-preview] ${sourcePath} has no title heading`);
45 const body = source
46 .replace(/^# .+\n+/, "")
47 .replace(/^> [^\n]*\]\((?:zh_hans\/|\.\.\/)[\w.]+\)[^\n]*\n+/, "");
48 const guide = buildInstallGuide(body, { sourcePath, tableLabel: language.tableLabel, resolveLink: (path) => SITE_PATHS.get(path) });
49 return {
50 title,
51 lang: language.lang,
52 sourcePath: `docs/${sourcePath}`,
53 sourceHash: createHash("sha256").update(source).digest("hex"),
54 headings: guide.headings.filter((heading) => heading.depth <= 3),
55 chunks: guide.chunks.map((chunk) => chunk.kind === "code" ? { ...chunk, html: highlight(chunk.text, chunk.lang) } : chunk),
56 searchSections: [{ id: "", title, text: guide.preamble }, ...guide.searchSections],
57 markdown: `# ${title}\n\n${body}`,
58 };
59 }
60
61 function routeGroups() {
62 const groups = new Map();
63 for (const row of runtimeRouteInventory(readFileSync(routeSource, "utf8"))) {
64 const segments = row.path.split("/").filter(Boolean);
65 const name = segments[0] === "v1" ? segments[1] : segments[0] === "__codewhale" ? "bootstrap" : segments[0] ?? "root";
66 groups.set(name, [...(groups.get(name) ?? []), row]);
67 }
68 return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([name, routes]) => ({ name, routes }));
69 }
70
71 const pages = Object.fromEntries(PAGES.map((page) => [
72 page.slug,
73 Object.fromEntries(LANGUAGES.map((language) => [language.key, renderPage(page, language)]).filter(([, rendered]) => rendered)),
74 ]));
75 const routes = { sourcePath: "crates/app-server/src/runtime_api.rs", sourceHash: createHash("sha256").update(readFileSync(routeSource)).digest("hex"), groups: routeGroups() };
76
77 writeFileSync(target, `// Generated from docs/*.md and crates/app-server/src/runtime_api.rs by scripts/derive-docs-preview.mjs. Do not edit.\n\nexport const DOCS_PREVIEW_PAGES = ${JSON.stringify(pages, null, 1)};\n\nexport const DOCS_PREVIEW_ROUTES = ${JSON.stringify(routes, null, 1)};\n`);
78 console.log(`[docs-preview] rendered ${PAGES.length} Markdown pages in ${LANGUAGES.length} languages and ${routes.groups.reduce((sum, group) => sum + group.routes.length, 0)} runtime routes`);
79
79 lines Plain Text