| 1 | import { readFileSync, writeFileSync, existsSync } from "node:fs"; |
| 2 | import { resolve, sep } from "node:path"; |
| 3 | import { createHash } from "node:crypto"; |
| 4 | |
| 5 | export function readDocTopics(webDir) { |
| 6 | const path = resolve(webDir, "lib", "docs-map.ts"); |
| 7 | if (!existsSync(path)) throw new Error(`missing docs registry: ${path}`); |
| 8 | const source = readFileSync(path, "utf8"); |
| 9 | const topics = []; |
| 10 | const pattern = /\{\s*id:\s*"(\w[^"]*)",\s*slug:\s*"(\w[^"]*)",[\s\S]*?repoSource:\s*(\[[^\]]+\]|"[^"]+")/g; |
| 11 | for (const match of source.matchAll(pattern)) { |
| 12 | const paths = match[3].startsWith("[") |
| 13 | ? match[3].match(/"([^"]+)"/g)?.map((value) => value.slice(1, -1)) ?? [] |
| 14 | : [match[3].slice(1, -1)]; |
| 15 | topics.push({ id: match[1], slug: match[2], repoSource: paths }); |
| 16 | } |
| 17 | if (topics.length === 0) throw new Error("empty docs registry"); |
| 18 | return topics; |
| 19 | } |
| 20 | |
| 21 | export function deriveAgentDocs(webDir, repoRoot) { |
| 22 | return readDocTopics(webDir).map((topic) => ({ |
| 23 | id: topic.id, slug: topic.slug, |
| 24 | sources: topic.repoSource.map((path) => { |
| 25 | const absolute = resolve(repoRoot, path.split("#", 1)[0]); |
| 26 | if (!absolute.startsWith(resolve(repoRoot) + sep)) throw new Error(`invalid doc source: ${path}`); |
| 27 | const content = readFileSync(absolute, "utf8"); |
| 28 | return { path, sha256: createHash("sha256").update(content).digest("hex"), content }; |
| 29 | }), |
| 30 | })); |
| 31 | } |
| 32 | |
| 33 | export function writeAgentDocs(webDir, repoRoot) { |
| 34 | writeFileSync( |
| 35 | resolve(webDir, "data", "agent-docs.generated.json"), |
| 36 | `${JSON.stringify(deriveAgentDocs(webDir, repoRoot), null, 2)}\n`, |
| 37 | ); |
| 38 | } |
| 39 |