From c23875f0d9c8786e86126704abc1ad09f10a500e Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sat, 7 Nov 2026 22:19:40 +0200 Subject: [PATCH 01/14] docs(dox): owner steps for Search Console, Bing and crawler reports (DOX-G6, #448) Runbook section 8 of CORE-86 now lists the console steps that show how the site is crawled and indexed: the Search Console sitemap and URL Inspection, the Bing Webmaster Tools import, the AI Crawl Control request counts, and Crawler Hints. Each step has a Check line, and none is optional. --- context/domination/issues/CORE-86.md | 2 +- context/domination/issues/CORE-86/runbook.md | 43 +++++++++++++++++--- context/dox/built.md | 5 ++- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/context/domination/issues/CORE-86.md b/context/domination/issues/CORE-86.md index 200398011..c4e260510 100644 --- a/context/domination/issues/CORE-86.md +++ b/context/domination/issues/CORE-86.md @@ -77,4 +77,4 @@ The docs site lives on a `workers.dev` hostname that no README, skill or package ## Runbook -[Cloudflare and GitHub steps](CORE-86/runbook.md): the owner's zone, token, landing, deploy-order, Web Analytics, repo-link, Search Console and Sponsors steps, each with its check. +[Cloudflare and GitHub steps](CORE-86/runbook.md): the owner's zone, token, landing, deploy-order, Web Analytics, repo-link, Search Console, Bing Webmaster Tools and Sponsors steps, each with its check. diff --git a/context/domination/issues/CORE-86/runbook.md b/context/domination/issues/CORE-86/runbook.md index eea9455f7..9e1651d5a 100644 --- a/context/domination/issues/CORE-86/runbook.md +++ b/context/domination/issues/CORE-86/runbook.md @@ -162,14 +162,45 @@ gh api orgs/northguild -q .blog # https://nort Today: `homepageUrl` is the `workers.dev` URL and the org website is empty. -## 8. Search Console (optional) +## 8. Search Console, Bing Webmaster Tools and crawler reports -search.google.com/search-console → **Add property → Domain** → `northguild.dev`. Copy the -`google-site-verification=…` value; Cloudflare DNS → Add record → `TXT`, name `@`, that value (the -Search Console flow can also add it through Cloudflare). Verify. Then **Sitemaps** → submit -`https://northguild.dev/gmt/sitemap-index.xml`. +The Domain property's verification record is live on the zone: `dig +short TXT northguild.dev` +lists a `google-site-verification=…` value beside the SPF. Bing has no record yet; step O3 verifies +it by import from Search Console. Steps O1–O5 are the owner's and run in this order. -Check: `dig +short TXT northguild.dev` lists the SPF and the verification value. +**O1: Search Console, Domain property `northguild.dev`.** Confirm the property is verified. Under +**Sitemaps** submit `https://northguild.dev/gmt/sitemap-index.xml`, and, once the root sitemap +exists, `https://northguild.dev/sitemap-index.xml`. + +Check: the sitemap status reads "Success" with a URL count; **Indexing → Pages** shows the indexed +and not-indexed counts and the top three not-indexed reasons. + +**O2: Search Console, URL Inspection.** Inspect `https://northguild.dev/gmt/`, +`https://northguild.dev/gmt/reference/zoned/calculate/startOfZoned/` and +`https://northguild.dev/gmt/install.md`. + +Check: each result says whether the URL is indexed and names the canonical Google chose. + +**O3: Bing Webmaster Tools.** bing.com/webmasters → **Add site → Import from Google Search +Console**, then submit the same sitemap URL or URLs under **Sitemaps**. + +Check: the site is listed as verified, the sitemap shows as processed, and the indexed-page count is +shown. + +**O4: AI Crawl Control, crawler report.** Cloudflare → AI Crawl Control → read the per-crawler +request counts for the last 30 days. This is a read-only report; the Block Crawler switches stay +as § 0 sets them. + +Check: counts appear for GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-SearchBot, +Claude-User, PerplexityBot, Google-Extended and Bingbot, and no crawler shows blocked requests. + +**O5: Crawler Hints.** Cloudflare → Caching → Configuration → **Crawler Hints** → On. It sends +IndexNow pings to participating engines when cached content changes. It is a zone setting and is +not used for anything AI Crawl Control decides. + +Check: the switch reads On. After the next deploy, Bing Webmaster Tools → **IndexNow** lists the +received URLs. If none arrive within a week, switch Crawler Hints off again; nothing in the repo +depends on it. ## 9. GitHub Sponsors (D11) diff --git a/context/dox/built.md b/context/dox/built.md index 4cc6fafc9..c382a81d7 100644 --- a/context/dox/built.md +++ b/context/dox/built.md @@ -170,8 +170,9 @@ that bind future changes, the traps, and the runbooks. Every story is done; stat `dist/gmt/`. - **Smoke.** `scripts/deploy-smoke.mjs` checks the redirect matrix after each deploy. - **`robots.txt`** is served by the landing Worker; crawlers read only the host root. - - **Zone and dashboard setup** (zone settings, tokens, `www`, Web Analytics, org links) is - in `context/domination/issues/CORE-86/runbook.md`. + - **Zone and dashboard setup** (zone settings, tokens, `www`, Web Analytics, org links, Search + Console, Bing Webmaster Tools, the AI Crawl Control report and Crawler Hints) is in + `context/domination/issues/CORE-86/runbook.md`. - **Base `/gmt`.** Routes are base-less inside the site (generators, route manifest, corpus `page` and `url`, sidebar slugs). `src/lib/site.ts` holds `SITE_ORIGIN`, `SITE_BASE`, `SITE_URL` and `LEGACY_ORIGIN`, with `withBase`, `stripBase` and `isUnderBase`. `/gmt` is From 79f3a1fa3d494f3a694a314802a49fb8655c5e39 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sat, 7 Nov 2026 22:19:49 +0200 Subject: [PATCH 02/14] feat(dox): accurate page dates, noindex on twins and long-lived asset caching (DOX-G6, #448) Generated pages now state lastUpdated from their inputs' newest commit (scripts/build-utils/commit-dates.mjs, one git log per run). Starlight reads footer dates from git, and generated MDX is untracked, so these pages had no date at all. The sitemap's lastmod is copied from each page's footer date, so the two cannot disagree. A tracked src/assets-root/_headers is copied to dist/_headers beside _redirects. Hashed /gmt/_astro/* files get a one-year immutable Cache-Control, and the .md twins and llms*.txt files get X-Robots-Tag: noindex, since they have no meta tags or canonical. The 404 page carries noindex and no canonical, so it cannot be indexed as /gmt/404/. deploy-smoke checks the new headers and the 404 page after each deploy. --- apps/dox/astro.config.mjs | 8 +- apps/dox/scripts/build-industry-pages.ts | 21 ++- apps/dox/scripts/build-reference.ts | 41 ++++- apps/dox/scripts/build-scenario-index.mjs | 65 +++----- apps/dox/scripts/build-tool-index.ts | 12 +- apps/dox/scripts/build-utils/commit-dates.mjs | 154 ++++++++++++++++++ .../scripts/build-utils/commit-dates.test.ts | 137 ++++++++++++++++ apps/dox/scripts/build-utils/index-pages.ts | 59 ++++++- .../dox/scripts/build-utils/industry-pages.ts | 33 +++- apps/dox/scripts/deploy-smoke.mjs | 86 +++++++++- apps/dox/scripts/dist-base.test.ts | 41 ++++- apps/dox/scripts/head-tags.test.ts | 82 ++++++++++ apps/dox/src/assets-root/_headers | 14 ++ apps/dox/src/lib/copy-redirects.ts | 39 +++-- apps/dox/src/lib/head-tags.test.ts | 33 ++++ apps/dox/src/lib/head-tags.ts | 19 +++ apps/dox/src/lib/sitemap-lastmod.test.ts | 74 +++++++++ apps/dox/src/lib/sitemap-lastmod.ts | 49 ++++++ apps/dox/src/route-data.ts | 18 +- context/dox/built.md | 50 +++++- 20 files changed, 945 insertions(+), 90 deletions(-) create mode 100644 apps/dox/scripts/build-utils/commit-dates.mjs create mode 100644 apps/dox/scripts/build-utils/commit-dates.test.ts create mode 100644 apps/dox/src/assets-root/_headers create mode 100644 apps/dox/src/lib/sitemap-lastmod.test.ts create mode 100644 apps/dox/src/lib/sitemap-lastmod.ts diff --git a/apps/dox/astro.config.mjs b/apps/dox/astro.config.mjs index d9584ae7f..703315198 100644 --- a/apps/dox/astro.config.mjs +++ b/apps/dox/astro.config.mjs @@ -17,6 +17,7 @@ import rehypeBaseLinks from "./src/lib/rehype-base-links.ts"; import rehypeExternalLinks from "./src/lib/rehype-external-links.ts"; import rehypeTableScroll from "./src/lib/rehype-table-scroll.ts"; import { copyRedirects } from "./src/lib/copy-redirects.ts"; +import { sitemapLastmod } from "./src/lib/sitemap-lastmod.ts"; import { pruneWidgetCss } from "./src/lib/prune-widget-css.ts"; import { gmtReferenceWatch } from "./src/lib/gmt-reference-watch.ts"; import { devWorkerProxy } from "./src/lib/dev-worker-proxy.ts"; @@ -28,6 +29,9 @@ import { MIGRATE, START_HERE } from "./src/lib/section-order.ts"; // and Pagefind resolve under /gmt/. One module holds both, for the Worker and // the scripts too. +/* Where the build writes the pages (`outDir` below), for the sitemap to read. */ +const OUT_DIR = fileURLToPath(new URL("./dist/gmt", import.meta.url)); + const gmtPkg = fileURLToPath( new URL("../../packages/gmt/dist", import.meta.url), ); @@ -299,9 +303,11 @@ export default defineConfig({ ], }), // After starlight(): Starlight adds its own sitemap only when none is configured. /dox/ is - // the chat shell and has `noindex`, so it is not listed. + // the chat shell and has `noindex`, so it is not listed. `lastmod` is the date in the page's + // footer, read from the built HTML (`src/lib/sitemap-lastmod.ts`). sitemap({ filter: (page) => new URL(page).pathname !== withBase("/dox/"), + serialize: (item) => sitemapLastmod(OUT_DIR, item), }), ], }); diff --git a/apps/dox/scripts/build-industry-pages.ts b/apps/dox/scripts/build-industry-pages.ts index 7fb370e1e..e2d906339 100644 --- a/apps/dox/scripts/build-industry-pages.ts +++ b/apps/dox/scripts/build-industry-pages.ts @@ -14,7 +14,7 @@ */ import { readdirSync, readFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { INDUSTRY_OVERVIEWS } from "../src/lib/industry-overview"; @@ -26,11 +26,17 @@ import { type HubIndustry, type HubSectionPage, } from "./build-utils/industry-pages"; +import { + loadCommitDates, + newestCommit, + withLastUpdated, +} from "./build-utils/commit-dates.mjs"; import { syncTree, writeIfChanged } from "./build-utils/generated-files.mjs"; import type { IndexedPage } from "./build-utils/index-pages"; import { readSectionPage } from "./build-utils/industry-sidebar"; const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const repoRoot = resolve(appRoot, "..", ".."); const docsDir = resolve(appRoot, "src", "content", "docs"); const corpusFile = resolve( appRoot, @@ -48,12 +54,13 @@ const pages: IndexedPage[] = ( JSON.parse(readFileSync(corpusFile, "utf8")) as CorpusFunction[] ) .filter((entry) => entry.kind === "function") - .map(({ namespace, module, name, url, description }) => ({ + .map(({ namespace, module, name, url, description, sourcePath }) => ({ namespace, module, name, url, description, + sourcePath, })); const industries: HubIndustry[] = INDUSTRIES.map((industry) => { @@ -94,6 +101,7 @@ function sectionPages(section: string): HubSectionPage[] { title: page.title, description: page.description, industries: page.industries, + path: relative(repoRoot, resolve(dir, file)).split("\\").join("/"), }; }); } @@ -104,9 +112,16 @@ const hubs = renderIndustryHubs({ sectionPages: HUB_SECTIONS.flatMap(({ section }) => sectionPages(section)), }); +// Each hub is dated from the files it states (`build-utils/commit-dates.mjs`), read in one `git log`. +loadCommitDates(hubs.flatMap((hub) => hub.inputs)); const changes = syncTree( resolve(docsDir, "industries"), - new Map(hubs.map((hub) => [hub.file, hub.mdx])), + new Map( + hubs.map((hub) => [ + hub.file, + withLastUpdated(hub.mdx, newestCommit(hub.inputs)), + ]), + ), ); const sidebarWritten = writeIfChanged( resolve(appRoot, "src", "generated", "industries-sidebar.ts"), diff --git a/apps/dox/scripts/build-reference.ts b/apps/dox/scripts/build-reference.ts index eaa05f692..51c92a802 100644 --- a/apps/dox/scripts/build-reference.ts +++ b/apps/dox/scripts/build-reference.ts @@ -59,6 +59,12 @@ import { syncTree, writeIfChanged, } from "./build-utils/generated-files.mjs"; +import { + commitDatesKey, + loadCommitDates, + newestCommit, + withLastUpdated, +} from "./build-utils/commit-dates.mjs"; import { findGaps, formatGapReport, @@ -3000,7 +3006,13 @@ export function generateReference() { `[reference] no published gmt tag (${baseline.none}); no Unreleased badges`, ); } - const hash = `${hashFiles(referenceInputs())}|${baselineKey(baseline)}`; + // Each page states the commit date of its source, so the dates are an input too. + const sourceDates = commitDatesKey( + allSourceFiles(gmtSrc).map((file) => + relative(repoRoot, file).split("\\").join("/"), + ), + ); + const hash = `${hashFiles(referenceInputs())}|${baselineKey(baseline)}|${sourceDates}`; // The MDX tree is gitignored, so a fresh checkout (or a manual `rm -rf`) can // leave the generated modules in place while this directory is gone. const upToDate = @@ -3031,6 +3043,7 @@ function referenceInputs(): string[] { resolve(gmtSrc, "..", "package.json"), fileURLToPath(import.meta.url), resolve(appRoot, "scripts", "build-utils", "build-utils.ts"), + resolve(appRoot, "scripts", "build-utils", "commit-dates.mjs"), resolve(appRoot, "scripts", "build-utils", "doc-gate.ts"), resolve(appRoot, "scripts", "build-utils", "index-pages.ts"), resolve(appRoot, "scripts", "build-utils", "null-is-empty.ts"), @@ -3315,6 +3328,14 @@ function runGeneration(baseline: ReleasedBaseline) { const moduleSymbols = new Map(); const sharedTypes: SymbolEntry[] = []; + // A page states the commit date of the file it is made from (`build-utils/commit-dates.mjs`), + // read for every source in one `git log`. + const sourceOf = (doc: { sourcePath: string }) => + `packages/gmt/src/${doc.sourcePath}`; + loadCommitDates(dedupedDocs.map(sourceOf)); + const dated = (mdx: string, doc: { sourcePath: string }) => + withLastUpdated(mdx, newestCommit([sourceOf(doc)])); + for (const doc of dedupedDocs) { const unreleased = isUnreleased(baseline, doc.name); const withNote = (mdx: string) => @@ -3332,7 +3353,7 @@ function runGeneration(baseline: ReleasedBaseline) { ); pages.set( join(TYPES_SECTION, `${doc.name}.mdx`), - withIndustry(withNote(renderType(doc, page)), typeTags), + dated(withIndustry(withNote(renderType(doc, page)), typeTags), doc), ); pageRoutes.push(typePageUrl(doc.name)); sharedTypes.push({ @@ -3375,9 +3396,12 @@ function runGeneration(baseline: ReleasedBaseline) { pages.set( join(doc.namespace, doc.module, `${doc.name}.mdx`), - withIndustry(withNote(mdx), [ - industryOwning(doc.namespace) ?? CORE_INDUSTRY, - ]), + dated( + withIndustry(withNote(mdx), [ + industryOwning(doc.namespace) ?? CORE_INDUSTRY, + ]), + doc, + ), ); pageRoutes.push(pageUrl(doc.namespace, doc.module, doc.name)); @@ -3410,6 +3434,7 @@ function runGeneration(baseline: ReleasedBaseline) { name: d.name, url: pageUrl(d.namespace, d.module, d.name), description: d.description, + sourcePath: sourceOf(d), }); continue; } @@ -3418,6 +3443,7 @@ function runGeneration(baseline: ReleasedBaseline) { name: d.name, url: typeUrl(usage, d.name)!, description: d.description, + sourcePath: sourceOf(d), }; if (placement.kind === "page") { indexed.sharedTypes.push(entry); @@ -3429,7 +3455,10 @@ function runGeneration(baseline: ReleasedBaseline) { } const indexPages = renderIndexPages(indexed); for (const index of indexPages) { - pages.set(join(...index.file.split("/")), index.mdx); + pages.set( + join(...index.file.split("/")), + withLastUpdated(index.mdx, newestCommit(index.inputs)), + ); } // An index route is every proper prefix of a page route, which is how // `scripts/api-surface.mjs` derives them too. Anything else is a page with no index above diff --git a/apps/dox/scripts/build-scenario-index.mjs b/apps/dox/scripts/build-scenario-index.mjs index b25936fc7..ab0589d91 100644 --- a/apps/dox/scripts/build-scenario-index.mjs +++ b/apps/dox/scripts/build-scenario-index.mjs @@ -8,18 +8,16 @@ * Run as: node apps/dox/scripts/build-scenario-index.mjs */ -import { - existsSync, - readdirSync, - readFileSync, - statSync, - writeFileSync, -} from "node:fs"; -import { dirname, resolve } from "node:path"; +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { lastUpdatedLine, newestCommit } from "./build-utils/commit-dates.mjs"; +import { writeIfChanged } from "./build-utils/generated-files.mjs"; + const __dirname = dirname(fileURLToPath(import.meta.url)); const appRoot = resolve(__dirname, ".."); +const repoRoot = resolve(appRoot, "..", ".."); const scenariosDir = resolve(appRoot, "src", "content", "docs", "scenarios"); const indexPath = resolve(scenariosDir, "index.mdx"); @@ -40,30 +38,6 @@ function parseFrontmatter(content) { return fm; } -function getMtime(path) { - try { - return statSync(path).mtime; - } catch { - return 0; - } -} - -function shouldSkip() { - if (!existsSync(indexPath)) return false; - const entries = readdirSync(scenariosDir); - const latest = entries - .filter((f) => f.endsWith(".mdx") && f !== "index.mdx") - .map((f) => getMtime(resolve(scenariosDir, f))) - .concat(getMtime(indexPath)) - .sort((a, b) => b - a)[0]; - return getMtime(indexPath) >= latest; -} - -if (shouldSkip()) { - console.log("[scenarios] up-to-date, skipping"); - process.exit(0); -} - const files = readdirSync(scenariosDir) .filter((f) => f.endsWith(".mdx") && f !== "index.mdx") .sort(); @@ -72,12 +46,22 @@ const entries = files.map((file) => { const content = readFileSync(resolve(scenariosDir, file), "utf8"); const fm = parseFrontmatter(content); const slug = file.replace(/\.mdx$/, ""); - return { slug, title: fm.title || slug, description: fm.description || "" }; + return { + slug, + title: fm.title || slug, + description: fm.description || "", + path: relative(repoRoot, resolve(scenariosDir, file)).split("\\").join("/"), + }; }); +// The index is dated from the pages it lists. It is rebuilt on every run and written only when its +// text changes, so a commit that moves a page's date moves the index's. +const lastUpdated = lastUpdatedLine(newestCommit(entries.map((e) => e.path))); + const frontmatter = `--- title: Scenarios description: Live examples showing common date/time problems and how GMT solves them. +${lastUpdated} --- `; @@ -91,17 +75,8 @@ const body = entries const source = frontmatter + body; -let previous = ""; -try { - previous = readFileSync(indexPath, "utf8"); -} catch { - previous = ""; -} - -if (previous === source) { +if (writeIfChanged(indexPath, source)) { + console.log(`[scenarios] wrote index.mdx with ${entries.length} entries`); +} else { console.log("[scenarios] up to date"); - process.exit(0); } - -writeFileSync(indexPath, source); -console.log(`[scenarios] wrote index.mdx with ${entries.length} entries`); diff --git a/apps/dox/scripts/build-tool-index.ts b/apps/dox/scripts/build-tool-index.ts index 11439736e..18dff611e 100644 --- a/apps/dox/scripts/build-tool-index.ts +++ b/apps/dox/scripts/build-tool-index.ts @@ -15,12 +15,14 @@ */ import { readdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { INDUSTRY_TAG_IDS, industryTag } from "../src/lib/industry-tags"; +import { lastUpdatedLine, newestCommit } from "./build-utils/commit-dates.mjs"; const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const repoRoot = resolve(appRoot, "..", ".."); const toolsDir = resolve(appRoot, "src", "content", "docs", "tools"); const checkDir = resolve(appRoot, "src", "content", "docs", "check"); const indexPath = resolve(toolsDir, "index.mdx"); @@ -32,6 +34,8 @@ interface Tool { title: string; description: string; industries: string[]; + /** The page's file, repo-relative: the index is dated from the files it lists. */ + path: string; } const unquote = (value: string): string => @@ -57,6 +61,7 @@ function readTool(directory: string, dir: string, file: string): Tool { title: unquote(field("title")) || slug, description: unquote(field("description")), industries, + path: relative(repoRoot, resolve(dir, file)).split("\\").join("/"), }; } @@ -87,9 +92,14 @@ const sections = INDUSTRY_TAG_IDS.flatMap((id) => { ]; }); +const lastUpdated = lastUpdatedLine( + newestCommit(tools.map((tool) => tool.path)), +); + const source = `--- title: Tools description: Every interactive tool on the site, grouped by the industry it belongs to. +${lastUpdated} sidebar: order: 0 label: All tools diff --git a/apps/dox/scripts/build-utils/commit-dates.mjs b/apps/dox/scripts/build-utils/commit-dates.mjs new file mode 100644 index 000000000..e4de23bbe --- /dev/null +++ b/apps/dox/scripts/build-utils/commit-dates.mjs @@ -0,0 +1,154 @@ +/** + * The date each generated page was last changed, read from git. + * + * Starlight finds a page's footer date from the page's own file, and a generated page is not + * tracked, so it has none (`built.md`, "Trap: an untracked page has no footer date"). Each + * generator writes `lastUpdated:` into the page's frontmatter instead, from the commit date of the + * files the page is made from. The sitemap's `` copies the footer, so the two cannot + * disagree. + * + * `newestCommit(paths)` runs one `git log --name-only` per process, over the paths + * it is given, and caches the newest commit time of each path, as Starlight's + * `getAllNewestCommitDate` does. A later call with a path it has not read runs one more `git log` + * for those paths only; a generator that passes every input to `loadCommitDates` first costs one. + * The call reads history only, from `cwd` (the repository root by default); `GIT_DIR` and + * `GIT_WORK_TREE` direct it at a tree that has no `.git`. + */ + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { fileURLToPath } from "node:url"; + +/** The repository root: this file is `apps/dox/scripts/build-utils/commit-dates.mjs`. */ +const REPOSITORY = fileURLToPath(new URL("../../../../", import.meta.url)); + +/** + * Newest commit instant by repo-relative path (`2026-10-19T05:35:38.000Z`), and the paths already + * read, per `cwd`. Git writes the instant in UTC itself (`TZ=UTC`, `format-local`), so there is no + * date arithmetic here, and equal-width UTC strings order as instants. + */ +const caches = new Map(); + +/** + * @param {string} cwd + * @returns {{ times: Map, read: Set }} + */ +function cacheFor(cwd) { + let cache = caches.get(cwd); + if (!cache) { + cache = { times: new Map(), read: new Set() }; + caches.set(cwd, cache); + } + return cache; +} + +/** + * Reads the history of `paths` that this process has not read yet. + * + * @param {readonly string[]} paths repo-relative, `/`-separated + * @param {string} cwd + */ +function readHistory(paths, cwd) { + const cache = cacheFor(cwd); + const missing = [...new Set(paths)].filter((path) => !cache.read.has(path)); + if (missing.length === 0) return; + const log = spawnSync( + "git", + [ + "-c", + "core.quotepath=false", + "log", + "--date=format-local:%Y-%m-%dT%H:%M:%S.000Z", + "--format=t:%cd", + "--name-only", + "--", + ...missing, + ], + { + cwd, + encoding: "utf8", + env: { ...process.env, TZ: "UTC" }, + maxBuffer: 64 * 1024 * 1024, + }, + ); + // No history (not a repository, a shallow clone with no such path) leaves every path without a + // date, which the caller writes as `lastUpdated: false`. + for (const path of missing) cache.read.add(path); + if (log.error || log.status !== 0) return; + let at = ""; + for (const line of log.stdout.split("\n")) { + if (line.startsWith("t:")) { + at = line.slice(2); + } else if (line !== "") { + const known = cache.times.get(line) ?? ""; + if (at > known) cache.times.set(line, at); + } + } +} + +/** + * Reads the history of every path in one `git log`. + * + * @param {readonly string[]} paths repo-relative, `/`-separated + * @param {{ cwd?: string }} [options] + */ +export function loadCommitDates(paths, options = {}) { + readHistory(paths, options.cwd ?? REPOSITORY); +} + +/** + * The newest commit time over `paths`. + * + * @param {readonly string[]} paths repo-relative, `/`-separated + * @param {{ cwd?: string }} [options] + * @returns {string | undefined} an ISO instant in UTC (`2026-10-19T05:35:38.000Z`), or undefined + * when no path has a commit + */ +export function newestCommit(paths, options = {}) { + const cwd = options.cwd ?? REPOSITORY; + readHistory(paths, cwd); + const { times } = cacheFor(cwd); + let newest = ""; + for (const path of paths) { + const at = times.get(path) ?? ""; + if (at > newest) newest = at; + } + return newest === "" ? undefined : newest; +} + +/** + * A digest of every path's newest commit time. A generator that skips unchanged inputs by content + * adds it to the hash: a file edited and then reverted has its old bytes and a new commit date. + * + * @param {readonly string[]} paths repo-relative, `/`-separated + * @param {{ cwd?: string }} [options] + * @returns {string} + */ +export function commitDatesKey(paths, options = {}) { + const cwd = options.cwd ?? REPOSITORY; + readHistory(paths, cwd); + const { times } = cacheFor(cwd); + const lines = [...new Set(paths)] + .sort() + .map((path) => `${path}\t${times.get(path) ?? ""}`); + return createHash("sha256").update(lines.join("\n")).digest("hex"); +} + +/** The frontmatter line for a page: the instant, or `false` when no input has a commit. */ +export function lastUpdatedLine(instant) { + return `lastUpdated: ${instant ?? "false"}`; +} + +/** + * `mdx` with a `lastUpdated:` line at the end of its frontmatter. + * + * @param {string} mdx a page that starts with a frontmatter block + * @param {string | undefined} instant from `newestCommit` + */ +export function withLastUpdated(mdx, instant) { + const close = mdx.indexOf("\n---\n", 4); + if (!mdx.startsWith("---\n") || close < 0) { + throw new Error("[commit-dates] a page has no frontmatter to date."); + } + return `${mdx.slice(0, close)}\n${lastUpdatedLine(instant)}${mdx.slice(close)}`; +} diff --git a/apps/dox/scripts/build-utils/commit-dates.test.ts b/apps/dox/scripts/build-utils/commit-dates.test.ts new file mode 100644 index 000000000..e972a9f71 --- /dev/null +++ b/apps/dox/scripts/build-utils/commit-dates.test.ts @@ -0,0 +1,137 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + lastUpdatedLine, + loadCommitDates, + newestCommit, + withLastUpdated, +} from "./commit-dates.mjs"; + +let repo = ""; + +/** + * `newestCommit` honours these on purpose (a scratch tree reads history through them). The fixture + * is its own repository, so they are removed while this file runs and restored after. + */ +const GIT_LOCATION = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] as const; +const saved: Partial> = {}; + +/** Runs git in the fixture with a pinned identity, so no user config is read or written. */ +function git(args: string[], date?: string) { + execFileSync("git", args, { + cwd: repo, + stdio: "ignore", + env: { + PATH: process.env.PATH, + HOME: repo, + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_SYSTEM: "/dev/null", + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.com", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.com", + ...(date ? { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date } : {}), + }, + }); +} + +function commit(files: Record, date: string) { + for (const [path, text] of Object.entries(files)) { + mkdirSync(join(repo, path, ".."), { recursive: true }); + writeFileSync(join(repo, path), text); + git(["add", path]); + } + git(["commit", "-m", "c"], date); +} + +beforeAll(() => { + for (const name of GIT_LOCATION) { + saved[name] = process.env[name]; + delete process.env[name]; + } + repo = mkdtempSync(join(tmpdir(), "commit-dates-")); + git(["init", "-q", "-b", "main"]); + commit({ "a/one.ts": "1", "a/two.ts": "1" }, "2026-01-01T10:00:00Z"); + commit({ "a/one.ts": "2" }, "2026-02-03T04:05:06Z"); + writeFileSync(join(repo, "untracked.ts"), "x"); +}); + +afterAll(() => { + for (const name of GIT_LOCATION) { + if (saved[name] === undefined) delete process.env[name]; + else process.env[name] = saved[name]; + } + rmSync(repo, { recursive: true, force: true }); +}); + +describe("newestCommit", () => { + it("gives the newest commit of a path as a UTC instant", () => { + expect(newestCommit(["a/one.ts"], { cwd: repo })).toBe( + "2026-02-03T04:05:06.000Z", + ); + expect(newestCommit(["a/two.ts"], { cwd: repo })).toBe( + "2026-01-01T10:00:00.000Z", + ); + }); + + it("gives the newest of several paths", () => { + expect(newestCommit(["a/two.ts", "a/one.ts"], { cwd: repo })).toBe( + "2026-02-03T04:05:06.000Z", + ); + }); + + it("gives undefined for a path with no commit", () => { + expect(newestCommit(["untracked.ts"], { cwd: repo })).toBeUndefined(); + expect(newestCommit(["nowhere.ts"], { cwd: repo })).toBeUndefined(); + expect(newestCommit([], { cwd: repo })).toBeUndefined(); + }); + + it("ignores a path with no commit beside one that has", () => { + expect(newestCommit(["untracked.ts", "a/two.ts"], { cwd: repo })).toBe( + "2026-01-01T10:00:00.000Z", + ); + }); + + it("reads a path once it is loaded", () => { + loadCommitDates(["a/one.ts", "a/two.ts"], { cwd: repo }); + expect(newestCommit(["a/one.ts"], { cwd: repo })).toBe( + "2026-02-03T04:05:06.000Z", + ); + }); + + it("gives undefined outside a repository", () => { + const bare = mkdtempSync(join(tmpdir(), "commit-dates-bare-")); + try { + expect(newestCommit(["a/one.ts"], { cwd: bare })).toBeUndefined(); + } finally { + rmSync(bare, { recursive: true, force: true }); + } + }); +}); + +describe("frontmatter line", () => { + it("writes the instant, or false", () => { + expect(lastUpdatedLine("2026-01-01T10:00:00.000Z")).toBe( + "lastUpdated: 2026-01-01T10:00:00.000Z", + ); + expect(lastUpdatedLine(undefined)).toBe("lastUpdated: false"); + }); + + it("goes at the end of the frontmatter", () => { + expect( + withLastUpdated( + '---\ntitle: "x"\n---\n\nbody\n', + "2026-01-01T00:00:00.000Z", + ), + ).toBe( + '---\ntitle: "x"\nlastUpdated: 2026-01-01T00:00:00.000Z\n---\n\nbody\n', + ); + }); + + it("refuses a page without frontmatter", () => { + expect(() => withLastUpdated("body", undefined)).toThrow(/frontmatter/); + }); +}); diff --git a/apps/dox/scripts/build-utils/index-pages.ts b/apps/dox/scripts/build-utils/index-pages.ts index a3cf8bdcd..1b8209336 100644 --- a/apps/dox/scripts/build-utils/index-pages.ts +++ b/apps/dox/scripts/build-utils/index-pages.ts @@ -18,6 +18,8 @@ export interface IndexedPage { name: string; url: string; description: string; + /** The file the page is made from, repo-relative. Dates the index pages that list it. */ + sourcePath?: string; } /** One public type: where it is documented, and what it is. */ @@ -26,6 +28,8 @@ export interface IndexedType { /** Its own page, or its anchor on its function's page. */ url: string; description: string; + /** The file that declares it, repo-relative. Dates the index pages that list it. */ + sourcePath?: string; } /** A type documented on a function's page, with the module that page is in. */ @@ -73,6 +77,8 @@ export interface IndexPage { /** The route it serves, with no trailing slash: `/reference/plain/calculate`. */ route: string; mdx: string; + /** The files of every page it lists, repo-relative: what its `lastUpdated` is dated from. */ + inputs: string[]; } /** Abbreviations whose full stop does not end a sentence. */ @@ -178,8 +184,23 @@ function hubPointer(industry: IndexedIndustry): string { return `The ${mdText(industry.label)} industry's own namespace. What it solves, and the guides and tools that show it, are on [${mdText(industry.label)}](/industries/${industry.id}/).`; } -function page(file: string, slug: string, lines: string[]): IndexPage { - return { file, route: `/${slug}`, mdx: lines.join("\n") }; +/** The files the listed items are made from, once each. */ +function inputsOf( + ...lists: ReadonlyArray> +): string[] { + const paths = lists.flatMap((list) => list.map((item) => item.sourcePath)); + return [ + ...new Set(paths.filter((path): path is string => path !== undefined)), + ].sort(); +} + +function page( + file: string, + slug: string, + lines: string[], + inputs: string[], +): IndexPage { + return { file, route: `/${slug}`, mdx: lines.join("\n"), inputs }; } /** @@ -238,7 +259,14 @@ export function renderIndexPages(input: IndexInput): IndexPage[] { lines.push(`- [Types](/reference/${TYPES_SECTION})`); lines.push(""); } - out.push(page("index.mdx", "reference", lines)); + out.push( + page( + "index.mdx", + "reference", + lines, + inputsOf(input.pages, input.sharedTypes, input.inlineTypes), + ), + ); } // /reference/types/ @@ -259,7 +287,12 @@ export function renderIndexPages(input: IndexInput): IndexPage[] { lines.push(""); } out.push( - page(`${TYPES_SECTION}/index.mdx`, `reference/${TYPES_SECTION}`, lines), + page( + `${TYPES_SECTION}/index.mdx`, + `reference/${TYPES_SECTION}`, + lines, + inputsOf(input.sharedTypes, input.inlineTypes), + ), ); } @@ -283,7 +316,14 @@ export function renderIndexPages(input: IndexInput): IndexPage[] { for (const p of byName(mods.get(mod)!)) lines.push(listItem(p)); lines.push(""); } - out.push(page(`${ns}/index.mdx`, `reference/${ns}`, lines)); + out.push( + page( + `${ns}/index.mdx`, + `reference/${ns}`, + lines, + inputsOf(modNames.flatMap((mod) => mods.get(mod)!)), + ), + ); } // /reference/// @@ -304,7 +344,14 @@ export function renderIndexPages(input: IndexInput): IndexPage[] { for (const t of byName(held)) lines.push(listItem(t)); lines.push(""); } - out.push(page(`${ns}/${mod}/index.mdx`, `reference/${ns}/${mod}`, lines)); + out.push( + page( + `${ns}/${mod}/index.mdx`, + `reference/${ns}/${mod}`, + lines, + inputsOf(mods.get(mod)!, held), + ), + ); } } diff --git a/apps/dox/scripts/build-utils/industry-pages.ts b/apps/dox/scripts/build-utils/industry-pages.ts index 739949bb4..2c9a9bd8b 100644 --- a/apps/dox/scripts/build-utils/industry-pages.ts +++ b/apps/dox/scripts/build-utils/industry-pages.ts @@ -44,6 +44,12 @@ export const HUB_SECTIONS = [ export type HubSection = (typeof HUB_SECTIONS)[number]["section"]; +/** The file that declares the industries: their labels, definitions, namespaces and modules. */ +export const INDUSTRY_DECLARATIONS = "apps/dox/src/data/industries.json"; + +/** The file that holds the text of a hub: what the industry is and what its functions solve. */ +export const INDUSTRY_OVERVIEW_TEXT = "apps/dox/src/lib/industry-overview.ts"; + /** A guide, tool, scenario or mistakes page, as its frontmatter states it. */ export interface HubSectionPage { section: HubSection; @@ -52,6 +58,8 @@ export interface HubSectionPage { title: string; description: string; industries: readonly string[]; + /** The page's file, repo-relative. Dates the hub that lists it. */ + path?: string; } /** One generated file under `src/content/docs/industries/`. */ @@ -59,6 +67,8 @@ export interface HubFile { /** `index.mdx` or `.mdx`. */ file: string; mdx: string; + /** The files the page states, repo-relative: what its `lastUpdated` is dated from. */ + inputs: string[]; } export interface HubInput { @@ -234,7 +244,22 @@ function renderHub( } lines.push(""); } - return { file: `${industry.id}.mdx`, mdx: lines.join("\n") }; + const members = HUB_SECTIONS.flatMap(({ section }) => + input.sectionPages.filter( + (p) => p.section === section && p.industries.includes(industry.id), + ), + ); + const inputs = [ + INDUSTRY_DECLARATIONS, + INDUSTRY_OVERVIEW_TEXT, + ...reachable.map((p) => p.sourcePath), + ...members.map((p) => p.path), + ].filter((path): path is string => path !== undefined); + return { + file: `${industry.id}.mdx`, + mdx: lines.join("\n"), + inputs: [...new Set(inputs)].sort(), + }; } /** `/industries/`: every industry, with the namespace it owns and the modules it draws on. */ @@ -262,7 +287,11 @@ function renderIndex(industries: readonly HubIndustry[]): HubFile { lines.push(parts.join(" ")); } lines.push(""); - return { file: "index.mdx", mdx: lines.join("\n") }; + return { + file: "index.mdx", + mdx: lines.join("\n"), + inputs: [INDUSTRY_DECLARATIONS], + }; } /** The index and one page per industry, in declared order. */ diff --git a/apps/dox/scripts/deploy-smoke.mjs b/apps/dox/scripts/deploy-smoke.mjs index 1f7dbe322..ff3e1b894 100644 --- a/apps/dox/scripts/deploy-smoke.mjs +++ b/apps/dox/scripts/deploy-smoke.mjs @@ -15,11 +15,17 @@ * * The whole set is retried up to 6 times, 10 s apart, for route propagation. The exit code * is 1 with a table of failures when the last attempt still fails. It does not roll back. + * + * `DOX_SMOKE_LOCAL=http://localhost:8787` runs only the crawl-hygiene rows (`_headers` and the 404 + * page) against a local `wrangler dev` that serves the built `dist`. The redirect rows need the + * live hosts and are skipped. */ import { readFileSync } from "node:fs"; -import { request } from "node:https"; +import { request as httpRequest } from "node:http"; +import { request as httpsRequest } from "node:https"; -const ND = "https://northguild.dev"; +const LOCAL = process.env.DOX_SMOKE_LOCAL?.replace(/\/$/, ""); +const ND = LOCAL ?? "https://northguild.dev"; const WD = "https://gmt-dox.northguild.workers.dev"; const ATTEMPTS = 6; const WAIT_MS = 10_000; @@ -33,6 +39,7 @@ const NAV = { /** One request, no redirect following. Resolves to `{ status, location, type, headers, body }`. */ function send(method, url, { headers = {}, body } = {}) { return new Promise((resolve, reject) => { + const request = url.startsWith("http:") ? httpRequest : httpsRequest; const req = request( url, { @@ -115,6 +122,77 @@ const hop = (rows, label, from, to, { headers, final = 200 } = {}) => steps: [{ status: 301, location: to }, { status: final }], }); +/** The meta tag that asks a crawler not to index a page. */ +const NOINDEX_META = /]*name="robots"[^>]*content="[^"]*noindex/i; + +/** + * The rows for the headers in `src/assets-root/_headers` and for the 404 page. `_headers` rules are + * joined with a comma when several match, so the hashed-asset row wants the one `immutable` value. + */ +async function crawlRows() { + const rows = []; + const noindex = ({ headers }) => + headers["x-robots-tag"] === "noindex" + ? undefined + : `x-robots-tag is ${headers["x-robots-tag"]}, not noindex`; + rows.push( + { + label: "noindex install.md", + url: `${ND}/gmt/install.md`, + steps: [{ status: 200, check: noindex }], + }, + { + label: "noindex llms.txt", + url: `${ND}/gmt/llms.txt`, + steps: [{ status: 200, check: noindex }], + }, + { + label: "no noindex header on /gmt/", + url: `${ND}/gmt/`, + steps: [ + { + status: 200, + check: ({ headers }) => + headers["x-robots-tag"] === undefined + ? undefined + : `x-robots-tag is ${headers["x-robots-tag"]}`, + }, + ], + }, + ); + // The hashed script a page names. Its header is the one `_headers` rule, not the default joined to it. + const home = await send("GET", `${ND}/gmt/`); + const script = /["'](\/gmt\/_astro\/[^"']+\.js)["']/.exec(home.body)?.[1]; + rows.push({ + label: "immutable _astro script", + url: script ? `${ND}${script}` : `${ND}/gmt/`, + steps: [ + { + status: 200, + check: ({ headers }) => + script === undefined + ? "no /gmt/_astro/*.js named in /gmt/" + : headers["cache-control"] === "public, max-age=31536000, immutable" + ? undefined + : `cache-control is ${headers["cache-control"]}`, + }, + ], + }); + rows.push({ + label: "404 page asks not to be indexed", + url: `${ND}/gmt/does-not-exist/`, + steps: [ + { + status: 404, + type: "text/html", + check: ({ body }) => + NOINDEX_META.test(body) ? undefined : "no noindex meta", + }, + ], + }); + return rows; +} + async function buildRows() { const rows = []; const add = (r) => rows.push(r); @@ -591,12 +669,12 @@ async function buildRows() { }, ], }); - return rows; + return [...rows, ...(await crawlRows())]; } async function attempt() { const failures = []; - for (const row of await buildRows()) { + for (const row of LOCAL ? await crawlRows() : await buildRows()) { let problem; try { problem = await run(row); diff --git a/apps/dox/scripts/dist-base.test.ts b/apps/dox/scripts/dist-base.test.ts index b4f1e1715..9276cc841 100644 --- a/apps/dox/scripts/dist-base.test.ts +++ b/apps/dox/scripts/dist-base.test.ts @@ -67,15 +67,52 @@ function built(): { root: string; pages: string } | null { } describe("the built site keeps the /gmt base", () => { - it("dist holds exactly gmt/ and _redirects", () => { + it("dist holds exactly gmt/, _headers and _redirects", () => { const b = built(); if (b === null) return; const { root, pages } = b; - expect(readdirSync(root).sort()).toEqual(["_redirects", "gmt"]); + expect(readdirSync(root).sort()).toEqual(["_headers", "_redirects", "gmt"]); expect(existsSync(resolve(pages, "index.html"))).toBe(true); expect(existsSync(resolve(pages, "404.html"))).toBe(true); expect(existsSync(resolve(root, "_redirects"))).toBe(true); expect(existsSync(resolve(pages, "_redirects"))).toBe(false); + expect(existsSync(resolve(root, "_headers"))).toBe(true); + expect(existsSync(resolve(pages, "_headers"))).toBe(false); + }); + + it("every _headers rule sits under /gmt/", () => { + const b = built(); + if (b === null) return; + // A rule path starts a line; its headers are indented, and a comment starts with `#`. + const paths = readFileSync(resolve(b.root, "_headers"), "utf8") + .split("\n") + .filter((line) => line !== "" && !/^\s/.test(line) && line[0] !== "#"); + expect(paths.length).toBeGreaterThan(0); + expect(paths.filter((path) => !path.startsWith("/gmt/"))).toEqual([]); + }); + + it("every file under _astro/ has a content hash in its name, so its immutable header is true", () => { + const b = built(); + if (b === null) return; + const names = readdirSync(resolve(b.pages, "_astro")); + expect(names.length).toBeGreaterThan(0); + // `name..ext`: Vite's hash is at least five characters of the URL-safe alphabet. + expect( + names.filter((name) => !/^.+\.[A-Za-z0-9_-]{5,}\.[a-z0-9]+$/.test(name)), + ).toEqual([]); + }); + + it("the only .txt files are the llms files, which the noindex rule covers", () => { + const b = built(); + if (b === null) return; + const txt = walk(b.pages, (n) => n.endsWith(".txt")) + .map((file) => relative(b.pages, file).split(sep).join("/")) + .sort(); + expect( + txt.filter((file) => !/(^|\/)llms(-full)?\.txt$/.test(file)), + ).toEqual([]); + expect(txt).toContain("llms.txt"); + expect(txt).toContain("llms-full.txt"); }); it("no HTML page carries a URL without the base", () => { diff --git a/apps/dox/scripts/head-tags.test.ts b/apps/dox/scripts/head-tags.test.ts index 59b66cc28..2bf15f112 100644 --- a/apps/dox/scripts/head-tags.test.ts +++ b/apps/dox/scripts/head-tags.test.ts @@ -1,6 +1,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync } from "node:fs"; import { relative, resolve } from "node:path"; +import { footerDate } from "../src/lib/sitemap-lastmod"; import { SITE_URL } from "../src/lib/site"; import { TITLE_SUFFIX } from "../src/lib/head-tags"; import { scanHead, type HeadScan } from "./build-utils/head-tags-scan"; @@ -295,6 +296,87 @@ describe("head tags of the built site", () => { expectNone(failures); }); + it("gives every sitemap URL the date in its page's footer, and none to a page without one", () => { + const dist = distDirOrSkip(); + if (dist === null) return; + const sitemap = readFileSync(resolve(dist, "sitemap-0.xml"), "utf8"); + const entries = [...sitemap.matchAll(/([\s\S]*?)<\/url>/g)].map( + (m) => ({ + loc: /([^<]+)<\/loc>/.exec(m[1])?.[1], + lastmod: /([^<]+)<\/lastmod>/.exec(m[1])?.[1], + }), + ); + expect(entries.length).toBeGreaterThan(100); + const byUrl = new Map( + builtPages(dist).map((page) => [ + `${SITE_URL}/${page.route}${page.route ? "/" : ""}`, + footerDate(page.html), + ]), + ); + const failures: string[] = []; + let dated = 0; + for (const { loc, lastmod } of entries) { + if (loc === undefined || !byUrl.has(loc)) { + failures.push(`${loc}: no built page`); + continue; + } + const footer = byUrl.get(loc); + if (lastmod !== footer) { + failures.push(`${loc}: lastmod ${lastmod}, footer ${footer}`); + } + if (lastmod !== undefined) dated += 1; + } + expect(dated).toBeGreaterThan(100); + expectNone(failures); + }); + + it("dates a reference page from its source file's last commit", () => { + const dist = distDirOrSkip(); + if (dist === null) return; + const html = readFileSync( + resolve(dist, "reference/zoned/calculate/startOfZoned/index.html"), + "utf8", + ); + // `%cd` with `format-local` follows TZ, so TZ=UTC gives the UTC instant in the page's format + // (`%cI` would keep the commit's stored offset). + const committed = execFileSync( + "git", + [ + "log", + "-1", + "--date=format-local:%Y-%m-%dT%H:%M:%S.000Z", + "--format=%cd", + "--", + "packages/gmt/src/zoned/calculate/startOfZoned.ts", + ], + { + cwd: repoRoot, + encoding: "utf8", + env: { ...process.env, TZ: "UTC" }, + }, + ).trim(); + expect(committed).toMatch(/Z$/); + expect(footerDate(html)).toBe(committed); + const sitemap = readFileSync(resolve(dist, "sitemap-0.xml"), "utf8"); + const url = `${SITE_URL}/reference/zoned/calculate/startOfZoned/`; + const entry = new RegExp( + `${url}(?:([^<]+))?`, + ).exec(sitemap); + expect(entry).not.toBeNull(); + expect(entry![1]).toBe(committed); + }); + + it("asks that the 404 page not be indexed, and gives it no canonical link or sitemap entry", () => { + const dist = distDirOrSkip(); + if (dist === null) return; + const scan = scanHead(readFileSync(resolve(dist, "404.html"), "utf8")); + expect(scan.noindex).toBe(true); + expect(scan.canonical).toBeUndefined(); + const sitemap = readFileSync(resolve(dist, "sitemap-0.xml"), "utf8"); + const locs = [...sitemap.matchAll(/([^<]+)<\/loc>/g)].map((m) => m[1]); + expect(locs.filter((loc) => loc.includes("404"))).toEqual([]); + }); + it("gives no page an edit link", () => { const dist = distDirOrSkip(); if (dist === null) return; diff --git a/apps/dox/src/assets-root/_headers b/apps/dox/src/assets-root/_headers new file mode 100644 index 000000000..5892a59b0 --- /dev/null +++ b/apps/dox/src/assets-root/_headers @@ -0,0 +1,14 @@ +# Cloudflare reads this file from the root of the assets directory (`dist/_headers`); `copyRedirects` +# puts it there. Assets are served before the Worker, so the headers of every page and file come from here. + +# Hashed build output: the file name changes with its content, so a cached copy is never stale. +/gmt/_astro/* + Cache-Control: public, max-age=31536000, immutable + +# The `.md` twin of a page repeats the page; the HTML page is the one to index. +/gmt/*.md + X-Robots-Tag: noindex + +# `llms.txt`, `llms-full.txt` and the per-namespace `llms.txt` files repeat the pages; they are for agents, not for a results page. +/gmt/*.txt + X-Robots-Tag: noindex diff --git a/apps/dox/src/lib/copy-redirects.ts b/apps/dox/src/lib/copy-redirects.ts index 6dcef3d02..44fbd5e30 100644 --- a/apps/dox/src/lib/copy-redirects.ts +++ b/apps/dox/src/lib/copy-redirects.ts @@ -1,31 +1,42 @@ /** - * Copies the generated `_redirects` to `dist/_redirects` after a build. + * Copies the generated `_redirects` and the tracked `_headers` to `dist/` after a build. * - * Cloudflare reads `_redirects` from the root of the assets directory (`dist/`), but Astro's - * `outDir` is `dist/gmt/`, so a file in `public/` would land at `dist/gmt/_redirects`, where - * nothing reads it. `scripts/build-reference.ts` writes `src/generated/_redirects`; this hook - * puts it one level above `outDir`. Build-only: `astro dev` never runs `astro:build:done`. + * Cloudflare reads both from the root of the assets directory (`dist/`), but Astro's `outDir` is + * `dist/gmt/`, so a file in `public/` would land at `dist/gmt/_redirects`, where nothing reads it. + * `scripts/build-reference.ts` writes `src/generated/_redirects`; `src/assets-root/_headers` is + * kept in the tree. This hook puts each one level above `outDir`. Build-only: `astro dev` never + * runs `astro:build:done`. */ import type { AstroIntegration } from "astro"; import { copyFileSync, existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; -const source = fileURLToPath( - new URL("../generated/_redirects", import.meta.url), -); +/** Each file to copy: where it is kept, the name it has in `dist/`, and how to produce it. */ +const files = [ + { + name: "_redirects", + source: fileURLToPath(new URL("../generated/_redirects", import.meta.url)), + fix: "Run `pnpm run generate` before building.", + }, + { + name: "_headers", + source: fileURLToPath(new URL("../assets-root/_headers", import.meta.url)), + fix: "It is tracked in the repository; restore it.", + }, +] as const; export function copyRedirects(): AstroIntegration { return { name: "gmt-copy-redirects", hooks: { "astro:build:done": ({ dir }) => { - // A build without `generate` must not deploy without its redirects. - if (!existsSync(source)) { - throw new Error( - `[copy-redirects] ${source} is missing. Run \`pnpm run generate\` before building.`, - ); + // A build without `generate` must not deploy without its redirects, nor one without its headers. + for (const { name, source, fix } of files) { + if (!existsSync(source)) { + throw new Error(`[copy-redirects] ${source} is missing. ${fix}`); + } + copyFileSync(source, fileURLToPath(new URL(`../${name}`, dir))); } - copyFileSync(source, fileURLToPath(new URL("../_redirects", dir))); }, }, }; diff --git a/apps/dox/src/lib/head-tags.test.ts b/apps/dox/src/lib/head-tags.test.ts index 90664b79a..4bebc2f50 100644 --- a/apps/dox/src/lib/head-tags.test.ts +++ b/apps/dox/src/lib/head-tags.test.ts @@ -4,6 +4,7 @@ import { jsonLd, ogImageKey, pageTitle, + removeHead, TITLE_SUFFIX, upsertHead, type HeadEntry, @@ -304,3 +305,35 @@ describe("isHomeId", () => { expect(isHomeId("guides")).toBe(false); }); }); + +describe("removeHead", () => { + const head: HeadEntry[] = [ + { tag: "title", content: "Not found" }, + { tag: "link", attrs: { rel: "canonical", href: "https://x/gmt/404/" } }, + { tag: "link", attrs: { rel: "sitemap", href: "/gmt/sitemap-index.xml" } }, + { tag: "meta", attrs: { name: "robots", content: "noindex" } }, + ]; + + it("drops the entries of the tag that carry the attributes", () => { + expect(removeHead(head, "link", { rel: "canonical" })).toEqual([ + head[0], + head[2], + head[3], + ]); + }); + + it("keeps entries of other tags and entries that differ in an attribute", () => { + expect(removeHead(head, "meta", { rel: "canonical" })).toEqual(head); + expect(removeHead(head, "link", { rel: "alternate" })).toEqual(head); + }); + + it("does not change the list it is given", () => { + const copy = structuredClone(head); + removeHead(head, "link", { rel: "canonical" }); + expect(head).toEqual(copy); + }); + + it("leaves a head with no such entry as it is", () => { + expect(removeHead([], "link", { rel: "canonical" })).toEqual([]); + }); +}); diff --git a/apps/dox/src/lib/head-tags.ts b/apps/dox/src/lib/head-tags.ts index 56111068c..cb403598a 100644 --- a/apps/dox/src/lib/head-tags.ts +++ b/apps/dox/src/lib/head-tags.ts @@ -269,3 +269,22 @@ export function upsertHead(head: HeadEntry[], entry: HeadEntry): HeadEntry[] { function sameEntry(a: HeadEntry, b: HeadEntry): boolean { return JSON.stringify(a) === JSON.stringify(b); } + +/** + * `head` without the entries of `tag` whose attributes include every one in `attrs`: + * `removeHead(head, "link", { rel: "canonical" })` drops the canonical link and keeps the other + * links. + */ +export function removeHead( + head: HeadEntry[], + tag: HeadEntry["tag"], + attrs: Record, +): HeadEntry[] { + return head.filter( + (entry) => + entry.tag !== tag || + !Object.entries(attrs).every( + ([key, value]) => entry.attrs?.[key] === value, + ), + ); +} diff --git a/apps/dox/src/lib/sitemap-lastmod.test.ts b/apps/dox/src/lib/sitemap-lastmod.test.ts new file mode 100644 index 000000000..d530c5d94 --- /dev/null +++ b/apps/dox/src/lib/sitemap-lastmod.test.ts @@ -0,0 +1,74 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { builtPage, footerDate, sitemapLastmod } from "./sitemap-lastmod"; + +const DATE = "2026-10-19T05:35:38.000Z"; +const dated = `

Last updated:

`; +const undated = `
body
`; + +let out = ""; + +function page(path: string, html: string) { + mkdirSync(join(out, path), { recursive: true }); + writeFileSync(join(out, path, "index.html"), html); +} + +beforeAll(() => { + out = mkdtempSync(join(tmpdir(), "sitemap-lastmod-")); + page("", dated); + page("install", undated); + page("guides/a", dated); +}); + +afterAll(() => { + rmSync(out, { recursive: true, force: true }); +}); + +describe("footerDate", () => { + it("reads the time in the footer, not one in the body", () => { + expect(footerDate(dated)).toBe(DATE); + }); + + it("is undefined for a footer without a date, or a page without a footer", () => { + expect(footerDate(undated)).toBeUndefined(); + expect(footerDate(``)).toBeUndefined(); + }); +}); + +describe("builtPage", () => { + it("maps a sitemap URL to its built file", () => { + expect(builtPage(out, "https://northguild.dev/gmt/")).toBe( + join(out, "index.html"), + ); + expect(builtPage(out, "https://northguild.dev/gmt/guides/a/")).toBe( + join(out, "guides", "a", "index.html"), + ); + }); + + it("is undefined outside the base or without a file", () => { + expect(builtPage(out, "https://northguild.dev/")).toBeUndefined(); + expect(builtPage(out, "https://northguild.dev/gmtx/")).toBeUndefined(); + expect( + builtPage(out, "https://northguild.dev/gmt/missing/"), + ).toBeUndefined(); + }); +}); + +describe("sitemapLastmod", () => { + it("sets lastmod to the footer date", () => { + expect( + sitemapLastmod(out, { url: "https://northguild.dev/gmt/guides/a/" }), + ).toEqual({ url: "https://northguild.dev/gmt/guides/a/", lastmod: DATE }); + }); + + it("sets none for a page without a footer date, and drops one it was given", () => { + expect( + sitemapLastmod(out, { + url: "https://northguild.dev/gmt/install/", + lastmod: "2020-01-01", + }), + ).toEqual({ url: "https://northguild.dev/gmt/install/" }); + }); +}); diff --git a/apps/dox/src/lib/sitemap-lastmod.ts b/apps/dox/src/lib/sitemap-lastmod.ts new file mode 100644 index 000000000..8d028ecfd --- /dev/null +++ b/apps/dox/src/lib/sitemap-lastmod.ts @@ -0,0 +1,49 @@ +/** + * The `` of a sitemap URL: the date in the footer of the page it names. + * + * Starlight writes a page's last-updated date into its footer as + * `