From 66b8887a570de6768eba78d9f3ef26e20cf96d36 Mon Sep 17 00:00:00 2001 From: mintaka Date: Mon, 9 Nov 2026 23:28:54 -0500 Subject: [PATCH 1/3] feat(site): bundle public repo docs at build time (RIG-9139) Co-authored-by: Matt Wilkinson --- .github/workflows/ci.yml | 3 + .github/workflows/deploy.yml | 13 +- .gitignore | 2 + README.md | 6 + bun.lock | 3 + hk.pkl | 2 +- package.json | 3 + site/scripts/bundle-routes.test.ts | 48 +++++ site/scripts/bundle-routes.ts | 24 +++ site/scripts/fetch.test.ts | 68 +++++++ site/scripts/fetch.ts | 232 ++++++++++++++++++++++ site/scripts/gather.test.ts | 15 +- site/scripts/gather.ts | 308 +++++++++++++++++------------ site/scripts/ref-gate-dist.test.ts | 46 +++++ site/scripts/ref-gate-dist.ts | 61 ++++++ site/sources.json | 32 +++ 16 files changed, 733 insertions(+), 133 deletions(-) create mode 100644 site/scripts/bundle-routes.test.ts create mode 100644 site/scripts/bundle-routes.ts create mode 100644 site/scripts/fetch.test.ts create mode 100644 site/scripts/fetch.ts create mode 100644 site/scripts/ref-gate-dist.test.ts create mode 100644 site/scripts/ref-gate-dist.ts create mode 100644 site/sources.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 145ebceb..5ea6c91f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,5 +60,8 @@ jobs: - name: Public reference gate run: bun run ref-gate + - name: Fetch bundled sources + run: bun run fetch + - name: Build site run: bun run build diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 9e91b924..855dbcfb 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -4,6 +4,9 @@ on: push: branches: [main] pull_request: {} + workflow_dispatch: + schedule: + - cron: "17 5 * * *" permissions: {} @@ -14,7 +17,8 @@ concurrency: jobs: deploy: # Fork PRs do not receive secrets, so skip their Pages deployment. - if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + # Manual runs publish to production main only, so a branch dispatch is skipped. + if: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') runs-on: ubuntu-latest permissions: contents: read @@ -34,12 +38,19 @@ jobs: bun="$(nix build --no-link --print-out-paths --inputs-from . nixpkgs#bun)" echo "$bun/bin" >> "$GITHUB_PATH" + - name: Fetch bundled sources + # Before install: fetch.ts imports only node: modules, so no package code runs here. + run: bun run fetch + - name: Install dependencies run: bun install --frozen-lockfile - name: Build site run: bun run build + - name: Reference gate over published output + run: bun run ref-gate:dist + - name: Deploy to Cloudflare Pages run: bun run deploy env: diff --git a/.gitignore b/.gitignore index bf27db69..7bc616b8 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ dist/ .astro/ .devenv/ site/dist/ +site/.bundle/ site/.astro/ site/node_modules/ .direnv/ @@ -12,3 +13,4 @@ site/src/sidebar.generated.ts node_modules/.cache/ result result-* +site/public/_bundle.json diff --git a/README.md b/README.md index 13b145e1..43fb5aed 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,9 @@ Run `bun install`, `bun test`, `bun run gate`, `bun run ref-gate`, `rumdl check The canonical source-repository dispatch workflow is `site/dispatch/docs-dispatch.yml`. Cloudflare assigns the Pages hostname for project `docs`; the site does not configure a custom domain. + +## Bundled sources + +`site/sources.json` lists the code repos whose markdown the site bundles. `bun run fetch` clones each repo's `main` over anonymous HTTPS into `site/.bundle/`, and `bun run gather` turns their pages into site routes under `//`. A source uses the `default` config (every gatherable markdown file) until it adds a `docs-bundle.toml`. + +The deploy workflow runs the fetch before dependency install. After the build, `bun run ref-gate:dist` scans `site/dist` (minus `pagefind/`) and fails the deploy on a reference hit. The build writes `_bundle.json` with each source's SHA. Set `DOCS_BUNDLE_PINS="="` to build a pinned SHA. diff --git a/bun.lock b/bun.lock index 4a0cba72..368aeb20 100644 --- a/bun.lock +++ b/bun.lock @@ -9,6 +9,7 @@ "@astrojs/starlight": "0.41.8", "@rigelbuild/design-ledger-gate": "2.0.1", "@rigelbuild/dl-claim": "1.1.1", + "@rigelbuild/docs-bundle": "1.2.0", "@rigelbuild/ref-gate": "1.0.0", "astro": "7.2.4", "github-slugger": "2.0.0", @@ -297,6 +298,8 @@ "@rigelbuild/dl-claim": ["@rigelbuild/dl-claim@1.1.1", "", { "dependencies": { "@rigelbuild/design-ledger-gate": "2.0.1" }, "bin": { "dl-claim": "index.ts" } }, "sha512-/amE3EQw3dqJ4nTGKKKBpPqgmiNQxMmHaYd6jtoEyHRXOvmjelIxxVybkOCkWRTXn2Ca0JT8q8XhO3bP5g8aTA=="], + "@rigelbuild/docs-bundle": ["@rigelbuild/docs-bundle@1.2.0", "", { "dependencies": { "github-slugger": "2.0.0" }, "bin": { "docs-bundle": "cli.ts" } }, "sha512-hxDTgde5lfWi72OtdGLfZZJdK3LHuStiFwQesKIEC8fBSeaQjHFhktb13ImrIds31RaBa7AxuYW1eUiwqDXkew=="], + "@rigelbuild/ref-gate": ["@rigelbuild/ref-gate@1.0.0", "", { "bin": { "ref-gate": "index.ts" } }, "sha512-ZWq24B8dYrCzC0O/QjLIFL9PhbBSjaDdJ6ZOvYyVk2IzY+icK9jDdwAgne9Ylg7UqgA2ywgUjWuBtbr7kko/tg=="], "@rigelbuild/tsconfig": ["@rigelbuild/tsconfig@1.0.0", "", {}, "sha512-l1SY3uaeICqJvmmN/BrTLg7IqQZmQcv4dhbiYKKOSMEFnkFUMjvSrugYSmkkglIzprxob81iSlL+I2Pym6eXjw=="], diff --git a/hk.pkl b/hk.pkl index 098fb30e..602108b3 100644 --- a/hk.pkl +++ b/hk.pkl @@ -27,7 +27,7 @@ hooks { } ["build"] = new Step { depends = "ref-gate" - check = "bun run build" + check = "bun run fetch && bun run build" } } } diff --git a/package.json b/package.json index 3135d17a..cef94a7f 100644 --- a/package.json +++ b/package.json @@ -4,11 +4,13 @@ "type": "module", "scripts": { "gather": "bun site/scripts/gather.ts", + "fetch": "bun site/scripts/fetch.ts", "test": "bun test", "build": "bun run gather && astro build --root site", "check": "astro check --root site", "gate": "design-ledger-gate --config design-ledger.config.json", "ref-gate": "ref-gate --config ref-gate.config.json", + "ref-gate:dist": "bun site/scripts/ref-gate-dist.ts", "claim": "dl-claim --config design-ledger.claim.config.json", "deploy": "bun site/scripts/deploy.ts" }, @@ -16,6 +18,7 @@ "@astrojs/check": "0.9.10", "@astrojs/starlight": "0.41.8", "@rigelbuild/design-ledger-gate": "2.0.1", + "@rigelbuild/docs-bundle": "1.2.0", "@rigelbuild/dl-claim": "1.1.1", "@rigelbuild/ref-gate": "1.0.0", "astro": "7.2.4", diff --git a/site/scripts/bundle-routes.test.ts b/site/scripts/bundle-routes.test.ts new file mode 100644 index 00000000..a172acf0 --- /dev/null +++ b/site/scripts/bundle-routes.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, test } from "bun:test"; +import type { BundlePage, FetchedSource } from "@rigelbuild/docs-bundle"; +import { remapSourceRoutes } from "./bundle-routes.ts"; + +const source: FetchedSource = { + repo: "RigelBuild/meissa", + mount: "/meissa/", + config: "default", + root: "/tmp/meissa", + sha: "a".repeat(40), +}; + +function page(sourcePath: string, route: string): BundlePage { + return { + repo: source.repo, + sourcePath, + route, + section: null, + pagefind: true, + }; +} + +describe("bundled route adaptation", () => { + test("remaps nested pages to their public repo mount", () => { + expect( + remapSourceRoutes( + [ + page( + "docs/guides/Setup Guide.md", + "/RigelBuild/meissa/meissa/docs/guides/setup-guide", + ), + ], + source, + ), + ).toEqual([ + page("docs/guides/Setup Guide.md", "/meissa/docs/guides/setup-guide"), + ]); + }); + + test("keeps a README page at the mounted repository's index", () => { + expect( + remapSourceRoutes( + [page("README.md", "/RigelBuild/meissa/meissa/readme")], + source, + ), + ).toEqual([page("README.md", "/meissa")]); + }); +}); diff --git a/site/scripts/bundle-routes.ts b/site/scripts/bundle-routes.ts new file mode 100644 index 00000000..9e09a361 --- /dev/null +++ b/site/scripts/bundle-routes.ts @@ -0,0 +1,24 @@ +import type { BundlePage, FetchedSource } from "@rigelbuild/docs-bundle"; + +export function remapSourceRoutes( + pages: readonly BundlePage[], + source: FetchedSource, +): BundlePage[] { + const repoPrefix = `/${source.repo}`; + const mount = source.mount.replace(/^\/+|\/+$/g, ""); + const mountPrefix = mount.length === 0 ? "" : `/${mount}`; + return pages.map((page) => { + if (page.repo !== source.repo || !page.route.startsWith(repoPrefix)) + throw new Error(`unexpected route from docs bundle: ${page.route}`); + const mounted = page.route.slice(repoPrefix.length); + if (mountPrefix.length > 0 && !mounted.startsWith(mountPrefix)) + throw new Error(`route does not match source mount: ${page.route}`); + const relativeRoute = + mountPrefix.length === 0 ? mounted : mounted.slice(mountPrefix.length); + const route = + page.sourcePath.toLowerCase() === "readme.md" + ? mountPrefix || "/" + : `${mountPrefix}${relativeRoute}`.replace(/\/index$/, "") || "/"; + return { ...page, route }; + }); +} diff --git a/site/scripts/fetch.test.ts b/site/scripts/fetch.test.ts new file mode 100644 index 00000000..9c0c102a --- /dev/null +++ b/site/scripts/fetch.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { + buildCloneArgs, + buildGitEnvironment, + parsePins, + sparsePatterns, +} from "./fetch.ts"; + +describe("source fetch command construction", () => { + test("uses a shallow filtered main clone for unpinned sources", () => { + const args = buildCloneArgs("RigelBuild/meissa", "/tmp/source"); + expect(args).toEqual([ + "-c", + "credential.helper=", + "clone", + "--branch", + "main", + "--filter=blob:none", + "--sparse", + "--depth", + "1", + "https://github.com/RigelBuild/meissa.git", + "/tmp/source", + ]); + }); + + test("keeps blob filtering and drops clone depth for a pinned source", () => { + const args = buildCloneArgs( + "RigelBuild/meissa", + "/tmp/source", + "a".repeat(40), + ); + expect(args).toContain("--filter=blob:none"); + expect(args).not.toContain("--depth"); + expect(sparsePatterns()).toContain("/docs-bundle.toml"); + expect(sparsePatterns()).toContain("/**/*.md"); + expect(sparsePatterns()).toContain("/**/*.SVG"); + }); + + test("constructs a prompt-free environment without inherited credentials", () => { + expect( + buildGitEnvironment({ + PATH: "/usr/bin", + HOME: "/home/test", + GH_TOKEN: "not-forwarded", + GITHUB_TOKEN: "not-forwarded", + GIT_CONFIG_GLOBAL: "/tmp/hostile-config", + }), + ).toEqual({ + PATH: "/usr/bin", + HOME: "/home/test", + GIT_TERMINAL_PROMPT: "0", + GIT_CONFIG_NOSYSTEM: "1", + }); + }); + + test("parses source pins and rejects ambiguous entries", () => { + expect(parsePins(`RigelBuild/meissa=${"b".repeat(40)}`)).toEqual( + new Map([["RigelBuild/meissa", "b".repeat(40)]]), + ); + expect(() => parsePins("RigelBuild/meissa=bad")).toThrow("invalid pin"); + expect(() => + parsePins( + `RigelBuild/meissa=${"b".repeat(40)},RigelBuild/meissa=${"c".repeat(40)}`, + ), + ).toThrow("duplicate pin"); + }); +}); diff --git a/site/scripts/fetch.ts b/site/scripts/fetch.ts new file mode 100644 index 00000000..e8b6652e --- /dev/null +++ b/site/scripts/fetch.ts @@ -0,0 +1,232 @@ +import { spawn } from "node:child_process"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { basename, join } from "node:path"; + +interface Source { + repo: string; + mount: string; + config: "required" | "default"; +} + +interface FetchedSource extends Source { + root: string; + sha: string; +} + +interface FetchOptions { + sources: readonly Source[]; + workDir: string; + pins: ReadonlyMap; + production: boolean; +} + +const IMAGE_EXTENSIONS = [ + "png", + "jpg", + "jpeg", + "gif", + "svg", + "webp", + "avif", +] as const; + +export function parsePins(value: string | undefined): Map { + const pins = new Map(); + if (value === undefined || value.trim() === "") return pins; + for (const entry of value.split(",")) { + const [repo, sha, ...extra] = entry.trim().split("="); + if ( + repo === undefined || + !/^RigelBuild\/[A-Za-z0-9_.-]+$/.test(repo) || + sha === undefined || + !/^[a-f\d]{40}$/i.test(sha) || + extra.length > 0 + ) { + throw new Error(`invalid pin: ${entry}`); + } + if (pins.has(repo)) throw new Error(`duplicate pin: ${repo}`); + pins.set(repo, sha); + } + return pins; +} + +export function sparsePatterns(): string[] { + return [ + "/*.md", + "/**/*.md", + ...IMAGE_EXTENSIONS.flatMap((extension) => [ + `/*.${extension}`, + `/**/*.${extension}`, + `/*.${extension.toUpperCase()}`, + `/**/*.${extension.toUpperCase()}`, + ]), + "/docs-bundle.toml", + ]; +} + +export function buildCloneArgs( + repo: string, + destination: string, + pin?: string, +): string[] { + const args = [ + "-c", + "credential.helper=", + "clone", + "--branch", + "main", + "--filter=blob:none", + "--sparse", + ]; + if (pin === undefined) args.push("--depth", "1"); + args.push(`https://github.com/${repo}.git`, destination); + return args; +} + +export function buildGitEnvironment( + environment: NodeJS.ProcessEnv = process.env, +): NodeJS.ProcessEnv { + const safe: NodeJS.ProcessEnv = { + GIT_TERMINAL_PROMPT: "0", + GIT_CONFIG_NOSYSTEM: "1", + }; + for (const name of [ + "PATH", + "HOME", + "TMPDIR", + "TEMP", + "TMP", + "SystemRoot", + "WINDIR", + ]) { + const value = environment[name]; + if (value !== undefined) safe[name] = value; + } + return safe; +} + +function runGit( + args: readonly string[], + cwd: string, + env: NodeJS.ProcessEnv, +): Promise { + return new Promise((resolve, reject) => { + const child = spawn("git", [...args], { + cwd, + env, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdout += chunk; + }); + child.stderr.on("data", (chunk: string) => { + stderr += chunk; + }); + child.on("error", reject); + child.on("close", (code) => { + if (code === 0) resolve(stdout.trim()); + else + reject(new Error(`git ${args[0]} failed (${code}): ${stderr.trim()}`)); + }); + }); +} + +async function fetchSource( + source: Source, + workDir: string, + pin: string | undefined, + production: boolean, + env: NodeJS.ProcessEnv, +): Promise { + const root = join(workDir, "sources", basename(source.repo)); + await rm(root, { recursive: true, force: true }); + await mkdir(join(workDir, "sources"), { recursive: true }); + await runGit(buildCloneArgs(source.repo, root, pin), workDir, env); + await runGit( + ["-C", root, "sparse-checkout", "set", "--no-cone", ...sparsePatterns()], + workDir, + env, + ); + if (pin !== undefined) { + if (production) { + await runGit( + ["-C", root, "merge-base", "--is-ancestor", pin, "origin/main"], + workDir, + env, + ); + } + await runGit(["-C", root, "checkout", "--detach", pin], workDir, env); + } + const sha = await runGit(["-C", root, "rev-parse", "HEAD"], workDir, env); + await rm(join(root, ".git"), { recursive: true, force: true }); + return { + ...source, + mount: source.mount.replace(/^\/+|\/+$/g, ""), + root, + sha, + }; +} + +function isSource(value: unknown): value is Source { + if (typeof value !== "object" || value === null || Array.isArray(value)) + return false; + const record = value as Record; + return ( + typeof record.repo === "string" && + /^RigelBuild\/[A-Za-z0-9_.-]+$/.test(record.repo) && + typeof record.mount === "string" && + (record.config === "default" || record.config === "required") + ); +} + +async function readSources(path: string): Promise { + const parsed: unknown = JSON.parse(await readFile(path, "utf8")); + if (!Array.isArray(parsed) || !parsed.every(isSource)) + throw new Error(`invalid bundle source list: ${path}`); + return parsed; +} + +export async function fetchSources(options: FetchOptions): Promise { + await mkdir(options.workDir, { recursive: true }); + const fetchedPath = join(options.workDir, "fetched.json"); + await rm(fetchedPath, { force: true }); + const env = buildGitEnvironment(); + for (const repo of options.pins.keys()) { + if (!options.sources.some((source) => source.repo === repo)) + throw new Error(`pin does not match a configured source: ${repo}`); + } + const fetched: FetchedSource[] = []; + for (const source of options.sources) { + fetched.push( + await fetchSource( + source, + options.workDir, + options.pins.get(source.repo), + options.production, + env, + ), + ); + } + await writeFile(fetchedPath, `${JSON.stringify(fetched, null, 2)}\n`); +} + +async function main(): Promise { + const siteRoot = join(import.meta.dir, ".."); + const workDir = join(siteRoot, ".bundle"); + const sources = await readSources(join(siteRoot, "sources.json")); + await mkdir(workDir, { recursive: true }); + await fetchSources({ + sources, + workDir, + pins: parsePins(process.env.DOCS_BUNDLE_PINS), + production: ["push", "schedule", "workflow_dispatch"].includes( + process.env.GITHUB_EVENT_NAME ?? "", + ), + }); +} + +if (import.meta.main) await main(); diff --git a/site/scripts/gather.test.ts b/site/scripts/gather.test.ts index c2aab761..502c4365 100644 --- a/site/scripts/gather.test.ts +++ b/site/scripts/gather.test.ts @@ -1,12 +1,7 @@ import { describe, expect, test } from "bun:test"; import { parseDecisionFile } from "@rigelbuild/design-ledger-gate/decision-files.ts"; -import { - buildDecisionIndex, - extractTitle, - routeSlug, - stripFirstH1, - transform, -} from "./gather.ts"; +import { extractTitle, routeSlug, stripFirstH1 } from "@rigelbuild/docs-bundle"; +import { buildDecisionIndex, transform } from "./gather.ts"; describe("gather transforms", () => { test("derives a title from the first H1 and removes only that H1", () => { @@ -15,14 +10,16 @@ describe("gather transforms", () => { expect(extractTitle(source, "docs/designs/demo/README.md")).toBe( "Project overview", ); - expect(stripFirstH1(source)).toBe("First paragraph.\n\n# Later heading\n"); + expect(stripFirstH1(source)).toBe( + "\nFirst paragraph.\n\n# Later heading\n", + ); }); test("ignores H1 text inside fenced code", () => { const source = "```md\n# Example\n```\n\n# Actual title\n\nBody"; expect(extractTitle(source, "docs/designs/demo/README.md")).toBe( "Actual title", ); - expect(stripFirstH1(source)).toBe("```md\n# Example\n```\n\nBody"); + expect(stripFirstH1(source)).toBe("```md\n# Example\n```\n\n\nBody"); }); test("rewrites gathered Markdown links to their site route", () => { diff --git a/site/scripts/gather.ts b/site/scripts/gather.ts index 741be8c1..0bf9936b 100644 --- a/site/scripts/gather.ts +++ b/site/scripts/gather.ts @@ -1,118 +1,29 @@ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; -import { basename, dirname, join, posix, relative } from "node:path"; +import { basename, dirname, join, relative } from "node:path"; import { type DecisionRow, parseDecisionFile, renderDecisionIndex, } from "@rigelbuild/design-ledger-gate/decision-files.ts"; -import { slug as githubSlug } from "github-slugger"; +import { + assertNoRouteCollisions, + type BundleManifest, + type BundlePage, + collectPages, + extractTitle, + type FetchedSource, + readFetched, + readPublishConfig, + rewriteLinks as rewriteBundleLinks, + routeSlug, + stripFirstH1, + writeManifest, +} from "@rigelbuild/docs-bundle"; +import { remapSourceRoutes } from "./bundle-routes.ts"; const REPO_SLUG = "RigelBuild/docs"; const DECISION_PATH_RE = /^docs\/designs\/([^/]+)\/decisions\/[^/]+\/DL-\d+\.md$/; -const MARKDOWN_LINK = /(!?\[[^\][\n]*)?(\]\()([^)\s]+)(\s+"[^"]*")?(\))/g; - -function firstH1Index(lines: readonly string[]): number { - let fence: { marker: "`" | "~"; length: number } | undefined; - for (let index = 0; index < lines.length; index += 1) { - const line = lines[index] ?? ""; - const fenceMarker = line.trim().match(/^(`{3,}|~{3,})/)?.[1]; - if (fence !== undefined) { - if ( - fenceMarker !== undefined && - fenceMarker[0] === fence.marker && - fenceMarker.length >= fence.length - ) { - fence = undefined; - } - continue; - } - if (fenceMarker !== undefined) { - fence = { - marker: fenceMarker[0] === "`" ? "`" : "~", - length: fenceMarker.length, - }; - continue; - } - if (/^#\s+.+$/.test(line.trim())) return index; - } - return -1; -} - -export function extractTitle(source: string, sourcePath: string): string { - const lines = source.split("\n"); - const heading = firstH1Index(lines); - return heading < 0 - ? basename(sourcePath, ".md") - : (lines[heading] ?? "").trim().replace(/^#\s+/, "").trim(); -} - -export function stripFirstH1(source: string): string { - const lines = source.split("\n"); - const heading = firstH1Index(lines); - if (heading < 0) return source; - lines.splice(heading, lines[heading + 1] === "" ? 2 : 1); - return lines.join("\n"); -} - -export function routeSlug(contentPath: string): string { - return `/${contentPath - .replace(/\.mdx?$/i, "") - .split("/") - .map((segment) => githubSlug(segment)) - .join("/") - .replace(/\/index$/, "")}`; -} - -function contentPath(sourcePath: string): string { - return sourcePath.replace(/^docs\//, ""); -} - -function normalizeRepoPath(path: string): string { - const segments: string[] = []; - for (const segment of path.split("/")) { - if (segment === "" || segment === ".") continue; - if (segment === "..") segments.pop(); - else segments.push(segment); - } - return segments.join("/"); -} - -export function rewriteLinks( - source: string, - sourcePath: string, - gathered: ReadonlySet, -): string { - return source.replace( - MARKDOWN_LINK, - ( - match, - label: string | undefined, - open: string, - target: string, - title: string | undefined, - close: string, - ) => { - if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(target)) return match; - const suffixAt = target.search(/[?#]/); - const linkPath = suffixAt < 0 ? target : target.slice(0, suffixAt); - const suffix = suffixAt < 0 ? "" : target.slice(suffixAt); - const resolved = normalizeRepoPath( - posix.join(dirname(sourcePath), linkPath), - ); - let destination: string; - if (/\.md$/i.test(resolved) && gathered.has(resolved)) { - destination = routeSlug(contentPath(resolved)) + suffix; - } else if (label?.startsWith("!") && gathered.has(resolved)) { - return match; - } else { - const kind = linkPath.endsWith("/") ? "tree" : "blob"; - destination = `https://github.com/${REPO_SLUG}/${kind}/main/${resolved}${suffix}`; - } - return `${label ?? ""}${open}${destination}${title ?? ""}${close}`; - }, - ); -} function frontmatter(title: string, sourcePath?: string): string { const escaped = title.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); @@ -130,21 +41,50 @@ export function transform( ): string { if (DECISION_PATH_RE.test(sourcePath)) { const parsed = parseDecisionFile(sourcePath, source); - if (!parsed.ok) { + if (!parsed.ok) throw new Error( `${sourcePath}:${parsed.error.line}: ${parsed.error.reason}`, ); - } const { id, decision, status, recordRaw } = parsed.row; const body = source.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, ""); const page = `${decision}\n\n**Status:** ${status}\n\n**Record:** [${recordRaw}](${recordRaw})\n${body.trim() === "" ? "" : `\n${body}`}`; return ( - frontmatter(id, sourcePath) + rewriteLinks(page, sourcePath, gathered) + frontmatter(id, sourcePath) + + rewriteDesignLinks(page, sourcePath, gathered) ); } return ( frontmatter(extractTitle(source, sourcePath), sourcePath) + - rewriteLinks(stripFirstH1(source), sourcePath, gathered) + rewriteDesignLinks(stripFirstH1(source), sourcePath, gathered) + ); +} + +function rewriteDesignLinks( + source: string, + sourcePath: string, + gathered: ReadonlySet, +): string { + return source.replace( + /(\]\()([^\s)]+)(\))/g, + (match, open: string, target: string, close: string) => { + if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(target)) return match; + const [path, ...suffix] = target.split(/[?#]/, 2); + if (path === undefined) return match; + const resolved = join(dirname(sourcePath), path).replaceAll("\\", "/"); + const normalized = resolved + .split("/") + .reduce((parts, segment) => { + if (segment === "..") parts.pop(); + else if (segment !== "." && segment !== "") parts.push(segment); + return parts; + }, []) + .join("/"); + if (/\.md$/i.test(normalized) && gathered.has(normalized)) { + const route = routeSlug(normalized.replace(/^docs\//, "")); + return `${open}${route}${suffix.length > 0 ? `#${suffix.join("")}` : ""}${close}`; + } + return `${open}https://github.com/${REPO_SLUG}/blob/main/${normalized}${close}`; + }, ); } @@ -162,7 +102,7 @@ export function buildDecisionIndex( } const sections = [...byArea.keys()].sort().map((area) => { const table = renderDecisionIndex(byArea.get(area) ?? []); - return `## ${basename(area)}\n\n${rewriteLinks(table, `${area}/index.md`, gathered)}`; + return `## ${basename(area)}\n\n${rewriteDesignLinks(table, `${area}/index.md`, gathered)}`; }); return `${frontmatter(`${surface} decisions`)}\nEvery ${surface} decision, by area. Generated from the decision files at build time.\n\n${sections.join("\n")}`; } @@ -178,19 +118,119 @@ async function markdownFiles(directory: string): Promise { return files; } -export async function gather( - repoRoot: string, +async function writeSourcePages( + contentRoot: string, + sources: readonly FetchedSource[], + pages: readonly BundlePage[], + routes: ReadonlyMap, +): Promise { + for (const source of sources) { + for (const page of pages.filter( + (candidate) => candidate.repo === source.repo, + )) { + const markdown = await readFile( + join(source.root, page.sourcePath), + "utf8", + ); + const body = rewriteBundleLinks( + stripFirstH1(markdown), + page, + routes, + source.root, + (link) => + console.warn( + `gather: broken link ${link.repo}/${link.sourcePath} -> ${link.target}`, + ), + ); + const content = `---\ntitle: "${escapeTitle(extractTitle(markdown, page.sourcePath))}"\neditUrl: "https://github.com/${source.repo}/edit/main/${page.sourcePath}"\n---\n${body}`; + const destination = join( + contentRoot, + page.route.replace(/^\/+/, ""), + "index.md", + ); + await mkdir(dirname(destination), { recursive: true }); + await writeFile(destination, content); + } + } +} + +function escapeTitle(title: string): string { + return title.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); +} + +async function loadPages( + sources: readonly FetchedSource[], +): Promise { + const pages: BundlePage[] = []; + for (const source of sources) { + if (source.mount.replace(/^\/+|\/+$/g, "") === "designs") + throw new Error(`source mount may not be designs: ${source.repo}`); + const config = await readPublishConfig(source.root, source.config); + pages.push( + ...remapSourceRoutes(await collectPages(source, config), source), + ); + } + return pages; +} + +async function assertFetchedSources( siteRoot: string, -): Promise { - const docsRoot = join(repoRoot, "docs"); + sources: readonly FetchedSource[], +): Promise { + const configured = JSON.parse( + await readFile(join(siteRoot, "sources.json"), "utf8"), + ) as unknown; + if (!Array.isArray(configured)) + throw new Error("site/sources.json must contain an array"); + const fetched = new Set(sources.map((source) => source.repo)); + const missing = configured.flatMap((entry) => + typeof entry === "object" && + entry !== null && + "repo" in entry && + typeof entry.repo === "string" && + !fetched.has(entry.repo) + ? [entry.repo] + : [], + ); + if (missing.length > 0) + throw new Error(`missing fetched source(s): ${missing.join(", ")}`); +} + +async function bundlePages( + contentRoot: string, + sources: readonly FetchedSource[], + designPages: readonly BundlePage[], +): Promise { + const fetchedPages = await loadPages(sources); + const allPages = [...designPages, ...fetchedPages]; + assertNoRouteCollisions(allPages); + const routes = new Map( + allPages.map((page): [string, string] => [ + `${page.repo}:${page.sourcePath}`, + page.route, + ]), + ); + await writeSourcePages(contentRoot, sources, fetchedPages, routes); + return fetchedPages; +} + +export interface GatherOptions { + repoRoot: string; + siteRoot: string; + sources: FetchedSource[]; +} + +export async function gather(opts: GatherOptions): Promise { + await assertFetchedSources(opts.siteRoot, opts.sources); + const docsRoot = join(opts.repoRoot, "docs"); const files = (await markdownFiles(docsRoot)).sort(); const sources = new Map(); for (const file of files) { - const sourcePath = relative(repoRoot, file).split("\\").join("/"); + const sourcePath = relative(opts.repoRoot, file).split("\\").join("/"); sources.set(sourcePath, await readFile(file, "utf8")); } const gathered = new Set(sources.keys()); - const contentRoot = join(siteRoot, "src", "content", "docs"); + const contentRoot = join(opts.siteRoot, "src", "content", "docs"); await rm(contentRoot, { recursive: true, force: true }); const landing = join(contentRoot, "index.md"); await mkdir(dirname(landing), { recursive: true }); @@ -199,10 +239,19 @@ export async function gather( `${frontmatter("Rigel public design docs")}\nDesign records and decisions for Rigel's public repositories.\n\n## Designs\n\nProjects are listed in the sidebar. Their design records and decisions are grouped by repository.\n`, ); const decisions = new Map(); + const designPages: BundlePage[] = []; for (const [sourcePath, source] of sources) { - const destination = join(contentRoot, contentPath(sourcePath)); + const destination = join(contentRoot, sourcePath.replace(/^docs\//, "")); await mkdir(dirname(destination), { recursive: true }); await writeFile(destination, transform(source, sourcePath, gathered)); + const route = routeSlug(sourcePath.replace(/^docs\//, "")); + designPages.push({ + repo: REPO_SLUG, + sourcePath, + route, + section: null, + pagefind: true, + }); const surface = sourcePath.match(DECISION_PATH_RE)?.[1]; if (surface !== undefined) { const parsed = parseDecisionFile(sourcePath, source); @@ -224,14 +273,29 @@ export async function gather( await mkdir(dirname(destination), { recursive: true }); await writeFile(destination, buildDecisionIndex(surface, rows, gathered)); } - return files.length; + const fetchedPages = await bundlePages( + contentRoot, + opts.sources, + designPages, + ); + const manifest: BundleManifest = { + docsRepo: { repo: REPO_SLUG, sha: process.env.GITHUB_SHA ?? "local" }, + sources: opts.sources.map((source) => ({ + repo: source.repo, + ref: "main", + sha: source.sha, + pages: fetchedPages.filter((page) => page.repo === source.repo).length, + })), + }; + // Astro empties dist/ during the build, so the manifest is written to public/ and copied to dist/. + await writeManifest(join(opts.siteRoot, "public"), manifest); + return manifest; } if (import.meta.main) { const siteRoot = join(import.meta.dir, ".."); const repoRoot = join(siteRoot, ".."); - const count = await gather(repoRoot, siteRoot); - console.log( - `gather: wrote ${count} docs into ${join(siteRoot, "src", "content", "docs")}`, - ); + const sources = await readFetched(join(siteRoot, ".bundle", "fetched.json")); + const manifest = await gather({ repoRoot, siteRoot, sources }); + console.log(`gather: wrote ${manifest.sources.length} bundled sources`); } diff --git a/site/scripts/ref-gate-dist.test.ts b/site/scripts/ref-gate-dist.test.ts new file mode 100644 index 00000000..692428cf --- /dev/null +++ b/site/scripts/ref-gate-dist.test.ts @@ -0,0 +1,46 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { RefGateConfig } from "@rigelbuild/ref-gate"; +import { scanDist } from "./ref-gate-dist.ts"; + +const roots: string[] = []; +const config = { + prefilter: { ere: "forbidden-marker", ignoreCase: false }, + patterns: [{ source: "forbidden-marker", flags: "" }], + ignore: [], + carveOutPaths: [], + carveOutPrefixes: [], + allowlist: {}, +} satisfies RefGateConfig; + +async function fixture(): Promise { + const root = await mkdtemp(join(tmpdir(), "docs-dist-gate-")); + roots.push(root); + return root; +} + +afterAll(async () => { + await Promise.all( + roots.map((root) => rm(root, { recursive: true, force: true })), + ); +}); + +describe("built-output reference gate", () => { + test("finds a forbidden reference in published files", async () => { + const dist = await fixture(); + await writeFile(join(dist, "index.html"), "published forbidden-marker\n"); + expect(await scanDist(dist, config)).toBe(1); + }); + + test("skips files under pagefind", async () => { + const dist = await fixture(); + await mkdir(join(dist, "pagefind"), { recursive: true }); + await writeFile( + join(dist, "pagefind", "pagefind.js"), + "forbidden-marker\n", + ); + expect(await scanDist(dist, config)).toBe(0); + }); +}); diff --git a/site/scripts/ref-gate-dist.ts b/site/scripts/ref-gate-dist.ts new file mode 100644 index 00000000..cc4c1abb --- /dev/null +++ b/site/scripts/ref-gate-dist.ts @@ -0,0 +1,61 @@ +import { readdir, readFile } from "node:fs/promises"; +import { join, relative, sep } from "node:path"; +import { + type Deps, + loadRefGateConfig, + type RefGateConfig, + runOnce, +} from "@rigelbuild/ref-gate"; + +async function publishedFiles(distDir: string): Promise { + const files: string[] = []; + async function walk(directory: string): Promise { + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (entry.name === "pagefind" && directory === distDir) continue; + const path = join(directory, entry.name); + if (entry.isDirectory()) await walk(path); + else if (entry.isFile()) files.push(path); + } + } + await walk(distDir); + return files; +} + +async function grepDist( + distDir: string, + prefilter: RefGateConfig["prefilter"], +): Promise { + const expression = new RegExp(prefilter.ere, prefilter.ignoreCase ? "i" : ""); + const hits: string[] = []; + for (const file of await publishedFiles(distDir)) { + const lines = (await readFile(file, "utf8")).split(/\r?\n/); + for (const [index, line] of lines.entries()) { + if (expression.test(line)) + hits.push( + `${relative(distDir, file).split(sep).join("/")}\0${index + 1}\0${line}`, + ); + expression.lastIndex = 0; + } + } + return hits; +} + +export async function scanDist( + distDir: string, + config: RefGateConfig, +): Promise { + const deps: Deps = { + grep: (prefilter) => grepDist(distDir, prefilter), + log: (message) => console.log(message), + err: (message) => console.error(message), + }; + return runOnce(deps, config); +} + +async function main(): Promise { + const repoRoot = join(import.meta.dir, "../.."); + const config = loadRefGateConfig(join(repoRoot, "ref-gate.config.json")); + process.exitCode = await scanDist(join(import.meta.dir, "../dist"), config); +} + +if (import.meta.main) await main(); diff --git a/site/sources.json b/site/sources.json new file mode 100644 index 00000000..b572eab4 --- /dev/null +++ b/site/sources.json @@ -0,0 +1,32 @@ +[ + { + "repo": "RigelBuild/meissa", + "mount": "/meissa/", + "config": "default" + }, + { + "repo": "RigelBuild/terraform-provider-googleworkspace", + "mount": "/terraform-provider-googleworkspace/", + "config": "default" + }, + { + "repo": "RigelBuild/solid-markdown", + "mount": "/solid-markdown/", + "config": "default" + }, + { + "repo": "RigelBuild/jj-vine", + "mount": "/jj-vine/", + "config": "default" + }, + { + "repo": "RigelBuild/trunk-mq-mcp", + "mount": "/trunk-mq-mcp/", + "config": "default" + }, + { + "repo": "RigelBuild/compass-forge-testbed", + "mount": "/compass-forge-testbed/", + "config": "default" + } +] From 9d61ffc041b727033946824a13066249b8287f8b Mon Sep 17 00:00:00 2001 From: mintaka Date: Wed, 11 Nov 2026 06:35:06 -0500 Subject: [PATCH 2/3] fix(site): address review round 1 on bundled sources (RIG-9139) Strip source frontmatter, keep link suffixes, add per-source nav, drop meissa until its testdata is excluded, and harden the fetch env. Co-authored-by: Matt Wilkinson --- .github/workflows/ci.yml | 3 + README.md | 4 +- bun.lock | 1 - hk.pkl | 2 +- package.json | 1 - site/astro.config.mjs | 15 +++ site/scripts/fetch.test.ts | 22 ++++ site/scripts/fetch.ts | 9 +- site/scripts/gather.test.ts | 215 +++++++++++++++++++++++++++++++++++- site/scripts/gather.ts | 81 ++++++++++++-- site/sources.json | 5 - 11 files changed, 333 insertions(+), 25 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ea6c91f..06b97896 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,3 +65,6 @@ jobs: - name: Build site run: bun run build + + - name: Reference gate over published output + run: bun run ref-gate:dist diff --git a/README.md b/README.md index 43fb5aed..b17c4853 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Check the returned ID before creating `docs/designs//decisions//D ## Checks and site -Run `bun install`, `bun test`, `bun run gate`, `bun run ref-gate`, `rumdl check .`, `biome ci .`, and `bun run build`. The gather step reads checked-in Markdown under `docs/`, renders decision pages and per-project decision indexes into generated content, and the Astro Starlight site publishes to the Cloudflare Pages project `docs`. +Run `bun install`, `bun test`, `bun run gate`, `bun run ref-gate`, `rumdl check .`, `biome ci .`, and `bun run fetch && bun run build`. The gather step reads checked-in Markdown under `docs/`, renders decision pages and per-project decision indexes into generated content, and the Astro Starlight site publishes to the Cloudflare Pages project `docs`. The canonical source-repository dispatch workflow is `site/dispatch/docs-dispatch.yml`. @@ -40,3 +40,5 @@ Cloudflare assigns the Pages hostname for project `docs`; the site does not conf `site/sources.json` lists the code repos whose markdown the site bundles. `bun run fetch` clones each repo's `main` over anonymous HTTPS into `site/.bundle/`, and `bun run gather` turns their pages into site routes under `//`. A source uses the `default` config (every gatherable markdown file) until it adds a `docs-bundle.toml`. The deploy workflow runs the fetch before dependency install. After the build, `bun run ref-gate:dist` scans `site/dist` (minus `pagefind/`) and fails the deploy on a reference hit. The build writes `_bundle.json` with each source's SHA. Set `DOCS_BUNDLE_PINS="="` to build a pinned SHA. + +Each bundled source gets a sidebar group under its mount directory, and the landing page links each source. diff --git a/bun.lock b/bun.lock index 368aeb20..959fff71 100644 --- a/bun.lock +++ b/bun.lock @@ -12,7 +12,6 @@ "@rigelbuild/docs-bundle": "1.2.0", "@rigelbuild/ref-gate": "1.0.0", "astro": "7.2.4", - "github-slugger": "2.0.0", "pagefind": "1.5.2", "sharp": "0.35.2", "wrangler": "4.128.0", diff --git a/hk.pkl b/hk.pkl index 602108b3..e1e78cf1 100644 --- a/hk.pkl +++ b/hk.pkl @@ -27,7 +27,7 @@ hooks { } ["build"] = new Step { depends = "ref-gate" - check = "bun run fetch && bun run build" + check = "bun run fetch && bun run build && bun run ref-gate:dist" } } } diff --git a/package.json b/package.json index cef94a7f..8e3b44b1 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ "@rigelbuild/dl-claim": "1.1.1", "@rigelbuild/ref-gate": "1.0.0", "astro": "7.2.4", - "github-slugger": "2.0.0", "pagefind": "1.5.2", "sharp": "0.35.2", "wrangler": "4.128.0" diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 1610cec9..58d8c5b3 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -1,6 +1,11 @@ +import { readFileSync } from "node:fs"; import starlight from "@astrojs/starlight"; import { defineConfig } from "astro/config"; +const sources = JSON.parse( + readFileSync(new URL("./sources.json", import.meta.url), "utf8"), +); + export default defineConfig({ output: "static", integrations: [ @@ -13,6 +18,16 @@ export default defineConfig({ label: "Designs", items: [{ autogenerate: { directory: "designs" } }], }, + ...sources.map((source) => ({ + label: source.repo.slice(source.repo.indexOf("/") + 1), + items: [ + { + autogenerate: { + directory: source.mount.replace(/^\/+|\/+$/g, ""), + }, + }, + ], + })), ], customCss: ["./src/styles/fonts.css", "./src/styles/custom.css"], // A bundled light Shiki theme keeps code samples readable on the light surface. diff --git a/site/scripts/fetch.test.ts b/site/scripts/fetch.test.ts index 9c0c102a..0b21b1fd 100644 --- a/site/scripts/fetch.test.ts +++ b/site/scripts/fetch.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { buildCloneArgs, buildGitEnvironment, + isSource, parsePins, sparsePatterns, } from "./fetch.ts"; @@ -51,6 +52,7 @@ describe("source fetch command construction", () => { HOME: "/home/test", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_GLOBAL: "/dev/null", }); }); @@ -65,4 +67,24 @@ describe("source fetch command construction", () => { ), ).toThrow("duplicate pin"); }); + + test("rejects dot-named repositories in pins and source lists", () => { + for (const repo of [ + "RigelBuild/.", + "RigelBuild/..", + "RigelBuild/.hidden", + ]) { + expect(() => parsePins(`${repo}=${"b".repeat(40)}`)).toThrow( + "invalid pin", + ); + expect(isSource({ repo, mount: "tool", config: "default" })).toBe(false); + } + expect( + isSource({ + repo: "RigelBuild/jj-vine", + mount: "/jj-vine/", + config: "default", + }), + ).toBe(true); + }); }); diff --git a/site/scripts/fetch.ts b/site/scripts/fetch.ts index e8b6652e..2a75d692 100644 --- a/site/scripts/fetch.ts +++ b/site/scripts/fetch.ts @@ -20,6 +20,8 @@ interface FetchOptions { production: boolean; } +const REPO_PATTERN = /^RigelBuild\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/; + const IMAGE_EXTENSIONS = [ "png", "jpg", @@ -37,7 +39,7 @@ export function parsePins(value: string | undefined): Map { const [repo, sha, ...extra] = entry.trim().split("="); if ( repo === undefined || - !/^RigelBuild\/[A-Za-z0-9_.-]+$/.test(repo) || + !REPO_PATTERN.test(repo) || sha === undefined || !/^[a-f\d]{40}$/i.test(sha) || extra.length > 0 @@ -89,6 +91,7 @@ export function buildGitEnvironment( const safe: NodeJS.ProcessEnv = { GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_GLOBAL: "/dev/null", }; for (const name of [ "PATH", @@ -171,13 +174,13 @@ async function fetchSource( }; } -function isSource(value: unknown): value is Source { +export function isSource(value: unknown): value is Source { if (typeof value !== "object" || value === null || Array.isArray(value)) return false; const record = value as Record; return ( typeof record.repo === "string" && - /^RigelBuild\/[A-Za-z0-9_.-]+$/.test(record.repo) && + REPO_PATTERN.test(record.repo) && typeof record.mount === "string" && (record.config === "default" || record.config === "required") ); diff --git a/site/scripts/gather.test.ts b/site/scripts/gather.test.ts index 502c4365..4e9e9a81 100644 --- a/site/scripts/gather.test.ts +++ b/site/scripts/gather.test.ts @@ -1,7 +1,74 @@ -import { describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; import { parseDecisionFile } from "@rigelbuild/design-ledger-gate/decision-files.ts"; -import { extractTitle, routeSlug, stripFirstH1 } from "@rigelbuild/docs-bundle"; -import { buildDecisionIndex, transform } from "./gather.ts"; +import { + extractTitle, + type FetchedSource, + routeSlug, + stripFirstH1, +} from "@rigelbuild/docs-bundle"; +import { buildDecisionIndex, gather, transform } from "./gather.ts"; + +const cleanups: string[] = []; + +afterEach(async () => { + await Promise.all( + cleanups + .splice(0) + .map((path) => rm(path, { recursive: true, force: true })), + ); +}); + +interface Fixture { + repoRoot: string; + siteRoot: string; + source: FetchedSource; +} + +async function makeFixture( + pages: Record, + configured: readonly string[] = ["RigelBuild/tool"], + mount = "tool", +): Promise { + const base = await mkdtemp(join(tmpdir(), "gather-test-")); + cleanups.push(base); + const repoRoot = join(base, "repo"); + const siteRoot = join(repoRoot, "site"); + const sourceRoot = join(base, "source"); + await mkdir(join(repoRoot, "docs", "designs", "demo"), { recursive: true }); + await writeFile( + join(repoRoot, "docs", "designs", "demo", "record.md"), + "# Record\n\nBody.\n", + ); + await mkdir(siteRoot, { recursive: true }); + await writeFile( + join(siteRoot, "sources.json"), + JSON.stringify( + configured.map((repo) => ({ + repo, + mount: `/${mount}/`, + config: "default", + })), + ), + ); + for (const [path, content] of Object.entries(pages)) { + await mkdir(dirname(join(sourceRoot, path)), { recursive: true }); + await writeFile(join(sourceRoot, path), content); + } + return { + repoRoot, + siteRoot, + source: { + repo: "RigelBuild/tool", + mount, + config: "default", + root: sourceRoot, + sha: "a".repeat(40), + }, + }; +} describe("gather transforms", () => { test("derives a title from the first H1 and removes only that H1", () => { @@ -56,4 +123,146 @@ describe("gather transforms", () => { "/designs/demo/decisions/build/dl-007", ); }); + + test("keeps query and anchor suffixes on routed and fallback links", () => { + const path = "docs/designs/demo/record.md"; + const gathered = new Set([path, "docs/designs/demo/README.md"]); + const source = + "# Record\n\n[Overview](README.md?view=raw#intro) [Code](../../../site/scripts/gather.ts#L10) [Dir](../../../site/)"; + const page = transform(source, path, gathered); + expect(page).toContain("[Overview](/designs/demo/readme?view=raw#intro)"); + expect(page).toContain( + "[Code](https://github.com/RigelBuild/docs/blob/main/site/scripts/gather.ts#L10)", + ); + expect(page).toContain( + "[Dir](https://github.com/RigelBuild/docs/tree/main/site)", + ); + }); + + test("leaves image links unchanged", () => { + const path = "docs/designs/demo/record.md"; + const page = transform( + "# Record\n\n![Logo](logo.png)", + path, + new Set([path]), + ); + expect(page).toContain("![Logo](logo.png)"); + }); +}); + +describe("gather over a source tree", () => { + test("writes bundled pages with editUrl frontmatter and counts them in the manifest", async () => { + const fixture = await makeFixture({ + "guide.md": "# Guide\n\nBody.\n", + "README.md": "# Tool\n\nIntro.\n", + }); + const manifest = await gather({ + repoRoot: fixture.repoRoot, + siteRoot: fixture.siteRoot, + sources: [fixture.source], + }); + const content = join(fixture.siteRoot, "src", "content", "docs"); + const guide = await readFile( + join(content, "tool", "guide", "index.md"), + "utf8", + ); + expect(guide).toContain( + 'editUrl: "https://github.com/RigelBuild/tool/edit/main/guide.md"', + ); + const readme = await readFile(join(content, "tool", "index.md"), "utf8"); + expect(readme).toContain( + 'editUrl: "https://github.com/RigelBuild/tool/edit/main/README.md"', + ); + expect(manifest.sources).toEqual([ + { repo: "RigelBuild/tool", ref: "main", sha: "a".repeat(40), pages: 2 }, + ]); + const written: unknown = JSON.parse( + await readFile(join(fixture.siteRoot, "public", "_bundle.json"), "utf8"), + ); + expect(written).toMatchObject({ sources: manifest.sources }); + }); + + test("strips source frontmatter and titles the page from its H1 or page_title", async () => { + const fixture = await makeFixture({ + "guide.md": + '---\n# generated by https://github.com/hashicorp/terraform-plugin-docs\npage_title: "user Resource"\n---\n# user Resource\n\nBody text.\n', + "fallback.md": + '---\npage_title: "Setup Guide"\n---\n\nBody without a heading.\n', + }); + await gather({ + repoRoot: fixture.repoRoot, + siteRoot: fixture.siteRoot, + sources: [fixture.source], + }); + const content = join(fixture.siteRoot, "src", "content", "docs"); + const guide = await readFile( + join(content, "tool", "guide", "index.md"), + "utf8", + ); + expect(guide).toContain('title: "user Resource"'); + expect(guide).not.toContain("generated by"); + expect(guide).not.toContain("page_title"); + expect(guide.match(/^---$/gm)).toHaveLength(2); + const fallback = await readFile( + join(content, "tool", "fallback", "index.md"), + "utf8", + ); + expect(fallback).toContain('title: "Setup Guide"'); + expect(fallback).not.toContain("page_title"); + }); + + test("strips frontmatter that is not valid YAML instead of failing", async () => { + const fixture = await makeFixture({ + "guide.md": + '---\nlayout: ""\ndescription: |-\nUnindented block text\n---\n# Upgrade Guide\n\nBody.\n', + }); + await gather({ + repoRoot: fixture.repoRoot, + siteRoot: fixture.siteRoot, + sources: [fixture.source], + }); + const guide = await readFile( + join( + fixture.siteRoot, + "src", + "content", + "docs", + "tool", + "guide", + "index.md", + ), + "utf8", + ); + expect(guide).toContain('title: "Upgrade Guide"'); + expect(guide).not.toContain("Unindented block text"); + }); + + test("refuses to gather when a configured source was not fetched", async () => { + const fixture = await makeFixture({ "guide.md": "# Guide\n" }, [ + "RigelBuild/tool", + "RigelBuild/other", + ]); + await expect( + gather({ + repoRoot: fixture.repoRoot, + siteRoot: fixture.siteRoot, + sources: [fixture.source], + }), + ).rejects.toThrow("missing fetched source(s): RigelBuild/other"); + }); + + test("refuses a source mounted at designs", async () => { + const fixture = await makeFixture( + { "guide.md": "# Guide\n" }, + undefined, + "designs", + ); + await expect( + gather({ + repoRoot: fixture.repoRoot, + siteRoot: fixture.siteRoot, + sources: [fixture.source], + }), + ).rejects.toThrow("source mount may not be designs: RigelBuild/tool"); + }); }); diff --git a/site/scripts/gather.ts b/site/scripts/gather.ts index 0bf9936b..e27e07a6 100644 --- a/site/scripts/gather.ts +++ b/site/scripts/gather.ts @@ -19,11 +19,14 @@ import { stripFirstH1, writeManifest, } from "@rigelbuild/docs-bundle"; +import { YAML } from "bun"; import { remapSourceRoutes } from "./bundle-routes.ts"; const REPO_SLUG = "RigelBuild/docs"; const DECISION_PATH_RE = /^docs\/designs\/([^/]+)\/decisions\/[^/]+\/DL-\d+\.md$/; +const SOURCE_FRONTMATTER_RE = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?/; +const DESIGN_LINK = /(!?\[[^\][\n]*)?(\]\()([^)\s]+)(\s+"[^"]*")?(\))/g; function frontmatter(title: string, sourcePath?: string): string { const escaped = title.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); @@ -65,12 +68,25 @@ function rewriteDesignLinks( gathered: ReadonlySet, ): string { return source.replace( - /(\]\()([^\s)]+)(\))/g, - (match, open: string, target: string, close: string) => { + DESIGN_LINK, + ( + match, + label: string | undefined, + open: string, + target: string, + title: string | undefined, + close: string, + ) => { + if (label?.startsWith("!")) return match; if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(target)) return match; - const [path, ...suffix] = target.split(/[?#]/, 2); - if (path === undefined) return match; - const resolved = join(dirname(sourcePath), path).replaceAll("\\", "/"); + const suffixAt = target.search(/[?#]/); + const linkPath = suffixAt < 0 ? target : target.slice(0, suffixAt); + const suffix = suffixAt < 0 ? "" : target.slice(suffixAt); + if (linkPath.length === 0) return match; + const resolved = join(dirname(sourcePath), linkPath).replaceAll( + "\\", + "/", + ); const normalized = resolved .split("/") .reduce((parts, segment) => { @@ -79,11 +95,14 @@ function rewriteDesignLinks( return parts; }, []) .join("/"); + const prefix = `${label ?? ""}${open}`; + const tail = `${title ?? ""}${close}`; if (/\.md$/i.test(normalized) && gathered.has(normalized)) { const route = routeSlug(normalized.replace(/^docs\//, "")); - return `${open}${route}${suffix.length > 0 ? `#${suffix.join("")}` : ""}${close}`; + return `${prefix}${route}${suffix}${tail}`; } - return `${open}https://github.com/${REPO_SLUG}/blob/main/${normalized}${close}`; + const kind = linkPath.endsWith("/") ? "tree" : "blob"; + return `${prefix}https://github.com/${REPO_SLUG}/${kind}/main/${normalized}${suffix}${tail}`; }, ); } @@ -118,6 +137,40 @@ async function markdownFiles(directory: string): Promise { return files; } +function frontmatterTitle(fields: unknown): string | undefined { + if (typeof fields !== "object" || fields === null) return undefined; + if ("title" in fields && typeof fields.title === "string") + return fields.title; + if ("page_title" in fields && typeof fields.page_title === "string") + return fields.page_title; + return undefined; +} + +function splitFrontmatter(markdown: string): { + body: string; + fields: unknown; +} { + const match = SOURCE_FRONTMATTER_RE.exec(markdown); + if (match === null) return { body: markdown, fields: undefined }; + let fields: unknown; + try { + fields = YAML.parse(match[1] ?? ""); + } catch { + // Source repos own their frontmatter; invalid YAML only loses the title. + fields = undefined; + } + return { body: markdown.slice(match[0].length), fields }; +} + +function pageTitle(body: string, fields: unknown, sourcePath: string): string { + const hasH1 = stripFirstH1(body) !== body; + if (!hasH1) { + const fallback = frontmatterTitle(fields); + if (fallback !== undefined) return fallback; + } + return extractTitle(body, sourcePath); +} + async function writeSourcePages( contentRoot: string, sources: readonly FetchedSource[], @@ -132,8 +185,10 @@ async function writeSourcePages( join(source.root, page.sourcePath), "utf8", ); + const { body: markdownBody, fields } = splitFrontmatter(markdown); + const title = pageTitle(markdownBody, fields, page.sourcePath); const body = rewriteBundleLinks( - stripFirstH1(markdown), + stripFirstH1(markdownBody), page, routes, source.root, @@ -142,7 +197,7 @@ async function writeSourcePages( `gather: broken link ${link.repo}/${link.sourcePath} -> ${link.target}`, ), ); - const content = `---\ntitle: "${escapeTitle(extractTitle(markdown, page.sourcePath))}"\neditUrl: "https://github.com/${source.repo}/edit/main/${page.sourcePath}"\n---\n${body}`; + const content = `---\ntitle: "${escapeTitle(title)}"\neditUrl: "https://github.com/${source.repo}/edit/main/${page.sourcePath}"\n---\n${body}`; const destination = join( contentRoot, page.route.replace(/^\/+/, ""), @@ -232,11 +287,17 @@ export async function gather(opts: GatherOptions): Promise { const gathered = new Set(sources.keys()); const contentRoot = join(opts.siteRoot, "src", "content", "docs"); await rm(contentRoot, { recursive: true, force: true }); + const sourceList = opts.sources + .map((source) => { + const mount = source.mount.replace(/^\/+|\/+$/g, ""); + return `- [${source.repo.slice(source.repo.indexOf("/") + 1)}](/${mount}/)`; + }) + .join("\n"); const landing = join(contentRoot, "index.md"); await mkdir(dirname(landing), { recursive: true }); await writeFile( landing, - `${frontmatter("Rigel public design docs")}\nDesign records and decisions for Rigel's public repositories.\n\n## Designs\n\nProjects are listed in the sidebar. Their design records and decisions are grouped by repository.\n`, + `${frontmatter("Rigel public design docs")}\nDesign records and decisions for Rigel's public repositories.\n\n## Designs\n\nProjects are listed in the sidebar. Their design records and decisions are grouped by repository.\n\n## Code repositories\n\nEach bundled repository has its own sidebar group.\n\n${sourceList}\n`, ); const decisions = new Map(); const designPages: BundlePage[] = []; diff --git a/site/sources.json b/site/sources.json index b572eab4..f67ee30d 100644 --- a/site/sources.json +++ b/site/sources.json @@ -1,9 +1,4 @@ [ - { - "repo": "RigelBuild/meissa", - "mount": "/meissa/", - "config": "default" - }, { "repo": "RigelBuild/terraform-provider-googleworkspace", "mount": "/terraform-provider-googleworkspace/", From ebf2022962dd48901fcfc580c723434848e95fb7 Mon Sep 17 00:00:00 2001 From: mintaka Date: Wed, 11 Nov 2026 07:41:59 -0500 Subject: [PATCH 3/3] fix(site): warn on unparsable source frontmatter (RIG-9139) Co-authored-by: Matt Wilkinson --- site/scripts/gather.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/site/scripts/gather.ts b/site/scripts/gather.ts index e27e07a6..328ea259 100644 --- a/site/scripts/gather.ts +++ b/site/scripts/gather.ts @@ -146,7 +146,10 @@ function frontmatterTitle(fields: unknown): string | undefined { return undefined; } -function splitFrontmatter(markdown: string): { +function splitFrontmatter( + markdown: string, + label: string, +): { body: string; fields: unknown; } { @@ -157,6 +160,7 @@ function splitFrontmatter(markdown: string): { fields = YAML.parse(match[1] ?? ""); } catch { // Source repos own their frontmatter; invalid YAML only loses the title. + console.warn(`gather: unparsable frontmatter ${label}`); fields = undefined; } return { body: markdown.slice(match[0].length), fields }; @@ -185,7 +189,10 @@ async function writeSourcePages( join(source.root, page.sourcePath), "utf8", ); - const { body: markdownBody, fields } = splitFrontmatter(markdown); + const { body: markdownBody, fields } = splitFrontmatter( + markdown, + `${source.repo}/${page.sourcePath}`, + ); const title = pageTitle(markdownBody, fields, page.sourcePath); const body = rewriteBundleLinks( stripFirstH1(markdownBody),