diff --git a/.github/social-preview.png b/.github/social-preview.png deleted file mode 100644 index 65b05425c..000000000 Binary files a/.github/social-preview.png and /dev/null differ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e396333ff..860acfb91 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -280,17 +280,16 @@ jobs: # DOX_DIST_REQUIRED turns those gates' "no dist, nothing to check" skip into a failure, but # only here, where the step above guarantees a build. Keyed to `CI` it would fire in the # Tests job too, which runs the same suite on three Node versions and does not build the site. - # `dist-base.test.ts` reads the same build for the /gmt base: a root URL without `/gmt` in any - # HTML, CSS, script, `.md`, `llms*.txt`, sitemap or `_redirects` fails here. - # `head-tags.test.ts` checks each built page's title, description and share tags. - # `select-options.test.ts` checks no built select repeats an option value or label. - # `gates/registry.test.ts` checks the gates' sample pages exist in it, and `a11y-tab-walk`'s - # page contract, which lists a subset of the built pages. - - name: "Built site: text surfaces, the /gmt base, head tags, select options and the gate pages" + # `test:dist` (apps/dox/scripts/dist-tests.mjs) runs every Node test that imports + # `scripts/dist-dir.ts`, found by that rule rather than from a list, so a new built-site test + # cannot be left out: a hand-kept list here once missed five of them. Among them, the /gmt + # base, each page's head tags and share cards, the sidebar's reach, select options and the + # gates' sample pages. + - name: "Built site: every test that reads apps/dox/dist" if: contains(fromJSON(env.CHECKS), 'dox-dist') env: DOX_DIST_REQUIRED: "1" - run: pnpm --filter dox exec vitest run scripts/llms.test.ts scripts/dist-base.test.ts scripts/head-tags.test.ts scripts/select-options.test.ts scripts/gates/registry.test.ts + run: pnpm --filter dox run test:dist # No table on a built page scrolls sideways at 1440 px. The check opens every built page with a # table in Chromium, so it needs the browser the Dox gates job installs. diff --git a/apps/dox/assets/share/README.md b/apps/dox/assets/share/README.md new file mode 100644 index 000000000..480b94cbd --- /dev/null +++ b/apps/dox/assets/share/README.md @@ -0,0 +1,21 @@ +# Share images + +Upload-ready images for the places that take a picture by hand. + +| File | Size | Use | +| --------------------------- | ---------- | ----------------------------------------------------------------------------- | +| `github-social-preview.png` | 1280 x 640 | The repository's social preview (Settings, Social preview). | +| `og-default-1200x630.png` | 1200 x 630 | The site card: the same image as `/og/site.png`. For profiles and listings. | +| `earth-1200x630.png` | 1200 x 630 | The artwork alone, with no text: sky, Earth and the cyan edge. | + +The Earth is centred on the midpoint of Helsinki and Isafjordur, and painted in the site's colours. + +Regenerate all three, with the same bytes each time: + +```sh +pnpm --filter dox run social-preview +``` + +This folder is outside `src/` and `public/`, so the site build does not publish it. + +Imagery: NASA Earth Observatory, Blue Marble Next Generation (public domain). diff --git a/apps/dox/assets/share/earth-1200x630.png b/apps/dox/assets/share/earth-1200x630.png new file mode 100644 index 000000000..6d20cfaf7 Binary files /dev/null and b/apps/dox/assets/share/earth-1200x630.png differ diff --git a/apps/dox/assets/share/github-social-preview.png b/apps/dox/assets/share/github-social-preview.png new file mode 100644 index 000000000..9a21786ab Binary files /dev/null and b/apps/dox/assets/share/github-social-preview.png differ diff --git a/apps/dox/assets/share/og-default-1200x630.png b/apps/dox/assets/share/og-default-1200x630.png new file mode 100644 index 000000000..337c0089e Binary files /dev/null and b/apps/dox/assets/share/og-default-1200x630.png differ diff --git a/apps/dox/astro.config.mjs b/apps/dox/astro.config.mjs index d9584ae7f..77b8e04d9 100644 --- a/apps/dox/astro.config.mjs +++ b/apps/dox/astro.config.mjs @@ -17,6 +17,8 @@ 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 { versionOgImages } from "./src/lib/og-image-version.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 +30,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), ); @@ -139,6 +144,9 @@ export default defineConfig({ copyRedirects(), // Build only: drops a widget's stylesheet link from the pages that do not show the widget. pruneWidgetCss(), + // Build only: puts ?v= on og:image and twitter:image. It stays above starlight(), + // whose Pagefind step runs on the same hook, so Pagefind and the dist gates read the final HTML. + versionOgImages(), react(), starlight({ title: "@northguild/gmt", @@ -204,15 +212,6 @@ export default defineConfig({ blocking: "render", }, }, - // DOX-A3b: discoverability — let LLMs find the llms.txt surface - { - tag: "link", - attrs: { - rel: "alternate", - type: "text/plain", - href: withBase("/llms.txt"), - }, - }, /* Raster fallbacks for the SVG favicon above, generated from it by `pnpm run favicons`. Starlight sorts its own `rel="shortcut icon"` entry *after* extra icon links precisely so the SVG wins wherever @@ -299,9 +298,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/package.json b/apps/dox/package.json index 35f27996b..4f7404bca 100644 --- a/apps/dox/package.json +++ b/apps/dox/package.json @@ -17,6 +17,7 @@ "check": "pnpm run generate && astro sync && astro check", "typecheck": "pnpm run check", "test": "pnpm run generate && vitest run", + "test:dist": "node scripts/dist-tests.mjs", "lint": "oxlint && stylelint \"src/**/*.{css,astro}\"", "reference:export": "tsx ./scripts/export-reference.ts", "docs-check": "tsx ./scripts/check-reference-docs.ts", @@ -56,7 +57,6 @@ "@tanstack/virtual-core": "^3.17.8", "ai": "^7.0.95", "astro": "7.4.2", - "astro-og-canvas": "0.13.2", "canvaskit-wasm": "^0.42.0", "class-variance-authority": "^0.7.1", "clsx": "2.1.1", @@ -74,6 +74,7 @@ "radix-ui": "^1.6.7", "react": "19.3.0", "react-dom": "19.3.0", + "sharp": "0.35.5", "shiki": "^4.4.3", "streamdown": "^2.6.0", "tailwind-merge": "3.6.0", diff --git a/apps/dox/scripts/a11y-tab-walk.mjs b/apps/dox/scripts/a11y-tab-walk.mjs index 052b6bd0b..54980d001 100644 --- a/apps/dox/scripts/a11y-tab-walk.mjs +++ b/apps/dox/scripts/a11y-tab-walk.mjs @@ -16,8 +16,8 @@ * * At 390 the mobile menu is opened only when the walk reaches its toggle; the menu's links count as * candidates only once it is open. `/dox/` is walked as it opens and once more with a widget in the - * rail. The pages are every page outside `/reference/`, plus the first function page and the first - * type page: reference pages share one template and each carries the full sidebar. + * rail. The pages are every page outside `/reference/`, plus the first function page of each + * namespace and the first type page: a reference page carries only its own namespace's tree. * * Usage (a built site served, as `pnpm --filter dox gates --only a11y-tab-walk` does): * node scripts/a11y-tab-walk.mjs [--base http://127.0.0.1:48291/gmt] [--browsers chromium,webkit] diff --git a/apps/dox/scripts/build-changelog.mjs b/apps/dox/scripts/build-changelog.mjs index ded67f0d3..44fca1498 100644 --- a/apps/dox/scripts/build-changelog.mjs +++ b/apps/dox/scripts/build-changelog.mjs @@ -2,10 +2,14 @@ /** * Generate the changelog pages from each package's CHANGELOG.md and the release tags. * - * Emits one page per package that has a CHANGELOG.md: src/content/docs/changelog/index.md for - * `@northguild/gmt` and changelog/.md for each other package. The package list is read from - * the directory, so a new package with a changelog gets a page with no change here (the sidebar - * test then names the missing link). A version's scope (current or + * Emits, per package that has a CHANGELOG.md, an index page and one page per release line + * (`major.minor`): src/content/docs/changelog/index.md and changelog/.md for + * `@northguild/gmt`, changelog//index.md and changelog//.md for each other + * package. A line's page holds its release notes, so no page nears the 1 MB a Messages preview + * reads; the index lists the lines and repeats no note. The package list is read from the + * directory, so a new package with a changelog gets its pages with no change here (the sidebar + * test then names the missing link). Any .md in the output directory that a run did not write is + * deleted. A version's scope (current or * the retired `@burglekitt`) and its release date come from its git tag, read in one call; the * transform is in lib/changelog.mjs. This script never writes the CHANGELOG.md files; they are * the release record. The emitted page is gitignored. @@ -25,18 +29,22 @@ import { mkdirSync, readdirSync, readFileSync, + rmSync, writeFileSync, } from "node:fs"; import { execFileSync } from "node:child_process"; -import { dirname, resolve } from "node:path"; +import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { loadGmt } from "../../../scripts/lib/gmt.mjs"; import { describePage, groupReleases, + lineSlug, parseChangelog, parseTags, - renderPage, + releaseLines, + renderIndexPage, + renderLinePage, } from "./lib/changelog.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -50,7 +58,12 @@ const PACKAGES = readdirSync(resolve(repoRoot, "packages")) existsSync(resolve(repoRoot, "packages", dir, "CHANGELOG.md")), ) .sort((a, b) => (a === "gmt" ? -1 : b === "gmt" ? 1 : a.localeCompare(b))) - .map((dir) => ({ dir, out: dir === "gmt" ? "index.md" : `${dir}.md` })); + .map((dir) => ({ + dir, + // The directory under changelog/ and the route of the package's index page. + folder: dir === "gmt" ? "" : dir, + route: dir === "gmt" ? "/changelog/" : `/changelog/${dir}/`, + })); /** Where a retired-scope plate sends the reader to install: the library, or a plugin's guide. */ const installLinkFor = (dir) => @@ -79,7 +92,24 @@ try { ); mkdirSync(outDir, { recursive: true }); - for (const { dir, out } of PACKAGES) { + /** Absolute paths of every page this run keeps. */ + const kept = new Set(); + /** Idempotent write: don't bump mtime when nothing changed. Returns whether it wrote. */ + const write = (path, source) => { + kept.add(path); + mkdirSync(dirname(path), { recursive: true }); + let previous = ""; + try { + previous = readFileSync(path, "utf8"); + } catch { + previous = ""; + } + if (previous === source) return false; + writeFileSync(path, source); + return true; + }; + + for (const { dir, folder, route } of PACKAGES) { const sourcePath = `packages/${dir}/CHANGELOG.md`; const pkgName = JSON.parse( readFileSync(resolve(repoRoot, "packages", dir, "package.json"), "utf8"), @@ -106,35 +136,67 @@ try { lastUpdated = ""; } - const source = renderPage({ + const title = dir === "gmt" ? "Changelog" : `Changelog: ${dir}`; + const shared = { pkgName, - title: dir === "gmt" ? "Changelog" : `Changelog: ${dir}`, - description: describePage(pkgName, groups), groups, formatDate: (stamp) => gmt.parseDateFromUtc(stamp), sourceUrl: `${SOURCE_BASE}/${sourcePath}`, sourcePath, installLink: installLinkFor(dir), - lastUpdated, - }); + route, + }; - // Idempotent write: don't bump mtime when nothing changed. - const outPath = resolve(outDir, out); - let previous = ""; - try { - previous = readFileSync(outPath, "utf8"); - } catch { - previous = ""; + let written = write( + resolve(outDir, folder, "index.md"), + renderIndexPage({ + ...shared, + title, + description: describePage(pkgName, groups), + lastUpdated, + }), + ); + const lines = new Set( + releaseLines(groups).flatMap((group) => + group.lines.map(({ line }) => line), + ), + ); + for (const line of lines) { + const changed = write( + resolve(outDir, folder, `${lineSlug(line)}.md`), + renderLinePage({ + ...shared, + title: `${title} ${line}`, + indexTitle: title, + line, + }), + ); + written ||= changed; } - if (previous !== source) writeFileSync(outPath, source); const untagged = groups .flatMap((group) => group.releases) .filter((release) => release.stamp === null).length; console.log( - `changelog: ${dir} ${versions.length} versions, ${groups.length} scopes, ${untagged} untagged (${previous === source ? "unchanged" : "written"})`, + `changelog: ${dir} ${versions.length} versions, ${groups.length} scopes, ${lines.size} line pages, ${untagged} untagged (${written ? "written" : "unchanged"})`, ); } + + // Delete what this run did not write: a page of a line that no longer exists, or the + // single-file layout of an earlier build. + const sweep = (directory) => { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const path = resolve(directory, entry.name); + if (entry.isDirectory()) { + sweep(path); + if (readdirSync(path).length === 0) rmSync(path, { recursive: true }); + } else if (entry.name.endsWith(".md") && !kept.has(path)) { + rmSync(path); + console.log(`changelog: removed stale ${relative(outDir, path)}`); + } + } + }; + sweep(outDir); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); 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-og-earth.ts b/apps/dox/scripts/build-og-earth.ts new file mode 100644 index 000000000..15348bf1a --- /dev/null +++ b/apps/dox/scripts/build-og-earth.ts @@ -0,0 +1,348 @@ +#!/usr/bin/env tsx +/** + * Draw the Earth of the share card: `src/assets/og-earth.webp`, 1200 by 630, a large Earth whose + * limb arcs across the lower part of the card on a dark sky, with no text. `src/lib/og-art.ts` lays + * the title and the description on top of it, above the limb. + * + * Run by hand, never in `build`: `pnpm --filter dox exec tsx scripts/build-og-earth.ts`. The same + * run always writes the same bytes: a fixed instant, a fixed camera, a fixed seed for the stars and + * no clock. The sphere is the Blue Marble texture (`public/earth-blue-marble.webp`) projected through + * the same pinhole camera as the home hero (6.61 Earth radii), lit by the Sun at the fixed instant, + * with a cyan rim of air. The globe engine itself is not captured: it draws zone pins and labels + * over the planet, which a share card does not want. + * + * The middle of the visible Earth (x 600, halfway between the limb's crest and the card's bottom + * edge) is the great-circle midpoint of Helsinki and Isafjordur, in the Norwegian Sea, north up. + * The colours are the site's: the photograph only says where land, ice and sea are, and a + * tritone read from `src/styles/gmt-tokens.css` paints them (sea in the void-to-teal range, land + * from teal to ice-dim, ice caps and snow in ice). + * + * Imagery: NASA Earth Observatory, Blue Marble Next Generation, public domain (see + * `scripts/prepare-globe-imagery.py` and `context/dox/built.md`, Earth imagery). Resampled and + * lit here; no NASA logo. + */ +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { getCanvasKit } from "../src/lib/og-canvaskit"; + +const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +const WIDTH = 1200; +const HEIGHT = 630; +/** The hero's camera: distance from the Earth's centre, in Earth radii. */ +const CAMERA = 6.61; +/** + * The instant that sets the Sun: the June solstice at 11:46 UTC, with the Sun over 23.44 N and the + * longitude of the middle point (3.5 E, 180 - 15 x 11.766 h). The whole visible cap is then in + * daylight and the terminator lies 90 degrees away, behind both limbs. + */ +const SUN_LAT = 23.44; + +/** The two cities whose great-circle midpoint is the middle of the visible Earth. */ +const HELSINKI = { lat: 60.1699, lon: 24.9384 }; +const ISAFJORDUR = { lat: 66.075, lon: -23.124 }; + +/** The Earth's apparent radius in pixels and the pixel its centre sits on; the crest is at y 360. */ +const FRAME = { + radius: 900, + cx: 600, + cy: 1262, + /** Where the middle point sits on the card: x 600, halfway from the crest (y 360) to y 630. */ + target: { x: 600, y: 495 }, + /** Pixels kept free of stars: the text box. */ + clear: [280, 30, 920, 300], +} as const; + +const rad = (degrees: number) => (degrees * Math.PI) / 180; +type Vec = [number, number, number]; +const dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a: Vec, b: Vec): Vec => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +const norm = (a: Vec): Vec => { + const n = Math.hypot(...a); + return [a[0] / n, a[1] / n, a[2] / n]; +}; +const ecef = (lat: number, lon: number): Vec => [ + Math.cos(rad(lat)) * Math.cos(rad(lon)), + Math.cos(rad(lat)) * Math.sin(rad(lon)), + Math.sin(rad(lat)), +]; +const smooth = (a: number, b: number, x: number) => { + const t = Math.min(1, Math.max(0, (x - a) / (b - a))); + return t * t * (3 - 2 * t); +}; + +/** A colour token's value from the dark theme's block, the first definition in the file. */ +const tokens = readFileSync( + resolve(appRoot, "src/styles/gmt-tokens.css"), + "utf8", +); +const token = (name: string): Vec => { + const hit = new RegExp(`--gmt-${name}:\\s*#([0-9a-fA-F]{6})`).exec(tokens); + if (!hit) throw new Error(`token --gmt-${name} not found`); + const n = parseInt(hit[1], 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +}; +const mix = (a: Vec, b: Vec, t: number): Vec => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, +]; +const VOID = token("void"); +const SURFACE_2 = token("surface-2"); +const TEAL = token("teal"); +const CYAN = token("cyan"); +const ICE_DIM = token("ice-dim"); +const ICE = token("ice"); + +/** The great-circle midpoint of two places, as a unit vector. */ +const midpoint = ( + a: { lat: number; lon: number }, + b: { lat: number; lon: number }, +) => norm(ecef(a.lat, a.lon).map((v, i) => v + ecef(b.lat, b.lon)[i]) as Vec); + +async function main() { + const CanvasKit = await getCanvasKit(); + const encoded = readFileSync( + resolve(appRoot, "public/earth-blue-marble.webp"), + ); + const image = CanvasKit.MakeImageFromEncoded(encoded); + if (!image) throw new Error("cannot decode earth-blue-marble.webp"); + const texW = image.width(); + const texH = image.height(); + const texture = image.readPixels(0, 0, { + width: texW, + height: texH, + colorType: CanvasKit.ColorType.RGBA_8888, + alphaType: CanvasKit.AlphaType.Unpremul, + colorSpace: CanvasKit.ColorSpace.SRGB, + }) as Uint8Array; + + const sample = (lat: number, lon: number): Vec => { + const u = ((((lon + 180) / 360) % 1) + 1) % 1; + const v = Math.min(0.9999, Math.max(0, (90 - lat) / 180)); + const x = u * texW - 0.5; + const y = v * texH - 0.5; + const x0 = Math.floor(x); + const y0 = Math.max(0, Math.min(texH - 2, Math.floor(y))); + const fx = x - x0; + const fy = y - y0; + const out: Vec = [0, 0, 0]; + for (let c = 0; c < 3; c++) { + const at = (xx: number, yy: number) => + texture[(yy * texW + ((xx + texW) % texW)) * 4 + c]; + out[c] = + at(x0, y0) * (1 - fx) * (1 - fy) + + at(x0 + 1, y0) * fx * (1 - fy) + + at(x0, y0 + 1) * (1 - fx) * fy + + at(x0 + 1, y0 + 1) * fx * fy; + } + return out; + }; + + { + const { radius, cx, cy } = FRAME; + // The focal length that makes the limb's apparent radius `radius` pixels. + const focal = radius * Math.sqrt(CAMERA * CAMERA - 1); + const mid = midpoint(HELSINKI, ISAFJORDUR); + const midLat = (Math.asin(mid[2]) * 180) / Math.PI; + const midLon = (Math.atan2(mid[1], mid[0]) * 180) / Math.PI; + // The angle from the sub-camera point to the middle point that lands it FRAME.target.y high: + // sin(t) / (CAMERA - cos(t)) = rise / focal, solved by bisection (it rises with t). + const rise = (cy - FRAME.target.y) / focal; + let lo = 0; + let hi = Math.PI / 2; + for (let i = 0; i < 60; i++) { + const m = (lo + hi) / 2; + if (Math.sin(m) / (CAMERA - Math.cos(m)) < rise) lo = m; + else hi = m; + } + const tilt = (lo + hi) / 2; + // North up: the sub-camera point is the middle point moved `tilt` south along its meridian. + const east = norm(cross([0, 0, 1], mid)); + const northAtMid = cross(mid, east); + const s: Vec = [ + Math.cos(tilt) * mid[0] - Math.sin(tilt) * northAtMid[0], + Math.cos(tilt) * mid[1] - Math.sin(tilt) * northAtMid[1], + Math.cos(tilt) * mid[2] - Math.sin(tilt) * northAtMid[2], + ]; + const right = east; + const up = cross(s, right); + const sun = ecef(SUN_LAT, midLon); + console.log( + `middle point ${midLat.toFixed(4)} N, ${midLon.toFixed(4)} E; sub-camera tilt ${((tilt * 180) / Math.PI).toFixed(2)} deg`, + ); + const SS = 3; + + // The sky: void, plus stars from a fixed generator. + const rgba = new Uint8ClampedArray(WIDTH * HEIGHT * 4); + const sky = (y: number): Vec => { + const t = y / HEIGHT; + return mix(VOID, SURFACE_2, t * 0.6); + }; + for (let y = 0; y < HEIGHT; y++) { + const c = sky(y); + for (let x = 0; x < WIDTH; x++) { + const at = (y * WIDTH + x) * 4; + rgba[at] = c[0]; + rgba[at + 1] = c[1]; + rgba[at + 2] = c[2]; + rgba[at + 3] = 255; + } + } + let seed = 20261108; + const rnd = () => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed / 4294967296; + }; + for (let i = 0; i < 260; i++) { + const x = Math.floor(rnd() * WIDTH); + const y = Math.floor(rnd() * HEIGHT); + const b = 40 + rnd() * rnd() * 70; + const [x0, y0, x1, y1] = FRAME.clear; + if (x >= x0 && x <= x1 && y >= y0 && y <= y1) continue; + const at = (y * WIDTH + x) * 4; + rgba[at] = Math.max(rgba[at], b * 0.9); + rgba[at + 1] = Math.max(rgba[at + 1], b); + rgba[at + 2] = Math.max(rgba[at + 2], b * 1.05); + } + + const x0 = Math.max(0, Math.floor(cx - radius * 1.25)); + const x1 = Math.min(WIDTH, Math.ceil(cx + radius * 1.25)); + const y0 = Math.max(0, Math.floor(cy - radius * 1.25)); + const y1 = Math.min(HEIGHT, Math.ceil(cy + radius * 1.25)); + const limbSin = 1 / CAMERA; + + for (let y = y0; y < y1; y++) { + for (let x = x0; x < x1; x++) { + let r = 0; + let g = 0; + let b = 0; + let cover = 0; + // The rim of air: strongest at the limb, fading out over about 5 per cent of the radius. + let glow = 0; + for (let sy = 0; sy < SS; sy++) { + for (let sx = 0; sx < SS; sx++) { + const px = x + (sx + 0.5) / SS - cx; + const py = cy - (y + (sy + 0.5) / SS); + const dir = norm([px / focal, py / focal, -1]); + // Ray from (0, 0, CAMERA) against the unit sphere. + const bq = CAMERA * dir[2]; + const disc = bq * bq - (CAMERA * CAMERA - 1); + if (disc >= 0) { + const t = -bq - Math.sqrt(disc); + const p: Vec = [dir[0] * t, dir[1] * t, CAMERA + dir[2] * t]; + const world: Vec = [ + right[0] * p[0] + up[0] * p[1] + s[0] * p[2], + right[1] * p[0] + up[1] * p[1] + s[1] * p[2], + right[2] * p[0] + up[2] * p[1] + s[2] * p[2], + ]; + const lat = + (Math.asin(Math.max(-1, Math.min(1, world[2]))) * 180) / + Math.PI; + const lon = (Math.atan2(world[1], world[0]) * 180) / Math.PI; + const tex = sample(lat, lon); + const lit = dot(world, sun); + const day = smooth(-0.1, 0.35, lit); + const shade = 0.12 + 0.95 * day; + // What the photograph says: land is warmer than the sea, snow and ice are white. + const luma = (0.3 * tex[0] + 0.55 * tex[1] + 0.15 * tex[2]) / 255; + const warm = (tex[0] - tex[2] + 0.3 * (tex[1] - tex[2])) / 255; + const snow = smooth( + 0.5, + 0.72, + Math.min(tex[0], tex[1], tex[2]) / 255, + ); + const land = Math.max(smooth(0.0, 0.07, warm), snow); + // The sea runs void to teal with the photograph's depth; land teal to ice-dim, with + // its own relief; snow and ice reach the ice token. + const sea = mix(SURFACE_2, TEAL, smooth(0.03, 0.3, luma) * 0.75); + const ground = mix(TEAL, ICE_DIM, smooth(0.08, 0.5, luma)); + const toned = mix(mix(sea, ground, land), ICE, snow * 0.85); + // Fresnel haze: the more edge-on the surface, the more of the air's cyan. + const normalFacing = Math.max( + 0, + dot(norm([p[0], p[1], p[2]]), [-dir[0], -dir[1], -dir[2]]), + ); + const haze = Math.pow(1 - normalFacing, 3) * 0.75; + for (let c = 0; c < 3; c++) { + const base = toned[c] * shade; + const v = + base * (1 - haze * (0.4 + 0.6 * day)) + + CYAN[c] * haze * (0.25 + 0.75 * day); + if (c === 0) r += v; + else if (c === 1) g += v; + else b += v; + } + cover += 1; + } else { + // Distance from the sphere's limb in sphere radii: sin of the ray's angle to the axis. + const rayTan = Math.hypot(dir[0], dir[1]) / -dir[2]; + const limbTan = limbSin / Math.sqrt(1 - limbSin * limbSin); + const out = rayTan / limbTan - 1; + if (out < 0.09) { + const sideLit = Math.max( + 0, + Math.min( + 1, + 0.35 + + 0.9 * + dot( + norm([dir[0], dir[1], 0]), + norm([ + right[0] * sun[0] + + right[1] * sun[1] + + right[2] * sun[2], + up[0] * sun[0] + up[1] * sun[1] + up[2] * sun[2], + 0, + ]), + ), + ), + ); + glow += Math.pow(1 - out / 0.09, 2.2) * (0.25 + 0.75 * sideLit); + } + } + } + } + const n = SS * SS; + const at = (y * WIDTH + x) * 4; + const sr = rgba[at]; + const sg = rgba[at + 1]; + const sb = rgba[at + 2]; + const k = cover / n; + const gl = (glow / n) * 0.55; + // Atmosphere over the sky, then the planet over both. + const ar = sr + (CYAN[0] - sr) * gl; + const ag = sg + (CYAN[1] - sg) * gl; + const ab = sb + (CYAN[2] - sb) * gl; + rgba[at] = ar * (1 - k) + r / n; + rgba[at + 1] = ag * (1 - k) + g / n; + rgba[at + 2] = ab * (1 - k) + b / n; + } + } + + const pixels = CanvasKit.MakeImage( + { + width: WIDTH, + height: HEIGHT, + alphaType: CanvasKit.AlphaType.Unpremul, + colorType: CanvasKit.ColorType.RGBA_8888, + colorSpace: CanvasKit.ColorSpace.SRGB, + }, + new Uint8Array(rgba.buffer), + WIDTH * 4, + ); + if (!pixels) throw new Error("cannot build the image"); + const bytes = pixels.encodeToBytes(CanvasKit.ImageFormat.WEBP, 90); + if (!bytes) throw new Error("cannot encode WebP"); + const file = resolve(appRoot, `src/assets/og-earth.webp`); + writeFileSync(file, bytes); + console.log(`wrote ${file} (${bytes.length} bytes)`); + } +} + +await main(); diff --git a/apps/dox/scripts/build-reference.ts b/apps/dox/scripts/build-reference.ts index 3695bad11..16f065548 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, @@ -87,6 +93,10 @@ import { import { buildRedirects } from "./build-utils/redirects"; import { SITE_BASE } from "../src/lib/site"; import { plainText, referenceHeadTitle } from "./build-utils/reference-title"; +import { + uniqueDescriptions, + valueKind, +} from "./build-utils/unique-descriptions"; import { MOVED_PAGES } from "./build-utils/moved-pages"; import { RENAMED_FUNCTIONS } from "./build-utils/renamed-functions"; import { @@ -2655,6 +2665,18 @@ function titleFields(doc: FnDoc | TypeDoc | RegexDoc): string[] { ]; } +/** The page with its frontmatter `description` replaced. The body keeps the original text. */ +function withDescription(mdx: string, description: string): string { + const replaced = mdx.replace( + /^description: .*$/m, + () => `description: ${JSON.stringify(description)}`, + ); + if (replaced === mdx) { + throw new Error("[reference] a page has no frontmatter description line."); + } + return replaced; +} + /** The page of a shared type: one that two or more public functions reach. */ export function renderType(doc: TypeDoc, page: PageContext): string { const { usage } = page; @@ -3011,7 +3033,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 = @@ -3042,6 +3070,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"), @@ -3326,6 +3355,30 @@ 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)])); + + // Pages that would share a meta description get a qualifier in it (`unique-descriptions.ts`). + const qualifiedDescriptions = uniqueDescriptions( + dedupedDocs.flatMap((d) => + d.kind === "type" + ? [] + : [ + { + id: fnKey(d), + description: plainText(d.description), + namespace: d.namespace, + kind: valueKind(d.name), + }, + ], + ), + ); + for (const doc of dedupedDocs) { const unreleased = isUnreleased(baseline, doc.name); const withNote = (mdx: string) => @@ -3343,7 +3396,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({ @@ -3383,12 +3436,19 @@ function runGeneration(baseline: ReleasedBaseline) { } else { mdx = renderRegex(doc); } + const qualifiedDescription = qualifiedDescriptions.get(fnKey(doc)); + if (qualifiedDescription !== undefined) { + mdx = withDescription(mdx, qualifiedDescription); + } 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)); @@ -3421,6 +3481,7 @@ function runGeneration(baseline: ReleasedBaseline) { name: d.name, url: pageUrl(d.namespace, d.module, d.name), description: d.description, + sourcePath: sourceOf(d), }); continue; } @@ -3429,6 +3490,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); @@ -3440,7 +3502,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-social-preview.ts b/apps/dox/scripts/build-social-preview.ts index 2b6fdf909..e7951273c 100644 --- a/apps/dox/scripts/build-social-preview.ts +++ b/apps/dox/scripts/build-social-preview.ts @@ -1,76 +1,41 @@ #!/usr/bin/env tsx /** - * Write the repository's GitHub social preview: `/.github/social-preview.png`, 1280 by 640. + * Write the upload-ready share images to `apps/dox/assets/share/`: * - * GitHub asks for 1280 by 640 and the site's share card is 1200 by 630, so the card is drawn by the - * same code as the site's (`src/lib/og-art.ts`), pasted onto a canvas of the page colour at - * x 40, y 10, and its cyan bottom edge is carried across the full width. + * - `github-social-preview.png`, 1280 by 640: the repository's social preview. GitHub asks for that + * size and the site card is 1200 by 630, so the card is drawn by the same code as the site's + * (`src/lib/og-art.ts`) and scaled to cover the larger canvas, cropped from the bottom so the + * cyan edge stays whole. + * - `og-default-1200x630.png`: the site card, the same bytes as `/og/site.png`. + * - `earth-1200x630.png`: the artwork alone, with no text. * * Run by hand, not in `generate`: `pnpm --filter dox run social-preview`. The owner uploads the - * file in the repository settings; GitHub has no API for it. + * files where they are wanted; GitHub has no API for its preview. `assets/` sits outside `src/` and + * `public/`, so the build never serves it. */ import { mkdirSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { generateOpenGraphImage } from "astro-og-canvas"; -import { PNG } from "pngjs"; -import { - OG_BACKGROUND, - OG_EDGE, - OG_EDGE_COLOR, - ogImageOptions, -} from "../src/lib/og-art"; +import sharp from "sharp"; +import { renderArtwork, renderCard } from "../src/lib/og-art"; +import { SITE_CARD_LINE } from "../src/lib/og-cards"; const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const output = resolve(appRoot, "..", "..", ".github", "social-preview.png"); +const folder = resolve(appRoot, "assets", "share"); -const WIDTH = 1280; -const HEIGHT = 640; -const OFFSET_X = 40; -const OFFSET_Y = 10; +const card = await renderCard({ kind: "site", line: SITE_CARD_LINE }); +const preview = await sharp(card) + .resize(1280, 640, { fit: "cover", position: "bottom" }) + .png({ palette: true, quality: 100, compressionLevel: 9 }) + .toBuffer(); +const artwork = await renderArtwork(); -const card = PNG.sync.read( - Buffer.from( - // A PNG renders to bytes; the declared type is the wider `BodyInit`. - (await generateOpenGraphImage( - ogImageOptions({ - title: "GMT", - description: - "Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.", - }), - )) as Uint8Array, - ), -); - -const canvas = new PNG({ width: WIDTH, height: HEIGHT }); -const [vr, vg, vb] = OG_BACKGROUND; -for (let i = 0; i < WIDTH * HEIGHT; i++) { - canvas.data[i * 4] = vr; - canvas.data[i * 4 + 1] = vg; - canvas.data[i * 4 + 2] = vb; - canvas.data[i * 4 + 3] = 255; -} - -for (let y = 0; y < card.height; y++) { - for (let x = 0; x < card.width; x++) { - const from = (y * card.width + x) * 4; - const to = ((y + OFFSET_Y) * WIDTH + (x + OFFSET_X)) * 4; - for (let c = 0; c < 4; c++) canvas.data[to + c] = card.data[from + c]; - } +mkdirSync(folder, { recursive: true }); +for (const [name, bytes] of [ + ["github-social-preview.png", preview], + ["og-default-1200x630.png", card], + ["earth-1200x630.png", artwork], +] as const) { + writeFileSync(resolve(folder, name), bytes); + console.log(`wrote ${resolve(folder, name)} (${bytes.length} bytes)`); } - -// The card's bottom edge ends at y 640; carry its cyan across the margins on either side. -const [er, eg, eb] = OG_EDGE_COLOR; -for (let y = HEIGHT - OG_EDGE; y < HEIGHT; y++) { - for (let x = 0; x < WIDTH; x++) { - const at = (y * WIDTH + x) * 4; - canvas.data[at] = er; - canvas.data[at + 1] = eg; - canvas.data[at + 2] = eb; - canvas.data[at + 3] = 255; - } -} - -mkdirSync(dirname(output), { recursive: true }); -writeFileSync(output, PNG.sync.write(canvas)); -console.log(`wrote ${output} (${WIDTH}x${HEIGHT})`); 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/head-tags-scan.test.ts b/apps/dox/scripts/build-utils/head-tags-scan.test.ts index 2454a34c8..ef28648b1 100644 --- a/apps/dox/scripts/build-utils/head-tags-scan.test.ts +++ b/apps/dox/scripts/build-utils/head-tags-scan.test.ts @@ -54,6 +54,14 @@ describe("scanHead", () => { expect(scan.jsonLd).toEqual(['{"@type":"BreadcrumbList"}']); }); + it("tells a describedby link from a text/plain alternate", () => { + const scan = scanHead( + ``, + ); + expect(scan.describedBy).toEqual(["/gmt/llms.txt"]); + expect(scan.textAlternates).toEqual(["/x.txt"]); + }); + it("finds an edit link to any GitHub repository and no other anchor", () => { expect(scanHead(PAGE).editLinks).toEqual([ "https://github.com/northguild/gmt/edit/main/packages/gmt/src/plain/calculate/addDate.ts", diff --git a/apps/dox/scripts/build-utils/head-tags-scan.ts b/apps/dox/scripts/build-utils/head-tags-scan.ts index 71a9f8a03..7a775cdd8 100644 --- a/apps/dox/scripts/build-utils/head-tags-scan.ts +++ b/apps/dox/scripts/build-utils/head-tags-scan.ts @@ -19,6 +19,10 @@ export type HeadScan = { ogTitle: string | undefined; /** The `href` of each ``. */ markdownAlternates: string[]; + /** The `href` of each ``. */ + describedBy: string[]; + /** The `href` of each ``. The site carries none. */ + textAlternates: string[]; /** The text of each `