#!/usr/bin/env bun import * as fs from "node:fs/promises"; import * as path from "node:path"; import { Glob } from "bun"; async function pathExists(candidate: string): Promise { try { await fs.access(candidate); return true; } catch { return false; } } async function findDocsDir(): Promise { let current = path.resolve(import.meta.dir); while (true) { const docsDir = path.join(current, "docs"); if (await pathExists(docsDir)) return docsDir; const parent = path.dirname(current); if (parent === current) return undefined; current = parent; } } const docsDir = await findDocsDir(); const outputPath = path.resolve(import.meta.dir, "../src/internal-urls/docs-index.generated.ts"); if (docsDir === undefined) { const existingIndex = Bun.file(outputPath); if (await existingIndex.exists()) { process.stderr.write("Docs directory not found; keeping bundled docs index.\n"); process.exit(0); } process.stderr.write("Docs directory not found and no bundled docs index exists.\n"); process.exit(1); } const glob = new Glob("**/*.md"); const entries: string[] = []; for await (const relativePath of glob.scan(docsDir)) { entries.push(relativePath.split(path.sep).join("/")); } entries.sort(); const docsWithContent = await Promise.all( entries.map(async relativePath => ({ relativePath, content: await Bun.file(path.join(docsDir, relativePath)).text(), })), ); const filenamesLiteral = JSON.stringify(entries); const mapEntries = docsWithContent .map(({ relativePath, content }) => `\t${JSON.stringify(relativePath)}: ${JSON.stringify(content)},`) .join("\n"); const output = [ "// Auto-generated by scripts/generate-docs-index.ts - DO NOT EDIT", `Reflect.set(globalThis, Symbol.for("gjc.docs-index.generated.loaded"), true);`, "", `export const EMBEDDED_DOC_FILENAMES: readonly string[] = ${filenamesLiteral};`, "", `export const EMBEDDED_DOCS: Readonly> = {`, `${mapEntries}`, `};`, "", ].join("\n"); await Bun.write(outputPath, output); process.stderr.write(`Generated ${path.relative(process.cwd(), outputPath)} (${entries.length} docs)\n`);