| 1 | import { createHash } from "node:crypto"; |
| 2 | import { Marked, Renderer } from "marked"; |
| 3 | import GithubSlugger from "github-slugger"; |
| 4 | |
| 5 | const DOCS_URL = "https://github.com/codewhale-hq/CodeWhale/blob/main/docs/"; |
| 6 | |
| 7 | function docLink(href, sourcePath, resolveLink) { |
| 8 | const documentUrl = new URL(sourcePath, DOCS_URL); |
| 9 | const url = new URL(href, documentUrl); |
| 10 | if (!["https:", "http:", "mailto:"].includes(url.protocol)) { |
| 11 | throw new Error(`Unsupported install-guide link protocol: ${url.protocol}`); |
| 12 | } |
| 13 | if (href.startsWith("#")) return href; |
| 14 | if (url.href.startsWith(`${documentUrl.href}#`)) return url.hash; |
| 15 | if (resolveLink && url.href.startsWith(DOCS_URL)) { |
| 16 | const sitePath = resolveLink(url.pathname.slice(new URL(DOCS_URL).pathname.length)); |
| 17 | if (sitePath) return `${sitePath}${url.hash}`; |
| 18 | } |
| 19 | return url.href; |
| 20 | } |
| 21 | |
| 22 | /** Render the checked-in guide at build time; fenced commands stay copyable. */ |
| 23 | export function buildInstallGuide(source, { sourcePath = "INSTALL.md", tableLabel = "Installation table", resolveLink } = {}) { |
| 24 | const slugger = new GithubSlugger(); |
| 25 | const anchors = []; |
| 26 | const fragments = []; |
| 27 | let tableNumber = 0; |
| 28 | const marked = new Marked({ |
| 29 | gfm: true, |
| 30 | renderer: { |
| 31 | heading(token) { |
| 32 | const id = slugger.slug(token.text); |
| 33 | anchors.push(id); |
| 34 | return `<h${token.depth} id="${id}">${this.parser.parseInline(token.tokens)}</h${token.depth}>\n`; |
| 35 | }, |
| 36 | html({ text }) { |
| 37 | // INSTALL.md uses explicit aliases for old incoming links. No other |
| 38 | // raw HTML is needed; reject it rather than widening the HTML surface. |
| 39 | const anchor = text.match(/^<a id="([\p{L}\p{M}\p{N}_-]+)">$/u); |
| 40 | if (anchor) { |
| 41 | anchors.push(anchor[1]); |
| 42 | return text; |
| 43 | } |
| 44 | if (text === "</a>") return text; |
| 45 | throw new Error(`Unsupported raw HTML in install guide: ${text.slice(0, 80)}`); |
| 46 | }, |
| 47 | table(token) { |
| 48 | const label = `${tableLabel} ${++tableNumber}: ${token.header.map((cell) => cell.text).join(" / ")}` |
| 49 | .replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">"); |
| 50 | return `<div class="install-guide-table" role="region" aria-label="${label}" tabindex="0">${Renderer.prototype.table.call(this, token)}</div>\n`; |
| 51 | }, |
| 52 | }, |
| 53 | walkTokens(token) { |
| 54 | if (token.type === "link" || token.type === "image") { |
| 55 | token.href = docLink(token.href, sourcePath, resolveLink); |
| 56 | if (token.href.startsWith("#")) fragments.push(decodeURIComponent(token.href.slice(1))); |
| 57 | } |
| 58 | }, |
| 59 | }); |
| 60 | const tokens = marked.lexer(source); |
| 61 | marked.walkTokens(tokens, marked.defaults.walkTokens); |
| 62 | const searchSlugger = new GithubSlugger(); |
| 63 | const visibleText = (token) => { |
| 64 | if (token.type === "html" || token.type === "space" || token.type === "hr") return ""; |
| 65 | if (token.type === "table") return [...token.header, ...token.rows.flat()].map(visibleText).join(" "); |
| 66 | if (token.items) return token.items.map(visibleText).join(" "); |
| 67 | if (token.tokens) return token.tokens.map(visibleText).join(" "); |
| 68 | return token.text ?? ""; |
| 69 | }; |
| 70 | const searchSections = []; |
| 71 | const headings = []; |
| 72 | let preamble = ""; |
| 73 | for (const token of tokens) { |
| 74 | if (token.type === "heading") { |
| 75 | const id = searchSlugger.slug(token.text); |
| 76 | headings.push({ id, depth: token.depth, title: visibleText(token) }); |
| 77 | searchSections.push({ id, title: visibleText(token), text: "" }); |
| 78 | } else if (searchSections.length) { |
| 79 | const section = searchSections[searchSections.length - 1]; |
| 80 | section.text = [section.text, visibleText(token)].filter(Boolean).join(" "); |
| 81 | } else { |
| 82 | preamble = [preamble, visibleText(token)].filter(Boolean).join(" "); |
| 83 | } |
| 84 | } |
| 85 | const chunks = []; |
| 86 | let htmlTokens = []; |
| 87 | const flush = () => { |
| 88 | if (htmlTokens.length) { |
| 89 | chunks.push({ kind: "html", text: marked.parser(htmlTokens) }); |
| 90 | htmlTokens = []; |
| 91 | } |
| 92 | }; |
| 93 | for (const token of tokens) { |
| 94 | if (token.type === "code") { |
| 95 | flush(); |
| 96 | chunks.push(token.lang ? { kind: "code", text: token.text, lang: token.lang } : { kind: "code", text: token.text }); |
| 97 | } else { |
| 98 | htmlTokens.push(token); |
| 99 | } |
| 100 | } |
| 101 | flush(); |
| 102 | const missing = fragments.filter((id) => !anchors.includes(id)); |
| 103 | if (missing.length) throw new Error(`Missing INSTALL.md anchors: ${missing.join(", ")}`); |
| 104 | return { sourceHash: createHash("sha256").update(source).digest("hex"), anchors, chunks, searchSections, headings, preamble }; |
| 105 | } |
| 106 | |
| 107 | export function installAnchorErrors(text, anchors) { |
| 108 | return [...text.matchAll(/INSTALL\.md#([\w%.-]+)/g)] |
| 109 | .map((match) => decodeURIComponent(match[1])) |
| 110 | .filter((id) => !anchors.includes(id)); |
| 111 | } |
| 112 | |
| 113 | export function renderInstallGuideModule(source, chineseSource) { |
| 114 | const guide = buildInstallGuide(source); |
| 115 | const chinese = chineseSource === undefined ? undefined : buildInstallGuide(chineseSource, { sourcePath: "zh_hans/INSTALL.md", tableLabel: "安装表" }); |
| 116 | const chineseGuide = chineseSource === undefined ? "" : `\nexport const CHINESE_INSTALL_GUIDE = ${JSON.stringify(chinese, null, 2)} as const;\n`; |
| 117 | const localizedGuides = chineseSource === undefined ? "" : `\nexport const INSTALL_GUIDES = {\n en: { guide: INSTALL_GUIDE, lang: "en", sourcePath: "INSTALL.md" },\n zh: { guide: CHINESE_INSTALL_GUIDE, lang: "zh-Hans", sourcePath: "zh_hans/INSTALL.md" },\n} as const;\n`; |
| 118 | return `// Generated from checked-in installation guides by scripts/derive-install.mjs. Do not edit.\n\nexport const INSTALL_GUIDE = ${JSON.stringify(guide, null, 2)} as const;\n${chineseGuide}${localizedGuides}`; |
| 119 | } |
| 120 |