diff --git a/context/stack.md b/context/stack.md index 1c293de7..766c938a 100644 --- a/context/stack.md +++ b/context/stack.md @@ -33,9 +33,9 @@ scripts/ version-sync script, run by `pnpm sync-version`; `release- skills/ the usage skill, `skills/worktree/SKILL.md`; hand-written, shipped inside the npm package (package.json `files`) and installable with `npx skills add`. Nothing on npm discovers it since TanStack Intent went (`skills add` reads GitHub); it stays in `files` so an `npm i -g` install has a copy matching its own version on disk docs/ Astro 7 + Starlight docs site, React 19 islands, Base UI; own package.json, `astro.config.mjs` docs/src/content/docs/ Starlight pages (29 pages: `index.mdx` is the landing at `/worktree/`, `getting-started.mdx` is Getting Started at `/worktree/getting-started/`, plus `commands/` (9 command pages and an index), `guides/` (12 guides and an index), `configuration`, `project-configuration`, `faq` and `changelog`) -docs/src/ chat client, site metadata, styles; the chat is the page `/dox` (`pages/dox.astro`, one React island, `chat/components/DoxPage.tsx`), reached by plain links only: the header's "Chat with Dox" crystal (`components/Header.astro`, repeated in the mobile menu by `components/MobileMenuFooter.astro`) and the landing's "Ask Dox" (`components/Hero.astro`); `components/DoxMark.astro` draws the crystal, and no page but `/dox` loads chat code; the header's right group ends with the settings gear (`components/SettingsControl.astro`, wired by `lib/settings-control.ts`: a native `[popover]` holding the "Dark theme" switch, whose rule is `lib/theme.ts`; it shows at every width, below 50rem as the only chip of the right group that does, and the mobile menu has no copy); sound is `lib/sound/` (GMT's engine, cut down: `settings.ts` is the reader's choice in the `dox:sound` key shared with GMT and northguild.dev, `cue.ts` is loaded on every page by `components/Head.astro`, and the engine is a chunk only its dynamic `import()` reaches, once a reader has unmuted, and on the landing alone it imports `lib/sound/leaves.ts`, the leaves' voices, driven by the last landing and the sampled landing places `hero/flight.ts` computes, only while sound is on, from the particles' own timings; no press makes a sound but the chat's Send and "Try again"); `components/Hero.astro` puts the landing's copy beside `HeroLeaves.astro` (the leaf-particle hero: a still SVG, a canvas and a small loader script; the effect itself, in `hero/` with OGL, is a chunk only the loader's dynamic `import()` reaches, so the landing alone ships hero script; its CSS is in the shared stylesheet) +docs/src/ chat client, site metadata, styles; the chat is the page `/dox` (`pages/dox.astro`, one React island, `chat/components/DoxPage.tsx`), reached by plain links only: the header's "Chat with Dox" crystal (`components/Header.astro`, repeated in the mobile menu by `components/MobileMenuFooter.astro`) and the landing's "Ask Dox" (`components/Hero.astro`); `components/DoxMark.astro` draws the crystal, and no page but `/dox` loads chat code; the header's right group ends with the settings gear (`components/SettingsControl.astro`, wired by `lib/settings-control.ts`: a native `[popover]` holding the "Dark theme" switch, whose rule is `lib/theme.ts`; it shows at every width, below 50rem as the only chip of the right group that does, and the mobile menu has no copy); sound is `lib/sound/` (GMT's engine, cut down: `settings.ts` is the reader's choice in the `dox:sound` key shared with GMT and northguild.dev, `cue.ts` is loaded on every page by `components/Head.astro`, and the engine is a chunk only its dynamic `import()` reaches, once a reader has unmuted, and on the landing alone it imports `lib/sound/leaves.ts`, the leaves' voices, driven by the last landing and the sampled landing places `hero/flight.ts` computes, only while sound is on, from the particles' own timings; no press makes a sound but the chat's Send and "Try again"); `components/Hero.astro` puts the landing's copy beside `HeroLeaves.astro` (the leaf-particle hero: a still SVG, a canvas and a small loader script; the effect itself, in `hero/` with OGL, is a chunk only the loader's dynamic `import()` reaches, so the landing alone ships hero script; its CSS is in the shared stylesheet); the share cards are made in the build: `pages/og/[...route].ts` writes `dist/og/site.png` and one PNG per page, `lib/og-cards.ts` decides the cards and their alt text, `lib/og-art.ts` draws one with CanvasKit (`lib/og-canvaskit.ts` loads it) over the committed `assets/og-art.png` in the Michroma TTF of `assets/og-fonts/`, `components/Head.astro` writes each page's share tags, and `lib/og-image-version.ts` is the integration that appends `?v=` to them after the build docs/src/styles/northguild/ the NorthGuild theme, vendored unedited from `northguild/northguild.dev` `packages/theme/` (each file's header names the commit); `docs/src/styles/theme.css` is this site's own `--gmt-*` → `--sl-*` mapping. To refresh, see `docs/README.md` (Theme) -docs/wrangler.jsonc the docs site's Worker config (assets from `docs/.deploy`, the build staged under `worktree/` and `docs/deploy/_headers` at its root by `stage:deploy`); `docs/scripts/` holds `audit-dist.mjs`, `theme-contrast.mjs` (measures the theme's contrast pairs), `build-legacy-pages.mjs` (writes the gitignored `docs/legacy/`), `deploy-smoke.mjs` and `web-vitals.mjs` (measures Core Web Vitals by hand, not a gate) +docs/wrangler.jsonc the docs site's Worker config (assets from `docs/.deploy`, the build staged under `worktree/` and `docs/deploy/_headers` at its root by `stage:deploy`); `docs/scripts/` holds `audit-dist.mjs`, `build-og-art.mjs` (draws the share cards' art into `docs/src/assets/og-art.png` by hand, never in the build), `theme-contrast.mjs` (measures the theme's contrast pairs), `build-legacy-pages.mjs` (writes the gitignored `docs/legacy/`), `deploy-smoke.mjs` and `web-vitals.mjs` (measures Core Web Vitals by hand, not a gate) docs/worker/ Cloudflare Worker for the docs chat, on TanStack AI: `POST /api/chat` serves the current client, `GET /api/brains` the usage counts, `POST /` the frozen legacy protocol (its own `wrangler.toml`, which binds `[ai]`, remote in dev, for the Workers AI brains, and the `DOX_USAGE` KV namespace for the usage ledger; plus a local-only `[env.evals]`, never deployed, for the live evals) docs/evals/ Dox chat evals (plan #355): `cases.ts` is the case set (pure data, loaded under Node type stripping: erasable syntax, `.ts` imports) and `cases.test.ts` checks it against the corpus; `metrics.ts` scores retrieval (pure), `offline.test.ts` runs every case through `validateChatRequest` and `prepareTurn` in `pnpm docs:test` and compares the scores with `baseline.json` (rewritten by `pnpm --filter docs evals:baseline`), `read-stream.ts` and `graders.ts` read and grade a live answer, `budget.ts` and `report.ts` hold the live layer's spending limits and its committed report, `run-live.ts` is the live runner (`pnpm --filter docs evals:live`; it spends real Neurons and refuses under `CI`), and `README.md` is the runbook context/ planning-workflow artifacts (this directory) diff --git a/context/verify.md b/context/verify.md index 2ceda363..bafdc712 100644 --- a/context/verify.md +++ b/context/verify.md @@ -121,8 +121,11 @@ hidden or a named image; the 404's heading a git error line (`fatal: ...`); and from the vendored tokens and fails if any reaches a used rule, a used custom property, the HTML or a script in the build (the vendored definitions, rules for classes no page uses and values `theme.css` overrides are not findings). The contrast of every themed pair is separate: `node docs/scripts/theme-contrast.mjs` prints it, and its test in `pnpm docs:test` fails under 4.5:1 (text) or 3:1 (controls, rings). -Plan §9 Q3 added, on every page: an `og:image` that is an absolute URL under `https://northguild.dev/worktree/` and a file in the build, 1200×630 by the -file's own header, with `og:image:type`, `:width` and `:height` saying what the file is; a `twitter:image` that is the same URL; and alt text for both. On +Plan §9 Q3 added the share image, and #286 (2026-11-29) replaced the single JPEG with a PNG card per page. On every page, the 404 and `/dox/`: an `og:image` that is exactly +`https://northguild.dev/worktree/og/.png?v=<12 lowercase hex>`, where the hash is the first 12 hex characters of the built file's SHA-256, and the file is a PNG by +its own header (a JPEG fails), 1200×630 and at most 307,200 bytes (WhatsApp skips a preview over 300 KB), with `og:image:type` `image/png` and `og:image:width` and `:height` +saying 1200 and 630; a `twitter:image` equal to the `og:image`; exactly one `og:locale`, `en_US`; and `og:image:alt` and `twitter:image:alt` both present and neither the +page's title. The card is the page's own (its path, `commands/branch` for `commands/branch/`), except the landing, the 404 and `/dox/`, which name `site` (`site.png`). On every page and the 404, a ``, with every icon link (`icon`, `shortcut icon`, `apple-touch-icon`) naming a regular file in the build; and a `` that is its `og:title` and `og:site_name` joined by GMT's ` · ` (2026-11-04, replacing ` | `), or its `og:title` alone where that names the site. The script's own test, `docs/scripts/audit-dist.test.mjs`, runs under `pnpm docs:test` (the docs Vitest config takes any `*.test.mjs`). @@ -193,6 +196,11 @@ test that genuinely has to be skipped is a conversation, not an edit to this pat refuses to run when `CI` is set. They need `wrangler login` and the network. `evals:live --help` and a run with no Worker at `--base` spend nothing. A run with `--write-baseline` rewrites `docs/evals/live-<brainId>.json`. Never run them to verify anything; the runbook is `docs/evals/README.md`. `wrangler deploy --dry-run --env evals` is safe and credential-free. +- **`node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON docs/scripts/build-og-art.mjs`** — generation, not verification. It *writes* + the committed `docs/src/assets/og-art.png` (the share cards' art), exits 1 without writing when the text's contrast is under 4.5:1 or + the PNG is over 307,200 bytes, and is run by hand when the art should change, never by the build. Commit the PNG with the change; + `build-og-art.test.mjs` in `pnpm docs:test` fails when the committed file's pixels differ from what the script draws now + (pixels, not bytes: the PNG's deflate differs by CPU, so a file drawn on macOS is a byte longer on CI's Linux). - **`pnpm changeset:add`** — not a gate: interactive (it prompts for a bump level and a description) and it writes a `.changeset/*.md` file. Run it when a change owes a release note, per [`release.md`](release.md). - **`pnpm changeset:status`** — not a gate: it compares against `origin/main`, so it needs that ref and a diff --git a/docs/README.md b/docs/README.md index 66a263d9..dec6cfc2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -550,6 +550,23 @@ make quiet sounds tied to their flight (see [The leaves' sounds](#the-leaves-sou query, the absence of any `opacity: 0` rule on a header item, and which parts may fade (never the wordmark, GitHub or Discord, or the search dialog's buttons). +## Share cards + +Each page's link preview is a 1200×630 PNG card, made by the build: the route `src/pages/og/[...route].ts` writes `dist/og/site.png` +(the landing, the 404 and `/dox/`) and one `dist/og/<page>.png` per page, each drawing its text over a committed piece of art: a page card its page title, the site card "worktree" and the line "A git worktree for every branch." The +build needs nothing from you; `pnpm docs:audit-dist` holds the cards and their tags. + +The art itself (the dark ground, the hero's branch graph and the panel behind the text, no words) is drawn by hand, not by the build: + +```bash +node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON docs/scripts/build-og-art.mjs +``` + +Run it when the art should change: the hero's graph changes (`src/hero/targets.ts`, `geometry.ts`) or you want a different look. The colours are hard-coded in +`COLORS` in the script, so after a theme token moves, edit `COLORS` first (the test's "the colours" case fails until you do). It writes `src/assets/og-art.png` and prints the text's contrast against the art; under 4.5:1, or over 307,200 bytes, it fails and writes nothing. **Commit the +PNG with the change.** `scripts/build-og-art.test.mjs` (in `pnpm docs:test`) redraws the art and fails when the committed file's pixels differ (pixels, not bytes: the PNG's deflate differs by CPU), +so a change to the graph without the redrawn PNG does not pass. The text is Michroma (`src/assets/og-fonts/`, SIL OFL, licence beside it). + ## Scripts reference All commands are run from the repo root with `pnpm --filter docs run <command>`, diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 489826f5..af357684 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -4,12 +4,9 @@ import sitemap from "@astrojs/sitemap"; import starlight from "@astrojs/starlight"; import tailwindcss from "@tailwindcss/vite"; import { defineConfig } from "astro/config"; +import { versionOgImages } from "./src/lib/og-image-version.ts"; import { sitemapLastmod } from "./src/lib/sitemap-lastmod.ts"; -// What the share preview shows, for readers who cannot see it (og:image:alt, twitter:image:alt). -const PREVIEW_ALT = - "The worktree docs landing: “A git worktree for every branch” beside a git graph drawn in green leaves."; - // `astro build` writes here; the sitemap reads each page's footer date back from it (D1). const DIST = fileURLToPath(new URL("./dist/", import.meta.url)); @@ -21,6 +18,8 @@ export default defineConfig({ trailingSlash: "always", build: { format: "directory" }, integrations: [ + // Before starlight(): hooks run in list order, so everything after reads the pages with the `?v=` hashes (plan #286 D5). + versionOgImages(), starlight({ title: "@northguild/worktree", // The delimiter in `<title>`: `<page> · @northguild/worktree`, the middle dot GMT's pages use (`Core Rules · GMT`; the @@ -147,23 +146,6 @@ export default defineConfig({ href: "/worktree/apple-touch-icon.png", }, }, - // The share preview (plan §9 Q3; the user, 2026-11-04: the landing with one of the hero's shapes): the landing in - // the dark theme with the hero formed as the git graph. A screenshot of `astro preview` at 1440×756 (DPR 2), the CLI - // version hidden so it does not age with a release, scaled to 1200×630. Retake it when the landing changes. - ...[ - ["og:image", "https://northguild.dev/worktree/og-image.jpg"], - ["og:image:type", "image/jpeg"], - ["og:image:width", "1200"], - ["og:image:height", "630"], - ["og:image:alt", PREVIEW_ALT], - ].map(([property, content]) => ({ - tag: "meta", - attrs: { property, content }, - })), - ...[ - ["twitter:image", "https://northguild.dev/worktree/og-image.jpg"], - ["twitter:image:alt", PREVIEW_ALT], - ].map(([name, content]) => ({ tag: "meta", attrs: { name, content } })), ], // Frame colours come from the --sl-* variables (the default), so the code blocks follow the theme picker. expressiveCode: { diff --git a/docs/package.json b/docs/package.json index f4b895ab..9e90fa82 100644 --- a/docs/package.json +++ b/docs/package.json @@ -64,9 +64,11 @@ "@testing-library/react": "^16.3.3", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "canvaskit-wasm": "0.42.0", "concurrently": "^10.0.6", "jsdom": "^26.1.0", "playwright": "^1.65.0", + "sharp": "0.35.5", "tsup": "^9.0.0", "typescript": "^5.9.3", "vitest": "^4.1.12", diff --git a/docs/public/og-image.jpg b/docs/public/og-image.jpg deleted file mode 100644 index 14822b4a..00000000 Binary files a/docs/public/og-image.jpg and /dev/null differ diff --git a/docs/scripts/audit-dist.mjs b/docs/scripts/audit-dist.mjs index 43a72202..4a1cd9b0 100644 --- a/docs/scripts/audit-dist.mjs +++ b/docs/scripts/audit-dist.mjs @@ -41,13 +41,19 @@ * Also (#352 phase 4, D7, the sound engine): no page, the 404 included, loads the engine up front (a script, a * modulepreload, or a static import); `cue.ts`'s dynamic `import()` is the only way to it. * - * Also (plan §9 Q3, the share preview and the favicon): every page has an `og:image` that is an absolute URL under the - * site and names a file in the build, a `twitter:image` that is the same URL, and alt text for both; and every page and - * the 404 link an icon (`rel="icon"`), with every icon link (`icon`, `shortcut icon`, `apple-touch-icon`) naming a file - * in the build, a regular file and not a directory. The favicon 404'd on every page until then, and nothing noticed. The - * og:image is 1200×630 (plan §4.4), read from the file's own header, and `og:image:type`, `:width` and `:height` say what - * the file is. Every page's and the 404's `<title>` is its `og:title` and `og:site_name` joined by GMT's ` · ` (the user, - * 2026-11-04, replacing Starlight's default ` | `), or its `og:title` alone where that already names the site. + * Also (plan §9 Q3, the favicon): every page and the 404 link an icon (`rel="icon"`), with every icon link (`icon`, + * `shortcut icon`, `apple-touch-icon`) naming a file in the build, a regular file and not a directory. The favicon 404'd on + * every page until then, and nothing noticed. Every page's and the 404's `<title>` is its `og:title` and `og:site_name` + * joined by GMT's ` · ` (the user, 2026-11-04, replacing Starlight's default ` | `), or its `og:title` alone where that + * already names the site. + * + * Also (#286 phase 5, D6, D9, the share cards): `auditShare` runs on the 29 pages, the 404 and `/dox/`, one failure line per + * rule. `og:image` is exactly `https://northguild.dev/worktree/og/<key>.png?v=<12 lowercase hex>`; the hash is the first 12 + * hex characters of the built file's SHA-256; the file is a PNG by its own header (a JPEG fails), 1200×630, at most 307,200 + * bytes (WhatsApp skips a preview over 300 KB); `og:image:type` is `image/png` and `og:image:width` and `:height` say + * 1200 and 630; `twitter:image` is the `og:image`; there is exactly one `og:locale`, `en_US`; `og:image:alt` and + * `twitter:image:alt` are present and neither is the page's title; and the card is the page's own (its path is its key, + * `commands/branch` for `commands/branch/`), except the landing, the 404 and `/dox/`, which name `site`. * * Also (#352, the settings gear replaces the theme toggle): no page has a `starlight-theme-select`, the theme provider's * script (the override, not Starlight's) is inline in `<head>` so the theme is set before first paint, and each page's @@ -99,6 +105,7 @@ */ import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { existsSync, readFileSync, statSync } from "node:fs"; import { readdir, readFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; @@ -121,10 +128,12 @@ const BASE_PATH = new URL(ORIGIN).pathname; * Undefined for anything outside the site. The build is written without the base (stage:deploy adds it). */ function builtFileOf(href, dist) { - const path = href.startsWith(ORIGIN) - ? href.slice(ORIGIN.length) - : href.startsWith(BASE_PATH) - ? href.slice(BASE_PATH.length) + // A static file server ignores a URL's query and fragment, so the file is the path alone. + const bare = href.split(/[?#]/)[0]; + const path = bare.startsWith(ORIGIN) + ? bare.slice(ORIGIN.length) + : bare.startsWith(BASE_PATH) + ? bare.slice(BASE_PATH.length) : undefined; return path === undefined || path === "" ? undefined : join(dist, path); } @@ -176,8 +185,104 @@ export function imageSize(bytes) { return undefined; } -/** Plan §4.4: a 1200×630 preview image. */ -const PREVIEW_SIZE = { width: 1200, height: 630 }; +/** The share card (#286): 1200×630, and WhatsApp skips a preview over 300 KB (307,200 bytes). */ +const CARD_SIZE = { width: 1200, height: 630 }; +const CARD_MAX_BYTES = 307_200; +/** `og:image`: the build's `/og/` route, a page's key (its route id, `/` kept), and the first 12 hex of the file's SHA-256. */ +const CARD_URL = new RegExp( + `^${ORIGIN.replaceAll(".", "\\.")}og/([a-z0-9][a-z0-9/-]*)\\.png\\?v=([0-9a-f]{12})$`, +); + +/** + * The share-card rules (#286 D6, D9) for one page's HTML, as failure rules without a page prefix. `key` is the card the + * page must name: its path (`commands/branch`), or `site` for the landing, the 404 and `/dox/`. A page of the 29 reaches it + * from `auditPage`, the 404 from `auditSite` and `/dox/` from `auditDox`, because those two have rule sets of their own. + */ +function auditShare(html, dist, key) { + const failures = []; + const fail = (rule) => failures.push(rule); + const metas = tagsOf(html, "meta"); + const metaContent = (name, value) => + metas.find((m) => m[name] === value)?.content; + + const image = metaContent("property", "og:image"); + if (!image) fail("no og:image tag"); + else { + const card = CARD_URL.exec(image); + if (!card) + fail( + `og:image is ${image}, expected ${ORIGIN}og/<key>.png?v=<12 lowercase hex>`, + ); + else if (card[1] !== key) + fail( + card[1] === "site" + ? `og:image is the site card, expected the page's own (${ORIGIN}og/${key}.png)` + : `og:image names the card ${card[1]}, expected ${key}`, + ); + if (!isBuiltFile(image, dist)) + fail(`og:image ${image} is not a file in the build`); + else { + const bytes = readFileSync(builtFileOf(image, dist)); + const digest = createHash("sha256").update(bytes).digest("hex"); + if (card && card[2] !== digest.slice(0, 12)) + fail( + `og:image ?v=${card[2]} is not the first 12 hex of the file's SHA-256 (${digest.slice(0, 12)})`, + ); + const size = imageSize(bytes); + if (size?.type !== "image/png") + fail(`og:image ${image} is not a PNG (by its own header)`); + else { + if (size.width !== CARD_SIZE.width || size.height !== CARD_SIZE.height) + fail( + `og:image is ${size.width}×${size.height}, expected ${CARD_SIZE.width}×${CARD_SIZE.height}`, + ); + if (bytes.length > CARD_MAX_BYTES) + fail( + `og:image is ${bytes.length} bytes, over the ${CARD_MAX_BYTES}-byte limit`, + ); + } + } + } + const type = metaContent("property", "og:image:type"); + if (type !== "image/png") + fail(`og:image:type is ${type ?? "missing"}, expected image/png`); + const width = metaContent("property", "og:image:width"); + const height = metaContent("property", "og:image:height"); + if (width !== String(CARD_SIZE.width) || height !== String(CARD_SIZE.height)) + fail( + `og:image:width and og:image:height say ${width ?? "missing"}×${height ?? "missing"}, expected ${CARD_SIZE.width}×${CARD_SIZE.height}`, + ); + + const twitterImage = metaContent("name", "twitter:image"); + if (!twitterImage) fail("no twitter:image tag"); + else if (image && twitterImage !== image) + fail(`twitter:image is ${twitterImage}, expected the og:image (${image})`); + + const locales = metas.filter((m) => m.property === "og:locale"); + if (locales.length !== 1) + fail(`${locales.length} og:locale tags, expected exactly 1`); + else if (locales[0].content !== "en_US") + fail(`og:locale is ${locales[0].content}, expected en_US`); + + // The alt says what the card shows; the page's title (og:title, else <title>, as auditTitle reads it) is not that. + const title = decode( + metaContent("property", "og:title") ?? + html.match(/<title>([^<]*)<\/title>/)?.[1] ?? + "", + ); + for (const [kind, name, tag] of [ + ["property", "og:image:alt", "og:image:alt"], + ["name", "twitter:image:alt", "twitter:image:alt"], + ]) { + const alt = metaContent(kind, name); + if (!alt) fail(`no ${tag} tag`); + else if (title !== "" && decode(alt) === title) + fail( + `${tag} is the page's title ("${title}"), not a description of the card`, + ); + } + return failures; +} /** * The title is the page's own (its `og:title`) and the site's (`og:site_name`), joined by GMT's middle dot ` · ` (the user, @@ -1764,48 +1869,8 @@ async function auditPage(path, dist, descriptions, options) { if (card === undefined) fail("no twitter:card tag"); else if (card !== "summary_large_image") fail(`twitter:card is ${card}, expected summary_large_image`); - // The share preview (plan §9 Q3): crawlers need an absolute URL, and a URL that 404s shows no card at all. - const image = metaContent("property", "og:image"); - if (!image) fail("no og:image tag"); - else if (!image.startsWith(ORIGIN)) - fail(`og:image is ${image}, expected an absolute URL under ${ORIGIN}`); - else if (!isBuiltFile(image, dist)) - fail(`og:image ${image} is not a file in the build`); - else { - // What the tags declare must be what the file is, and the file what plan §4.4 asks for. - const size = imageSize(readFileSync(builtFileOf(image, dist))); - const declared = { - type: metaContent("property", "og:image:type"), - width: metaContent("property", "og:image:width"), - height: metaContent("property", "og:image:height"), - }; - if (!size) fail(`og:image ${image} is not a PNG or a JPEG`); - else { - if ( - size.width !== PREVIEW_SIZE.width || - size.height !== PREVIEW_SIZE.height - ) - fail( - `og:image is ${size.width}×${size.height}, expected ${PREVIEW_SIZE.width}×${PREVIEW_SIZE.height}`, - ); - if ( - declared.width !== String(size.width) || - declared.height !== String(size.height) - ) - fail( - `og:image:width and og:image:height say ${declared.width}×${declared.height}, the file is ${size.width}×${size.height}`, - ); - if (declared.type !== size.type) - fail(`og:image:type is ${declared.type}, the file is ${size.type}`); - } - } - const twitterImage = metaContent("name", "twitter:image"); - if (!twitterImage) fail("no twitter:image tag"); - else if (twitterImage !== image) - fail(`twitter:image is ${twitterImage}, expected the og:image (${image})`); - if (!metaContent("property", "og:image:alt")) fail("no og:image:alt tag"); - if (!metaContent("name", "twitter:image:alt")) - fail("no twitter:image:alt tag"); + for (const rule of auditShare(html, dist, path === "" ? "site" : path)) + fail(rule); for (const rule of auditIcons(html, dist)) fail(rule); for (const rule of auditDescribedBy(html, dist)) fail(rule); for (const rule of auditTitle(html)) fail(rule); @@ -2118,6 +2183,7 @@ async function auditDox(dist) { // The header, the controls and the graphics are the site-wide rules, with the one difference that the page is the chat, // so its header's Dox link is the current page. + for (const rule of auditShare(html, dist, "site")) fail(rule); failures.push(...auditHeader(html, "/dox/", { onDox: true })); failures.push(...auditControls(html, "/dox/")); failures.push(...auditSvgs(html, "/dox/")); @@ -2184,6 +2250,7 @@ async function auditSite(dist) { failures.push(...auditNotFound(notFound)); for (const rule of [ ...auditIcons(notFound, dist), + ...auditShare(notFound, dist, "site"), ...auditTitle(notFound, { reportMissing: true }), ]) failures.push(`404.html: ${rule}`); diff --git a/docs/scripts/audit-dist.test.mjs b/docs/scripts/audit-dist.test.mjs index 30d73f58..a9445059 100644 --- a/docs/scripts/audit-dist.test.mjs +++ b/docs/scripts/audit-dist.test.mjs @@ -1,7 +1,7 @@ // @vitest-environment node import { execFileSync } from "node:child_process"; -import { randomBytes } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -223,16 +223,27 @@ const ICONS = [ '<link rel="icon" href="/worktree/favicon.ico" sizes="32x32"/>', '<link rel="apple-touch-icon" href="/worktree/apple-touch-icon.png"/>', ].join("\n"); -const PREVIEW = "https://northguild.dev/worktree/og-image.jpg"; -const PREVIEW_TAGS = [ - `<meta property="og:image" content="${PREVIEW}"/>`, - '<meta property="og:image:type" content="image/jpeg"/>', - '<meta property="og:image:width" content="1200"/>', - '<meta property="og:image:height" content="630"/>', - '<meta property="og:image:alt" content="The landing."/>', - `<meta name="twitter:image" content="${PREVIEW}"/>`, - '<meta name="twitter:image:alt" content="The landing."/>', -].join("\n"); +// #286: the share card is `og/<key>.png` (the page's route id; `site` for the landing, the 404 and /dox/), with `?v=` the +// first 12 hex of its SHA-256. The hash is computed here by node:crypto from the fixture's own bytes, never by the audit. +const sha12 = (bytes) => + createHash("sha256").update(bytes).digest("hex").slice(0, 12); +const keyOf = (path) => (path === "" ? "site" : path); +// A card is a valid PNG header plus the key's own bytes, so every card has a hash of its own. +const cardFile = (key) => Buffer.concat([png(1200, 630), Buffer.from(key)]); +const cardUrl = (key, bytes = cardFile(key)) => + `${ORIGIN}og/${key}.png?v=${sha12(bytes)}`; +const altOf = (key) => `A card for ${key}.`; +const previewTags = (key) => + [ + `<meta property="og:image" content="${cardUrl(key)}"/>`, + '<meta property="og:image:type" content="image/png"/>', + '<meta property="og:image:width" content="1200"/>', + '<meta property="og:image:height" content="630"/>', + `<meta property="og:image:alt" content="${altOf(key)}"/>`, + `<meta name="twitter:image" content="${cardUrl(key)}"/>`, + `<meta name="twitter:image:alt" content="${altOf(key)}"/>`, + '<meta property="og:locale" content="en_US"/>', + ].join("\n"); function jpeg(width, height) { const app0 = [0xff, 0xe0, 0x00, 0x04, 0x00, 0x00]; @@ -304,7 +315,7 @@ function page(path, overrides = {}) { `<meta property="og:url" content="${url(path)}"/>`, `<meta property="og:site_name" content="@northguild/worktree"/>`, `<meta name="twitter:card" content="summary_large_image"/>`, - overrides.preview ?? PREVIEW_TAGS, + overrides.preview ?? previewTags(keyOf(path)), overrides.icons ?? ICONS, overrides.describedby ?? LLMS_LINK, `<meta name="description" content="${description}"/>`, @@ -325,6 +336,7 @@ function notFoundPage(overrides = {}) { overrides.og ?? '<meta property="og:title" content="Page not found"/><meta property="og:site_name" content="@northguild/worktree"/>', overrides.icons ?? ICONS, + previewTags("site"), overrides.head ?? "", "</head><body>", overrides.header ?? HEADER, @@ -355,6 +367,7 @@ function doxPage(overrides = {}) { THEME_PROVIDER, `<title>${overrides.title ?? DOX_TITLE}`, overrides.robots ?? '', + previewTags("site"), overrides.shell ?? DOX_SHELL_SCRIPT, DOX_STYLESHEET, "", @@ -422,7 +435,8 @@ beforeEach(async () => { await write(dist, "_astro/particles.jkljkl.js", "export const effect = 1;"); for (const file of ["favicon.svg", "favicon.ico", "apple-touch-icon.png"]) await write(dist, file, "x"); - await write(dist, "og-image.jpg", jpeg(1200, 630)); + for (const key of ["site", ...PATHS.filter((p) => p !== "")]) + await write(dist, `og/${key}.png`, cardFile(key)); }); afterEach(async () => { @@ -573,7 +587,22 @@ describe("auditDist", () => { expect((await audit()).some((f) => /twitter:card/.test(f))).toBe(true); }); - describe("the share preview (plan §9 Q3)", () => { + // #286 phase 5 (D6, D9): one failing fixture per rule, each breaking that rule alone. The values come from the plan's §8 + // table: 1200×630, 307,200 bytes, `en_US`, and the first 12 hex of the file's SHA-256 (node:crypto, above). + describe("the share cards (#286)", () => { + const FAQ = cardUrl("faq"); + const faqHtml = async () => readFile(join(dist, htmlPath("faq")), "utf8"); + // Points faq's tags at a card of other bytes (and a matching hash) written in place of its own. + const replaceCard = async (bytes) => { + await write(dist, "og/faq.png", bytes); + await rewrite("faq", (html) => + html.replace( + /og\/faq\.png\?v=[0-9a-f]{12}/g, + `og/faq.png?v=${sha12(bytes)}`, + ), + ); + }; + it.each([ ["og:image", /]*>/], ["twitter:image", /]*>/], @@ -582,72 +611,253 @@ describe("auditDist", () => { ])("fails a page missing %s", async (tag, pattern) => { await rewrite("faq", (html) => html.replace(pattern, "")); const failures = await audit(); - // A missing og:image also leaves twitter:image naming something else; either way, only faq fails. - expect(failures.length).toBeGreaterThan(0); - expect(failures.every((f) => f.startsWith("/faq/:"))).toBe(true); - expect(failures.some((f) => f.includes(`no ${tag} tag`))).toBe(true); + expect(failures).toEqual([`/faq/: no ${tag} tag`]); }); - it("fails an og:image that is not an absolute URL under the site", async () => { - await rewrite("faq", (html) => - html.replaceAll(PREVIEW, "/worktree/og-image.jpg"), - ); + it.each([ + ["a relative URL", FAQ.replace(ORIGIN, "/worktree/")], + ["no ?v= query", `${ORIGIN}og/faq.png`], + ["uppercase hex", FAQ.replace(/v=.*/, (v) => v.toUpperCase())], + ["eleven hex characters", FAQ.slice(0, -1)], + ["thirteen hex characters", `${FAQ}0`], + ["a second query", `${FAQ}&x=1`], + ])("fails an og:image with %s", async (_name, bad) => { + await rewrite("faq", (html) => html.replaceAll(FAQ, bad)); expect(await audit()).toEqual([ - "/faq/: og:image is /worktree/og-image.jpg, expected an absolute URL under https://northguild.dev/worktree/", + `/faq/: og:image is ${bad}, expected ${ORIGIN}og/.png?v=<12 lowercase hex>`, ]); }); it("fails an og:image whose file is not in the build", async () => { - await rm(join(dist, "og-image.jpg")); - const failures = await audit(); - expect(failures).toContain( - `/faq/: og:image ${PREVIEW} is not a file in the build`, + await rm(join(dist, "og/faq.png")); + expect(await audit()).toEqual([ + `/faq/: og:image ${FAQ} is not a file in the build`, + ]); + }); + + it("reads the file behind the ?v= query, not a file named with it", async () => { + // A static file server ignores a URL's query. Other bytes, so another hash: the file is `og/faq.png`, and no file + // named `faq.png?v=...` exists. + await replaceCard(Buffer.concat([png(1200, 630), Buffer.from("again")])); + expect(await audit()).toEqual([]); + }); + + it("fails a ?v= that is not the file's SHA-256, naming the file's", async () => { + const wrong = "0123456789ab"; + await rewrite("faq", (html) => + html.replaceAll(`?v=${sha12(cardFile("faq"))}`, `?v=${wrong}`), ); - expect(failures).toHaveLength(PATHS.length); + expect(await audit()).toEqual([ + `/faq/: og:image ?v=${wrong} is not the first 12 hex of the file's SHA-256 (${sha12(cardFile("faq"))})`, + ]); }); - it("fails a preview that is not 1200×630, saying what the file is", async () => { - await write(dist, "og-image.jpg", jpeg(1440, 756)); - const failures = await audit(); - expect(failures).toContain( + it("fails a card that is a JPEG, even with the right hash and the right size", async () => { + await replaceCard(jpeg(1200, 630)); + expect(await audit()).toEqual([ + `/faq/: og:image ${cardUrl("faq", jpeg(1200, 630))} is not a PNG (by its own header)`, + ]); + }); + + it("fails a card that is not an image", async () => { + await replaceCard(Buffer.from("x")); + expect(await audit()).toEqual([ + `/faq/: og:image ${cardUrl("faq", Buffer.from("x"))} is not a PNG (by its own header)`, + ]); + }); + + it("fails a card that is not 1200×630, the tags still saying 1200×630", async () => { + await replaceCard(png(1440, 756)); + expect(await audit()).toEqual([ "/faq/: og:image is 1440×756, expected 1200×630", + ]); + }); + + it("accepts a card of exactly 307,200 bytes and fails one of 307,201", async () => { + // 307,200 = 300 × 1024, the issue's WhatsApp limit. + const at = (n) => Buffer.concat([png(1200, 630), Buffer.alloc(n - 33)]); + await replaceCard(at(307_200)); + expect(await audit()).toEqual([]); + await replaceCard(at(307_201)); + expect(await audit()).toEqual([ + "/faq/: og:image is 307201 bytes, over the 307200-byte limit", + ]); + }); + + it.each([ + [ + "a JPEG", + "image/jpeg", + "og:image:type is image/jpeg, expected image/png", + ], + ["nothing", undefined, "og:image:type is missing, expected image/png"], + ])("fails an og:image:type of %s", async (_name, type, failure) => { + await rewrite("faq", (html) => + html.replace( + '', + type ? `` : "", + ), ); - expect(failures).toContain( - "/faq/: og:image:width and og:image:height say 1200×630, the file is 1440×756", + expect(await audit()).toEqual([`/faq/: ${failure}`]); + }); + + it.each([ + ["width", "1200", "1201", "1201×630"], + ["height", "630", "631", "1200×631"], + ])("fails an og:image:%s that is not the card's", async (name, good, bad, said) => { + await rewrite("faq", (html) => + html.replace( + ``, + ``, + ), ); - expect(failures).toHaveLength(PATHS.length * 2); + expect(await audit()).toEqual([ + `/faq/: og:image:width and og:image:height say ${said}, expected 1200×630`, + ]); }); - it("fails declared tags that disagree with the file", async () => { + it("fails a twitter:image that is not the og:image", async () => { + const other = cardUrl("site"); await rewrite("faq", (html) => - html - .replace('content="1200"/>', 'content="1201"/>') - .replace('content="image/jpeg"/>', 'content="image/png"/>'), + html.replace( + ``, + ``, + ), ); expect(await audit()).toEqual([ - "/faq/: og:image:width and og:image:height say 1201×630, the file is 1200×630", - "/faq/: og:image:type is image/png, the file is image/jpeg", + `/faq/: twitter:image is ${other}, expected the og:image (${FAQ})`, ]); }); - it("fails a preview that is not an image", async () => { - await write(dist, "og-image.jpg", "x"); - expect((await audit()).filter((f) => f.startsWith("/faq/:"))).toEqual([ - `/faq/: og:image ${PREVIEW} is not a PNG or a JPEG`, + it.each([ + ["Starlight's own en", "en", "og:locale is en, expected en_US"], + ["a bare language", "en-US", "og:locale is en-US, expected en_US"], + ])("fails an og:locale of %s", async (_name, locale, failure) => { + await rewrite("faq", (html) => + html.replace('content="en_US"', `content="${locale}"`), + ); + expect(await audit()).toEqual([`/faq/: ${failure}`]); + }); + + it("fails a page with no og:locale and one with two", async () => { + const tag = ''; + await rewrite("faq", (html) => html.replace(tag, "")); + expect(await audit()).toEqual([ + "/faq/: 0 og:locale tags, expected exactly 1", + ]); + await rewrite("faq", (html) => + html.replace("", `${tag}${tag}`), + ); + expect(await audit()).toEqual([ + "/faq/: 2 og:locale tags, expected exactly 1", ]); }); - it("fails a twitter:image that is not the og:image", async () => { - const other = "https://northguild.dev/worktree/favicon.ico"; + it.each([ + ["og:image:alt", "property"], + ["twitter:image:alt", "name"], + ])("fails an %s that is the page's title", async (tag, kind) => { await rewrite("faq", (html) => html.replace( - ``, - ``, + ``, + ``, ), ); expect(await audit()).toEqual([ - `/faq/: twitter:image is ${other}, expected the og:image (${PREVIEW})`, + `/faq/: ${tag} is the page's title ("faq"), not a description of the card`, + ]); + }); + + it("reads the title from og:title, entities decoded, as the audit does elsewhere", async () => { + await rewrite("faq", (html) => + html + .replace('og:title" content="faq"', 'og:title" content="Q & A"') + .replace("faq ·", "<title>Q & A ·") + .replace(altOf("faq"), "Q & A") + .replace(altOf("faq"), "Q & A"), + ); + const failures = (await audit()).filter((f) => f.includes("title")); + expect(failures).toEqual([ + `/faq/: og:image:alt is the page's title ("Q & A"), not a description of the card`, + `/faq/: twitter:image:alt is the page's title ("Q & A"), not a description of the card`, + ]); + }); + + it("fails a page that names the site card instead of its own", async () => { + const site = cardUrl("site"); + await rewrite("faq", (html) => html.replaceAll(FAQ, site)); + expect(await audit()).toEqual([ + `/faq/: og:image is the site card, expected the page's own (${ORIGIN}og/faq.png)`, + ]); + }); + + it("fails a page that names another page's card", async () => { + await rewrite("faq", (html) => + html.replaceAll(FAQ, cardUrl("changelog")), + ); + expect(await audit()).toEqual([ + "/faq/: og:image names the card changelog, expected faq", + ]); + }); + + it("keys a nested page by its route id, slash kept", async () => { + await rewrite("commands/branch", (html) => + html.replaceAll(cardUrl("commands/branch"), cardUrl("commands")), + ); + expect(await audit()).toEqual([ + "/commands/branch/: og:image names the card commands, expected commands/branch", + ]); + }); + + it("fails the landing when it names a page's card instead of the site card", async () => { + await rewrite("", (html) => + html.replaceAll(cardUrl("site"), cardUrl("faq")), + ); + expect(await audit()).toEqual([ + "/ (root): og:image names the card faq, expected site", + ]); + }); + + // The 404 and /dox/ have rule sets of their own, so the share rules run from auditSite and auditDox for them, with the + // site card as the key; a 404 and a /dox/ that break a rule are named by their own prefix. + it("fails the 404 for a rule broken, and for a card that is not the site's", async () => { + await write(dist, "404.html", notFoundPage()); + await rewrite("", (html) => html); // the landing is untouched + const file = join(dist, "404.html"); + const html = await readFile(file, "utf8"); + await writeFile(file, html.replaceAll(cardUrl("site"), cardUrl("faq"))); + expect(await audit()).toEqual([ + "404.html: og:image names the card faq, expected site", + ]); + await writeFile(file, html.replace('content="en_US"', 'content="en"')); + expect(await audit()).toEqual([ + "404.html: og:locale is en, expected en_US", + ]); + }); + + it("fails /dox/ for a rule broken, and for a card that is not the site's", async () => { + const file = join(dist, "dox/index.html"); + const html = await readFile(file, "utf8"); + await writeFile(file, html.replaceAll(cardUrl("site"), cardUrl("faq"))); + expect(await audit()).toEqual([ + "/dox/: og:image names the card faq, expected site", + ]); + await writeFile( + file, + html.replace(/<meta name="twitter:image:alt"[^>]*>/, ""), + ); + expect(await audit()).toEqual(["/dox/: no twitter:image:alt tag"]); + }); + + it("fails the 404 and /dox/ for a card that is the page's title", async () => { + const file = join(dist, "404.html"); + const html = await readFile(file, "utf8"); + await writeFile(file, html.replaceAll(altOf("site"), "Page not found")); + expect(await audit()).toEqual([ + `404.html: og:image:alt is the page's title ("Page not found"), not a description of the card`, + `404.html: twitter:image:alt is the page's title ("Page not found"), not a description of the card`, ]); + expect(await faqHtml()).toContain(FAQ); }); }); diff --git a/docs/scripts/build-og-art.mjs b/docs/scripts/build-og-art.mjs new file mode 100644 index 00000000..c22d06c4 --- /dev/null +++ b/docs/scripts/build-og-art.mjs @@ -0,0 +1,274 @@ +// Draws the art of the share cards: the dark ground, the hero's branch graph as leaf-sized +// particles, and a bevelled panel where a card's text sits. 1200 by 630, no text. Writes +// docs/src/assets/og-art.png, which the card renderer (docs/src/lib/og-art.ts) draws its text over. +// +// Why it is made this way: +// - A link-preview app may cut the 630-pixel square from the middle of a card (x 285 to 915), so +// the graph and the panel stay inside that square with a margin. Nothing here is read outside it. +// - WhatsApp loads no preview image over 300 KB, so the art is a palette PNG under 307,200 bytes. +// - The graph is the hero's own: buildTargets (docs/src/hero/targets.ts) with a seeded random +// source, so the same picture comes out on every run (the same bytes, on one machine: the PNG's +// deflate differs by CPU, so build-og-art.test.mjs compares the committed file's pixels). +// - Colours are the theme's tokens (docs/src/styles/northguild/tokens.css) as RGB triples, because +// a canvas takes numbers and not CSS variables. build-og-art.test.mjs checks they still match. +// +// Run: node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON docs/scripts/build-og-art.mjs (by hand, never in the build; needs sharp and +// canvaskit-wasm, both docs dev dependencies, and Node's type stripping for targets.ts). It prints +// the WCAG contrast of the text colours against the brightest pixel behind the text, and exits +// non-zero below 4.5:1 without writing anything. + +import { writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import CanvasKitInit from "canvaskit-wasm"; +import sharp from "sharp"; +import { buildTargets } from "../src/hero/targets.ts"; +import { luminance } from "./theme-contrast.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +const require = createRequire(import.meta.url); + +export const OUT = resolve(here, "../src/assets/og-art.png"); +export const WIDTH = 1200; +export const HEIGHT = 630; +/** The square a link-preview app cuts from the middle of the card (x 285 to 915). */ +export const SAFE = { left: 285, right: 915 }; +/** What stays clear of the square's edge, for everything this script draws. */ +export const MARGIN = 28; +/** WhatsApp skips a preview image over 300 KB. */ +export const MAX_BYTES = 307_200; +/** WCAG 2.2, SC 1.4.3: text is at least 4.5:1 against what is behind it. */ +export const MIN_CONTRAST = 4.5; + +/** + * The theme's tokens (--gmt-*) and the hero's leaf greens (--leaf-*, dark theme, in + * docs/src/components/HeroLeaves.astro), as RGB triples. The accent is spring green, not gmt's cyan (D17). + */ +export const COLORS = { + void: [3, 8, 12], + spring: [74, 222, 128], + ice: [207, 234, 242], + iceDim: [152, 178, 190], + leaf2: [34, 197, 94], + leaf3: [134, 239, 172], + leaf4: [22, 163, 74], + leaf5: [52, 211, 153], + leaf6: [190, 242, 100], +}; + +/** The text colours a card uses: the theme's light text and its muted text. */ +export const TEXT_COLORS = { ice: COLORS.ice, iceDim: COLORS.iceDim }; + +/** The hero's graph: how many particles, drawn into a box this tall. */ +const PARTICLES = 3600; +const GRAPH_HEIGHT = HEIGHT - 2 * 36; +export const GRAPH_SCALE = GRAPH_HEIGHT / 470; +export const SEED = 20261129; + +/** + * The panel the text sits on: four straight sides and four 45-degree cuts (the theme's + * `corner-shape: bevel`, enlarged to read at card size), inside the square less a margin. + */ +export const PANEL = { + x: SAFE.left + MARGIN, + y: 175, + w: SAFE.right - SAFE.left - 2 * MARGIN, + h: 280, + bevel: 26, +}; +/** The wash over what is behind the panel: nearly opaque, so the text stays legible over the graph. */ +const WASH_ALPHA = 0.9; +/** Where the text sits: the panel less a padding, the region the contrast is measured over. */ +const TEXT_PAD = 28; +export const TEXT_BOX = { + x: PANEL.x + TEXT_PAD, + y: PANEL.y + TEXT_PAD, + w: PANEL.w - 2 * TEXT_PAD, + h: PANEL.h - 2 * TEXT_PAD, +}; + +/** A small seeded generator (mulberry32), so the graph is the same on every run. */ +export function seededRandom(seed) { + let a = seed >>> 0; + return function next() { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function toColor(CanvasKit, [r, g, b], alpha = 1) { + return CanvasKit.Color(r, g, b, alpha); +} + +/** The graph's leaves: x, y, radius and colour, in card pixels, centred on the square. */ +export function leaves(random) { + const isShape = new Uint8Array(PARTICLES).fill(1); + const { graphX, graphY } = buildTargets({ + count: PARTICLES, + isShape, + joinsLeaf: new Uint8Array(PARTICLES), + // The design box is 380 by 470; the scale fits its height into GRAPH_HEIGHT. + scale: GRAPH_SCALE, + random, + }); + // The design box is not symmetric, so centre the graph's own extent on the square. + const centre = + (SAFE.left + SAFE.right) / 2 - + (Math.min(...graphX) + Math.max(...graphX)) / 2; + // The hero's six greens, the most common first (leaf 1 is the site's spring). + const palette = [ + COLORS.spring, + COLORS.spring, + COLORS.spring, + COLORS.leaf2, + COLORS.leaf2, + COLORS.leaf3, + COLORS.leaf4, + COLORS.leaf5, + COLORS.leaf6, + ]; + return Array.from({ length: PARTICLES }, (_, i) => ({ + x: centre + graphX[i], + // buildTargets returns y up; a canvas is y down. + y: HEIGHT / 2 - graphY[i], + r: 1.4 + random() * 1.6, + color: palette[Math.floor(random() * palette.length)], + alpha: 0.45 + random() * 0.5, + })); +} + +function bevelledPath(CanvasKit, { x, y, w, h, bevel }) { + const r = x + w; + const b = y + h; + return CanvasKit.Path.MakeFromSVGString( + [ + `M${x + bevel} ${y}`, + `L${r - bevel} ${y}`, + `L${r} ${y + bevel}`, + `L${r} ${b - bevel}`, + `L${r - bevel} ${b}`, + `L${x + bevel} ${b}`, + `L${x} ${b - bevel}`, + `L${x} ${y + bevel}`, + "Z", + ].join(" "), + ); +} + +/** The contrast of `color` against the brightest pixel inside `box` of an RGBA buffer. */ +export function worstContrast(pixels, box, color) { + let brightest = 0; + for (let y = Math.floor(box.y); y < Math.ceil(box.y + box.h); y++) { + for (let x = Math.floor(box.x); x < Math.ceil(box.x + box.w); x++) { + const i = (y * WIDTH + x) * 4; + brightest = Math.max( + brightest, + luminance({ r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] }), + ); + } + } + const [r, g, b] = color; + return (luminance({ r, g, b }) + 0.05) / (brightest + 0.05); +} + +/** + * Draws the art. Returns the palette PNG's bytes, the contrast of each text colour, and the + * horizontal extent of what was drawn (the graph's leaves, and the panel). + */ +export async function drawArt() { + const CanvasKit = await CanvasKitInit({ + locateFile: (file) => require.resolve(`canvaskit-wasm/bin/${file}`), + }); + const surface = CanvasKit.MakeSurface(WIDTH, HEIGHT); + if (!surface) throw new Error("CanvasKit could not make a surface"); + const canvas = surface.getCanvas(); + canvas.clear(toColor(CanvasKit, COLORS.void)); + + const all = leaves(seededRandom(SEED)); + const paint = new CanvasKit.Paint(); + paint.setAntiAlias(true); + for (const leaf of all) { + paint.setColor(toColor(CanvasKit, leaf.color, leaf.alpha)); + canvas.drawCircle(leaf.x, leaf.y, leaf.r, paint); + } + const graph = { + left: Math.min(...all.map((l) => l.x - l.r)), + right: Math.max(...all.map((l) => l.x + l.r)), + }; + + // The panel: a wash, a faint spring edge (--gmt-border is spring at 18%), as .gmt-glass draws its bevelled box. + const panel = bevelledPath(CanvasKit, PANEL); + paint.setColor(toColor(CanvasKit, COLORS.void, WASH_ALPHA)); + canvas.drawPath(panel, paint); + paint.setStyle(CanvasKit.PaintStyle.Stroke); + paint.setStrokeWidth(1.5); + paint.setStrokeJoin(CanvasKit.StrokeJoin.Miter); + paint.setColor(toColor(CanvasKit, COLORS.spring, 0.18)); + canvas.drawPath(panel, paint); + panel.delete(); + paint.delete(); + + const pixels = canvas.readPixels(0, 0, { + width: WIDTH, + height: HEIGHT, + colorType: CanvasKit.ColorType.RGBA_8888, + alphaType: CanvasKit.AlphaType.Unpremul, + colorSpace: CanvasKit.ColorSpace.SRGB, + }); + surface.dispose(); + if (!pixels) throw new Error("CanvasKit could not read the pixels back"); + const rgba = Uint8Array.from(pixels); + + const contrast = Object.fromEntries( + Object.entries(TEXT_COLORS).map(([name, color]) => [ + name, + worstContrast(rgba, TEXT_BOX, color), + ]), + ); + const png = await sharp(rgba, { + raw: { width: WIDTH, height: HEIGHT, channels: 4 }, + }) + .removeAlpha() + .png({ + palette: true, + quality: 100, + effort: 1, + dither: 0, + compressionLevel: 9, + }) + .toBuffer(); + return { + png, + contrast, + graph, + panel: { left: PANEL.x, right: PANEL.x + PANEL.w }, + }; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + const { png, contrast, graph, panel } = await drawArt(); + console.log( + `contrast against the brightest pixel behind the text: ice ${contrast.ice.toFixed(2)}:1, ice-dim ${contrast.iceDim.toFixed(2)}:1`, + ); + console.log( + `graph x ${graph.left.toFixed(0)}..${graph.right.toFixed(0)}, panel x ${panel.left}..${panel.right} (safe square ${SAFE.left}..${SAFE.right})`, + ); + const failed = Object.values(contrast).some((c) => c < MIN_CONTRAST); + if (failed || png.length > MAX_BYTES) { + console.error( + failed + ? `a text colour falls below ${MIN_CONTRAST}:1; nothing written` + : `${png.length} bytes is over ${MAX_BYTES}; nothing written`, + ); + process.exit(1); + } + writeFileSync(OUT, png); + console.log(`wrote ${OUT} (${png.length} bytes)`); +} diff --git a/docs/scripts/build-og-art.test.mjs b/docs/scripts/build-og-art.test.mjs new file mode 100644 index 00000000..c0c6f59c --- /dev/null +++ b/docs/scripts/build-og-art.test.mjs @@ -0,0 +1,143 @@ +// @vitest-environment node + +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import sharp from "sharp"; +import { beforeAll, describe, expect, it } from "vitest"; +import { HEAD } from "../src/hero/geometry.ts"; +import { BOX } from "../src/lib/og-art.ts"; +import { + COLORS, + drawArt, + GRAPH_SCALE, + HEIGHT, + leaves, + MARGIN, + MAX_BYTES, + MIN_CONTRAST, + OUT, + SAFE, + SEED, + seededRandom, + TEXT_BOX, + WIDTH, +} from "./build-og-art.mjs"; +import { resolveColor, themeProperties } from "./theme-contrast.mjs"; + +// Oracles, none of them from this script: the card is 1200 x 630 and the safe square is x 285..915 (the +// issue's own figures), WhatsApp skips a preview over 300 KB = 307,200 bytes (the issue), text is at +// least 4.5:1 (WCAG 2.2 AA), and a PNG's IHDR puts the width at byte 16, the height at 20 and the +// colour type at 25, where colour type 3 is a palette (the PNG spec, ISO/IEC 15948 section 11.2.2). +const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; + +describe("the card art", () => { + let first; + let second; + beforeAll(async () => { + first = await drawArt(); + second = await drawArt(); + }, 60_000); + + it("is the same bytes on two runs", () => { + expect(Buffer.compare(first.png, second.png)).toBe(0); + }); + + it("is a 1200 x 630 palette PNG", () => { + expect([...first.png.subarray(0, 8)]).toEqual(PNG_SIGNATURE); + expect(first.png.readUInt32BE(16)).toBe(1200); + expect(first.png.readUInt32BE(20)).toBe(630); + expect(first.png[25]).toBe(3); + expect([WIDTH, HEIGHT]).toEqual([1200, 630]); + }); + + it("is at most 307,200 bytes", () => { + expect(MAX_BYTES).toBe(307_200); + expect(first.png.length).toBeLessThanOrEqual(307_200); + }); + + it("keeps the graph and the panel inside x 285..915 with a margin", () => { + expect([SAFE.left, SAFE.right]).toEqual([285, 915]); + expect(MARGIN).toBe(28); + for (const { left, right } of [first.graph, first.panel]) { + expect(left).toBeGreaterThanOrEqual(285 + 28); + expect(right).toBeLessThanOrEqual(915 - 28); + } + }); + + it("leaves the text at least 4.5:1 against the brightest pixel behind it", () => { + expect(MIN_CONTRAST).toBe(4.5); + for (const value of Object.values(first.contrast)) { + expect(value).toBeGreaterThanOrEqual(4.5); + } + }); + + it("draws HEAD's ring at the top, above the trunk's foot (geometry's y is down)", () => { + // HEAD.at is y -150 in geometry's y-down box, so the card's y is the middle row less 150 scaled. + const headY = HEIGHT / 2 + HEAD.at[1] * GRAPH_SCALE; + const all = leaves(seededRandom(SEED)); + const reach = HEAD.outer * GRAPH_SCALE; + // HEAD's ring is the dense cluster right of the trunk at that height; drawn upside down it would be at the foot. + const atHead = all.filter( + (l) => l.x > 610 && Math.abs(l.y - headY) < reach, + ); + expect(atHead.length).toBeGreaterThan(100); + }); + + it("is the picture the script commits", async () => { + // Pixels, not bytes: sharp's zlib-ng deflates differently by CPU, so the same picture is 24,604 + // bytes on darwin-arm64 and 24,603 on linux-x64 (CI). Decoded, the two are identical. + const pixels = (png) => sharp(png).removeAlpha().raw().toBuffer(); + const [committed, drawn] = await Promise.all([ + pixels(readFileSync(OUT)), + pixels(first.png), + ]); + expect(Buffer.compare(committed, drawn)).toBe(0); + }); +}); + +describe("the renderer's text box", () => { + // The renderer (src/lib/og-art.ts) lays the text out in its own copy of TEXT_BOX. The contrast this + // script measures holds only inside TEXT_BOX, so a panel moved here without the renderer following + // would put the text over ground nobody measured. + it("is the box whose contrast the art was measured over", () => { + expect(BOX).toEqual(TEXT_BOX); + }); +}); + +describe("the leaf greens", () => { + // The hero's palette is in HeroLeaves.astro (:root, the dark theme), not in tokens.css. + const astro = readFileSync( + resolve( + dirname(fileURLToPath(import.meta.url)), + "../src/components/HeroLeaves.astro", + ), + "utf8", + ); + it.each([ + ["leaf2", "--leaf-2"], + ["leaf3", "--leaf-3"], + ["leaf4", "--leaf-4"], + ["leaf5", "--leaf-5"], + ["leaf6", "--leaf-6"], + ])("%s is the hero's %s", (name, prop) => { + const hex = astro.match(new RegExp(`${prop}: (#[0-9a-f]{6})`))?.[1]; + expect(hex).toBeDefined(); + const { r, g, b } = resolveColor(hex, new Map()); + expect(COLORS[name]).toEqual([r, g, b]); + }); +}); + +describe("the colours", () => { + // The tokens are in tokens.css; the script holds them as numbers because a canvas takes numbers. + const properties = themeProperties("dark"); + it.each([ + ["void", "--gmt-void"], + ["spring", "--gmt-spring"], + ["ice", "--gmt-ice"], + ["iceDim", "--gmt-ice-dim"], + ])("%s is the theme's %s", (name, token) => { + const { r, g, b } = resolveColor(`var(${token})`, properties); + expect(COLORS[name]).toEqual([r, g, b]); + }); +}); diff --git a/docs/src/assets/og-art.png b/docs/src/assets/og-art.png new file mode 100644 index 00000000..cf472b69 Binary files /dev/null and b/docs/src/assets/og-art.png differ diff --git a/docs/src/assets/og-fonts/Michroma-OFL.txt b/docs/src/assets/og-fonts/Michroma-OFL.txt new file mode 100644 index 00000000..2d0610cd --- /dev/null +++ b/docs/src/assets/og-fonts/Michroma-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2011 The Michroma Project Authors (https://github.com/googlefonts/Michroma-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/src/assets/og-fonts/Michroma-Regular.ttf b/docs/src/assets/og-fonts/Michroma-Regular.ttf new file mode 100644 index 00000000..59e8c534 Binary files /dev/null and b/docs/src/assets/og-fonts/Michroma-Regular.ttf differ diff --git a/docs/src/components/Head.astro b/docs/src/components/Head.astro index faca032f..b3e24214 100644 --- a/docs/src/components/Head.astro +++ b/docs/src/components/Head.astro @@ -8,10 +8,15 @@ * It also points every page but the 404 at its llms.txt with `rel="describedby"` (D8); the URL is the one llms-txt.ts * renders to, not a third copy of it. * - * The share preview (`og:image`, `twitter:image` and their alt text) and the icon links are site-wide, so they are - * `starlight({ head })` entries in astro.config.mjs rather than anything here (plan §9 Q3). + * The share preview is per page (plan #286 D6): this drops Starlight's `og:locale` (`en`) and any other image entry and + * writes the page's own card (`og-cards.ts` decides which; the landing, the 404 and `/dox/` share `site`) with its type, + * size, alt text and `og:locale` `en_US`. The `?v=` hash is appended after the build by `og-image-version.ts`. The icon + * links stay site-wide `starlight({ head })` entries in astro.config.mjs (plan #240 §9 Q3). */ +import { getCollection } from "astro:content"; import { LLMS_TXT_URL } from "../lib/llms-txt"; +import { ogCards, ogImageAlt } from "../lib/og-cards"; +import { OG_URL_PREFIX } from "../lib/og-image-version"; import { cliVersion } from "../lib/site-meta"; import { buildStructuredData, headTitle } from "../lib/structured-data"; @@ -25,13 +30,44 @@ const namesThisUrl = ({ tag, attrs }: (typeof head)[number]) => (tag === "link" && attrs?.rel === "canonical") || (tag === "meta" && attrs?.property === "og:url"); -const tags = head - .filter((tag) => !(isNotFound && namesThisUrl(tag))) - .map((tag) => - tag.tag === "title" - ? { ...tag, content: headTitle(entry.data.title, siteTitle, "·") } - : tag, - ); +// The card: the page's own when og-cards.ts has one, else the site card (the landing, the 404, and /dox/, which is not +// in the collection). +const cards = ogCards(await getCollection("docs")); +const cardKey = entry.id in cards ? entry.id : "site"; +const imageUrl = `${OG_URL_PREFIX}${cardKey}.png`; +const imageAlt = ogImageAlt(cards[cardKey]); + +const isImageEntry = ({ tag, attrs }: (typeof head)[number]) => + tag === "meta" && + (String(attrs?.property).startsWith("og:image") || + String(attrs?.name).startsWith("twitter:image") || + attrs?.property === "og:locale"); +const meta = (key: "property" | "name", value: string, content: string) => ({ + tag: "meta" as const, + attrs: { [key]: value, content }, + content: undefined, +}); +const shareTags = [ + meta("property", "og:image", imageUrl), + meta("property", "og:image:type", "image/png"), + meta("property", "og:image:width", "1200"), + meta("property", "og:image:height", "630"), + meta("property", "og:image:alt", imageAlt), + meta("name", "twitter:image", imageUrl), + meta("name", "twitter:image:alt", imageAlt), + meta("property", "og:locale", "en_US"), +]; + +const tags = [ + ...head + .filter((tag) => !isImageEntry(tag)) + .filter((tag) => !(isNotFound && namesThisUrl(tag))), + ...shareTags, +].map((tag) => + tag.tag === "title" + ? { ...tag, content: headTitle(entry.data.title, siteTitle, "·") } + : tag, +); // Path relative to the site root: "" for the landing, "getting-started" or "commands/branch" for a nested page. const base = import.meta.env.BASE_URL.replace(/\/$/, ""); diff --git a/docs/src/hero/targets.ts b/docs/src/hero/targets.ts index 333d3591..7bc1129f 100644 --- a/docs/src/hero/targets.ts +++ b/docs/src/hero/targets.ts @@ -25,7 +25,7 @@ import { RINGS, STEM, TRUNK, -} from "./geometry"; +} from "./geometry.ts"; const TAU = Math.PI * 2; diff --git a/docs/src/lib/og-art.test.ts b/docs/src/lib/og-art.test.ts new file mode 100644 index 00000000..2ea7bca1 --- /dev/null +++ b/docs/src/lib/og-art.test.ts @@ -0,0 +1,171 @@ +// @vitest-environment node + +import { readdirSync, readFileSync } from "node:fs"; +import { join, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import sharp from "sharp"; +import { describe, expect, it } from "vitest"; +import { placeCard, renderCard } from "./og-art"; +import { ogCards } from "./og-cards"; + +// Expected values do not come from renderCard. Sources: +// - 1200 x 630 and the safe square x 285..915: the plan's section 8 table (the issue's own figures). +// - 307,200 bytes: WhatsApp skips a preview over 300 KB (the issue); section 8. +// - x 313..887: the safe square less the 28-pixel margin (section 4: 285+28 to 915-28). +// - PNG header: the PNG specification (RFC 2083 / W3C PNG 2nd ed.): signature, then IHDR with width and height as +// big-endian 32-bit at byte 16 and 20, bit depth at 24, colour type at 25; colour type 3 is a palette image. +// - 4.5:1: WCAG 2.2 SC 1.4.3; relative luminance per WCAG 2.2's definition, written out again here. +// - the text colours: --gmt-ice 207,234,242 and --gmt-ice-dim 152,178,190 (docs/src/styles/northguild/tokens.css). +const LEFT = 285 + 28; +const RIGHT = 915 - 28; +const MAX_BYTES = 307_200; +const CONTENT = fileURLToPath(new URL("../content/docs", import.meta.url)); +const ART = resolve( + fileURLToPath(new URL("../assets/og-art.png", import.meta.url)), +); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() + ? sourceFiles(join(dir, entry.name)) + : [join(dir, entry.name)], + ); +} + +function docsEntries() { + return sourceFiles(CONTENT) + .filter((file) => /\.mdx?$/.test(file)) + .map((file) => { + const line = readFileSync(file, "utf8") + .split("\n") + .find((l) => l.startsWith("title: ")); + if (!line) throw new Error(`${file} has no title:`); + return { + id: relative(CONTENT, file) + .replace(/\.mdx?$/, "") + .replace(/\/index$/, ""), // Astro drops a trailing /index from an entry id + data: { title: JSON.parse(line.slice("title: ".length)) as string }, + }; + }); +} + +const cards = ogCards(docsEntries()); +const keys = Object.keys(cards); + +function luminance(r: number, g: number, b: number) { + const lin = (v: number) => { + const c = v / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b); +} + +describe("renderCard", () => { + it("returns a 1200 x 630 palette PNG under 307,200 bytes for the site card and every page", async () => { + expect(keys).toHaveLength(29); + for (const key of keys) { + const png = await renderCard(cards[key]); + const view = Buffer.from(png); + expect(view.subarray(0, 8).toString("hex"), key).toBe("89504e470d0a1a0a"); + expect(view.readUInt32BE(16), `${key} width`).toBe(1200); + expect(view.readUInt32BE(20), `${key} height`).toBe(630); + expect(view[24], `${key} bit depth`).toBeLessThanOrEqual(8); + expect(view[25], `${key} colour type`).toBe(3); + expect(png.length, `${key} bytes`).toBeLessThanOrEqual(MAX_BYTES); + } + }, 120_000); + + it("draws something over the art: a card differs from the bare art", async () => { + const art = await sharp(ART).removeAlpha().raw().toBuffer(); + const card = await sharp( + await renderCard({ kind: "page", title: "worktree branch" }), + ) + .removeAlpha() + .raw() + .toBuffer(); + expect(card.length).toBe(art.length); + expect(card.equals(art)).toBe(false); + }); + + it("throws, naming the title, when even the smallest size needs three lines", async () => { + const title = "an exceedingly long page title ".repeat(12).trim(); + await expect(renderCard({ kind: "page", title })).rejects.toThrow(title); + }); +}); + +describe("placeCard", () => { + it("keeps every line's box inside x 313..887 and in at most two lines", async () => { + for (const key of keys) { + const placed = await placeCard(cards[key]); + for (const box of placed.boxes) { + expect(box.x, `${key} left`).toBeGreaterThanOrEqual(LEFT); + expect(box.x + box.width, `${key} right`).toBeLessThanOrEqual(RIGHT); + } + expect(placed.titleLines, `${key} lines`).toBeLessThanOrEqual(2); + } + }, 60_000); + + it("centres a box in the square (the square's middle is x 600)", async () => { + for (const key of ["site", "commands/branch", "faq"]) { + const { boxes } = await placeCard(cards[key]); + for (const box of boxes) { + expect(box.x + box.width / 2, key).toBeCloseTo(600, 0); + } + } + }); + + it("never shortens a title with an ellipsis", async () => { + for (const key of keys) { + const card = cards[key]; + const text = JSON.stringify(card); + expect(text).not.toContain("…"); + expect((await placeCard(card)).text).toContain( + card.kind === "site" ? "worktree" : card.title, + ); + } + }, 60_000); + + it("has the site card say 'worktree' and its line, on one title line", async () => { + const placed = await placeCard(cards.site); + expect(placed.text).toBe("worktree\nA git worktree for every branch."); + expect(placed.titleLines).toBe(1); + }); + + it("puts text at least 4.5:1 against the brightest art pixel behind each box", async () => { + const { data, info } = await sharp(ART) + .removeAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); + expect([info.width, info.height]).toEqual([1200, 630]); + const ICE = luminance(207, 234, 242); + const ICE_DIM = luminance(152, 178, 190); + for (const key of keys) { + const placed = await placeCard(cards[key]); + for (const box of placed.boxes) { + let brightest = 0; + for ( + let y = Math.floor(box.y); + y < Math.ceil(box.y + box.height); + y++ + ) { + for ( + let x = Math.floor(box.x); + x < Math.ceil(box.x + box.width); + x++ + ) { + const i = (y * 1200 + x) * 3; + brightest = Math.max( + brightest, + luminance(data[i], data[i + 1], data[i + 2]), + ); + } + } + const text = box.color === "ice" ? ICE : ICE_DIM; + expect( + (text + 0.05) / (brightest + 0.05), + `${key}`, + ).toBeGreaterThanOrEqual(4.5); + } + } + }, 60_000); +}); diff --git a/docs/src/lib/og-art.ts b/docs/src/lib/og-art.ts new file mode 100644 index 00000000..cbc820f9 --- /dev/null +++ b/docs/src/lib/og-art.ts @@ -0,0 +1,235 @@ +/** + * Draws a share card: the committed art (`src/assets/og-art.png`, made by `scripts/build-og-art.mjs`) + * with the card's text centred on its panel, as a palette PNG under 300 KB. Michroma only (D8). + * + * Why it is made this way: + * - A link-preview app may cut the 630-pixel square from the middle of the card (x 285 to 915), so the + * text sits in the art's `TEXT_BOX` (x 341..859, y 203..427): inside the square less a 28-pixel margin + * (x 313..887) and inside the region whose contrast the art script measured, so the 4.5:1 it reports + * holds where the text lands. + * - A title takes the largest size that fits two lines and throws when even the smallest does not; + * nothing is ever shortened with an ellipsis. + * - Paths are relative to `docs/`, where the build and the tests run. + */ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { FontMgr, Image, Paragraph } from "canvaskit-wasm"; +import sharp from "sharp"; +import { getCanvasKit } from "./og-canvaskit"; + +export const OG_WIDTH = 1200; +export const OG_HEIGHT = 630; +/** + * The region the art's contrast was measured over (`TEXT_BOX` in `scripts/build-og-art.mjs`), copied as + * numbers so the build does not load the art script; `build-og-art.test.mjs` fails when the two differ. + */ +export const BOX = { x: 341, y: 203, w: 518, h: 224 }; + +/** `--gmt-ice`, the title, and `--gmt-ice-dim`, the site card's line (docs/src/styles/northguild/tokens.css). */ +const ICE: [number, number, number] = [207, 234, 242]; +const ICE_DIM: [number, number, number] = [152, 178, 190]; + +/** A page title's largest size; it shrinks one pixel at a time until it takes two lines at most. */ +const TITLE_MAX = 40; +const TITLE_MIN = 14; +/** The site card's "worktree" (one line) and its line under it (two lines at most). */ +const SITE_NAME_MAX = 64; +const SITE_NAME_MIN = 40; +const LINE_MAX = 24; +const LINE_MIN = 14; +const GAP = 22; + +/** A share card: the site card has a name and a line; a page card is its title alone. */ +export type OgCard = + | { kind: "site"; line: string } + | { kind: "page"; title: string }; + +/** Where one block of text lands, in card pixels (the box of its longest line). */ +export interface OgBox { + x: number; + y: number; + width: number; + height: number; + color: "ice" | "iceDim"; +} + +export interface OgLayout { + /** The text, blocks joined by a newline. */ + text: string; + boxes: OgBox[]; + /** The lines the title takes. */ + titleLines: number; + /** The title's font size. */ + titleSize: number; +} + +const bytes = (path: string) => readFileSync(resolve(process.cwd(), path)); +/** A file's bytes as the exact `ArrayBuffer` CanvasKit's font loader takes. */ +const toArrayBuffer = (file: Uint8Array): ArrayBuffer => + file.buffer.slice( + file.byteOffset, + file.byteOffset + file.byteLength, + ) as ArrayBuffer; + +/** The font and the art, loaded once; every card shares them. */ +let shared: + | { + CanvasKit: Awaited<ReturnType<typeof getCanvasKit>>; + fontMgr: FontMgr; + art: Image; + } + | undefined; +async function load() { + if (shared) return shared; + const CanvasKit = await getCanvasKit(); + const fontMgr = CanvasKit.FontMgr.FromData( + toArrayBuffer(bytes("src/assets/og-fonts/Michroma-Regular.ttf")), + ); + if (!fontMgr) throw new Error("cannot load the card font"); + const art = CanvasKit.MakeImageFromEncoded(bytes("src/assets/og-art.png")); + if (!art) throw new Error("cannot decode the card art"); + shared = { CanvasKit, fontMgr, art }; + return shared; +} + +/** The text blocks of a card, each with the largest size that fits and the colour it is drawn in. */ +async function laidOut(card: OgCard) { + const { CanvasKit, fontMgr } = await load(); + const paragraph = ( + text: string, + size: number, + color: number[], + ): Paragraph => { + const style = new CanvasKit.ParagraphStyle({ + textAlign: CanvasKit.TextAlign.Center, + textStyle: { + color: CanvasKit.Color(color[0], color[1], color[2]), + fontFamilies: ["Michroma"], + fontSize: size, + heightMultiplier: 1.25, + }, + }); + const builder = CanvasKit.ParagraphBuilder.Make(style, fontMgr); + builder.addText(text); + const built = builder.build(); + builder.delete(); + built.layout(BOX.w); + return built; + }; + /** The largest size from `max` down to `min` at which the text fits `lines` lines inside the box. */ + const largestFitting = ( + text: string, + max: number, + min: number, + lines: number, + color: number[], + ) => { + for (let size = max; size >= min; size--) { + const p = paragraph(text, size, color); + if (p.getLineMetrics().length <= lines && p.getLongestLine() <= BOX.w) { + return { p, size }; + } + p.delete(); + } + throw new Error( + `share card text does not fit ${lines} line${lines === 1 ? "" : "s"} at ${min}px: ${text}`, + ); + }; + + const blocks = + card.kind === "site" + ? [ + { + ...largestFitting("worktree", SITE_NAME_MAX, SITE_NAME_MIN, 1, ICE), + color: "ice" as const, + }, + { + ...largestFitting(card.line, LINE_MAX, LINE_MIN, 2, ICE_DIM), + color: "iceDim" as const, + }, + ] + : [ + { + ...largestFitting(card.title, TITLE_MAX, TITLE_MIN, 2, ICE), + color: "ice" as const, + }, + ]; + const height = + blocks.reduce((sum, b) => sum + b.p.getHeight(), 0) + + GAP * (blocks.length - 1); + if (height > BOX.h) { + for (const b of blocks) b.p.delete(); + throw new Error( + `share card text is ${Math.round(height)}px tall, over the ${BOX.h}px box: ${JSON.stringify(card)}`, + ); + } + let y = BOX.y + (BOX.h - height) / 2; + const placed = blocks.map((b) => { + const width = b.p.getLongestLine(); + const at = { + p: b.p, + y, + box: { + x: BOX.x + (BOX.w - width) / 2, + y, + width, + height: b.p.getHeight(), + color: b.color, + } satisfies OgBox, + }; + y += b.p.getHeight() + GAP; + return at; + }); + const layout: OgLayout = { + text: card.kind === "site" ? `worktree\n${card.line}` : card.title, + boxes: placed.map((b) => b.box), + titleLines: blocks[0].p.getLineMetrics().length, + titleSize: blocks[0].size, + }; + return { layout, placed }; +} + +/** Lays a card's text out and returns where it lands. Draws nothing. */ +export async function placeCard(card: OgCard): Promise<OgLayout> { + const { layout, placed } = await laidOut(card); + for (const b of placed) b.p.delete(); + return layout; +} + +/** + * The card as the route serves it: the art with the text over it, as a palette PNG. 256 colours hold the + * art and the anti-aliased text; no dithering, which costs bytes and the art has none. + */ +export async function renderCard(card: OgCard): Promise<Uint8Array> { + const { CanvasKit, art } = await load(); + const { placed } = await laidOut(card); + const surface = CanvasKit.MakeSurface(OG_WIDTH, OG_HEIGHT); + if (!surface) throw new Error("cannot make a surface"); + const canvas = surface.getCanvas(); + canvas.drawImage(art, 0, 0); + for (const b of placed) canvas.drawParagraph(b.p, BOX.x, b.y); + const pixels = canvas.readPixels(0, 0, { + width: OG_WIDTH, + height: OG_HEIGHT, + colorType: CanvasKit.ColorType.RGBA_8888, + alphaType: CanvasKit.AlphaType.Unpremul, + colorSpace: CanvasKit.ColorSpace.SRGB, + }); + // A copy: the surface frees its own memory below. + const rgba = pixels ? Uint8Array.from(pixels as Uint8Array) : undefined; + for (const b of placed) b.p.delete(); + surface.dispose(); + if (!rgba) throw new Error("cannot read the card's pixels back"); + return sharp(rgba, { + raw: { width: OG_WIDTH, height: OG_HEIGHT, channels: 4 }, + }) + .removeAlpha() + .png({ + palette: true, + quality: 100, + effort: 1, + dither: 0, + compressionLevel: 9, + }) + .toBuffer(); +} diff --git a/docs/src/lib/og-canvaskit.ts b/docs/src/lib/og-canvaskit.ts new file mode 100644 index 00000000..f3c26f7e --- /dev/null +++ b/docs/src/lib/og-canvaskit.ts @@ -0,0 +1,21 @@ +/** + * The CanvasKit that draws the share cards, loaded once: `canvaskit-wasm`, the `full` build, because + * only it draws text with a typeface. Node only. It finds the WASM by path (`locateFile`), so the build's + * `/og/` route can load it; Phase 3's build is the proof that it does. + */ +import { createRequire } from "node:module"; +import type { CanvasKit } from "canvaskit-wasm"; + +const require = createRequire(import.meta.url); + +let singleton: Promise<CanvasKit> | undefined; + +export function getCanvasKit(): Promise<CanvasKit> { + singleton ??= import("canvaskit-wasm/full").then(({ default: init }) => + init({ + locateFile: (file: string) => + require.resolve(`canvaskit-wasm/bin/full/${file}`), + }), + ); + return singleton; +} diff --git a/docs/src/lib/og-cards.test.ts b/docs/src/lib/og-cards.test.ts new file mode 100644 index 00000000..0ab13cdb --- /dev/null +++ b/docs/src/lib/og-cards.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment node + +import { readdirSync, readFileSync } from "node:fs"; +import { join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { ogCards, ogImageAlt, SITE_CARD_LINE } from "./og-cards"; + +// Expected values do not come from ogCards. The keys come from D3 of the plan: the route id of each page of +// the site with `/` kept, the landing (`index`) being the site card and the 404 having no card of its own. +// The ids and titles are read from the source files, the way llms-txt.test.ts reads them. +const CONTENT = fileURLToPath(new URL("../content/docs", import.meta.url)); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() + ? sourceFiles(join(dir, entry.name)) + : [join(dir, entry.name)], + ); +} + +function docsEntries() { + return sourceFiles(CONTENT) + .filter((file) => /\.mdx?$/.test(file)) + .map((file) => { + const line = readFileSync(file, "utf8") + .split("\n") + .find((l) => l.startsWith("title: ")); + if (!line) throw new Error(`${file} has no title:`); + return { + id: relative(CONTENT, file) + .replace(/\.mdx?$/, "") + .replace(/\/index$/, ""), // Astro drops a trailing /index from an entry id + data: { title: JSON.parse(line.slice("title: ".length)) as string }, + }; + }); +} + +describe("ogCards", () => { + const entries = docsEntries(); + const cards = ogCards(entries); + + it("reads 30 source files: 29 pages and the 404", () => { + expect(entries).toHaveLength(30); + }); + + it("has the site card and one card per page except the landing and the 404: 29 keys", () => { + // 30 source files, less index (the landing's card is the site card) and 404 (no card), plus `site`. + expect(Object.keys(cards)).toHaveLength(29); + expect(cards).toHaveProperty("site"); + expect(cards).not.toHaveProperty("index"); + expect(cards).not.toHaveProperty("404"); + }); + + it("keys a page by its route id with the slash kept", () => { + expect(cards["commands/branch"]).toEqual({ + kind: "page", + title: "worktree branch: create a git worktree for a new branch", + }); + expect(cards["guides/rex-sessions"]).toMatchObject({ kind: "page" }); + expect(cards.faq).toMatchObject({ kind: "page" }); + }); + + it("gives every page card its own title, and nothing else", () => { + for (const entry of entries) { + if (entry.id === "index" || entry.id === "404") continue; + expect(cards[entry.id]).toEqual({ + kind: "page", + title: entry.data.title, + }); + } + }); + + it("quotes the landing's line on the site card", () => { + // The line is the issue's: the hero's heading. + expect(cards.site).toEqual({ + kind: "site", + line: "A git worktree for every branch.", + }); + expect(SITE_CARD_LINE).toBe("A git worktree for every branch."); + }); +}); + +describe("ogImageAlt", () => { + it("quotes the line on a site card", () => { + expect(ogImageAlt({ kind: "site", line: "A line." })).toContain( + '"A line."', + ); + }); + + it("describes a page card and is never its title alone", () => { + const alt = ogImageAlt({ kind: "page", title: "worktree branch" }); + expect(alt).not.toBe("worktree branch"); + expect(alt).toContain("worktree branch"); + expect(alt.length).toBeGreaterThan("worktree branch".length + 20); + }); +}); diff --git a/docs/src/lib/og-cards.ts b/docs/src/lib/og-cards.ts new file mode 100644 index 00000000..10cd2a78 --- /dev/null +++ b/docs/src/lib/og-cards.ts @@ -0,0 +1,43 @@ +/** + * Which share cards the site has and what each says (D3): `site`, and one card per page keyed by the + * page's route id with `/` kept (`commands/branch`). The landing (`index`) is the site card and the 404 + * has none, so neither gets a page card. Pure, so the `/og/` route and the tests both read it. + */ +import type { OgCard } from "./og-art"; + +/** The line under "worktree" on the site card: the landing's heading. */ +export const SITE_CARD_LINE = "A git worktree for every branch."; + +/** A docs page as the cards read it: its collection id and its frontmatter. */ +export interface OgDocEntry { + id: string; + data: { title: string }; +} + +/** Pages that share the site card instead of having one: the landing, and the 404 (not a shared page). */ +const WITHOUT_OWN_CARD = new Set(["index", "404"]); + +export function ogCards( + entries: readonly OgDocEntry[], +): Record<string, OgCard> { + const cards: Record<string, OgCard> = { + site: { kind: "site", line: SITE_CARD_LINE }, + }; + for (const entry of entries) { + if (WITHOUT_OWN_CARD.has(entry.id)) continue; + cards[entry.id] = { kind: "page", title: entry.data.title }; + } + return cards; +} + +/** + * The alt text of a card (`og:image:alt`, `twitter:image:alt`): what the image shows. The site card + * quotes its line; a page card quotes its title inside a description, so it is never the title alone. + */ +export function ogImageAlt(card: OgCard): string { + const scene = + "in light text on a dark panel over a branching graph of green leaves"; + return card.kind === "site" + ? `Share card for worktree: "${card.line}" ${scene}.` + : `Share card for the page "${card.title}" ${scene}.`; +} diff --git a/docs/src/lib/og-image-version.test.ts b/docs/src/lib/og-image-version.test.ts new file mode 100644 index 00000000..49e1546a --- /dev/null +++ b/docs/src/lib/og-image-version.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment node +import { createHash } from "node:crypto"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { versionDist, versionImageUrls } from "./og-image-version"; + +// Expected values: plan #286 §8 decides the `?v=` value: the first 12 hex characters of the SHA-256 of the built +// PNG's bytes. The expectation is computed here by node:crypto, never by the code under test. The URL prefix is +// D6/§4: https://northguild.dev/worktree/og/<key>.png. +const OG = "https://northguild.dev/worktree/og/"; +const BYTES = new Uint8Array([137, 80, 78, 71, 1, 2, 3, 4]); +const HASH = createHash("sha256").update(BYTES).digest("hex").slice(0, 12); + +// The alt tag's content looks like an image URL on purpose: only og:image and twitter:image may be rewritten. +const ALT = `<meta property="og:image:alt" content="${OG}x.png">`; +const metas = (url: string) => + `<meta property="og:image" content="${url}"><meta name="twitter:image" content="${url}">${ALT}`; + +describe("versionImageUrls", () => { + const knows = (path: string) => (path === "a/b.png" ? HASH : undefined); + + it("appends ?v=<12 hex> to og:image and twitter:image and touches nothing else", () => { + const html = `<head>${metas(`${OG}a/b.png`)}<p>${OG}a/b.png</p></head>`; + const out = versionImageUrls(html, OG, knows); + expect(out).toBe( + `<head>${metas(`${OG}a/b.png?v=${HASH}`)}<p>${OG}a/b.png</p></head>`, + ); + expect(HASH).toMatch(/^[0-9a-f]{12}$/); + }); + + it("fails on a URL that is not a PNG under /worktree/og/", () => { + for (const url of [ + "https://northguild.dev/worktree/share.jpg", + `${OG}a/b.jpg`, + "https://northguild.dev/other/og/a/b.png", + ]) { + expect(() => versionImageUrls(metas(url), OG, knows)).toThrow( + /not a PNG under/, + ); + } + }); + + it("fails on a URL that already has a query", () => { + expect(() => + versionImageUrls(metas(`${OG}a/b.png?v=abc`), OG, knows), + ).toThrow(/already has a query/); + }); + + it("fails on a PNG it cannot find", () => { + expect(() => versionImageUrls(metas(`${OG}a/c.png`), OG, knows)).toThrow( + /not in the build/, + ); + }); +}); + +describe("versionDist", () => { + let root: string; + const write = (rel: string, content: string | Uint8Array) => { + const target = join(root, rel); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, content); + }; + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "og-version-")); + }); + afterEach(() => rmSync(root, { recursive: true, force: true })); + + it("rewrites every built page from the PNG found in the build", () => { + write("og/commands/branch.png", BYTES); + write("commands/branch/index.html", metas(`${OG}commands/branch.png`)); + versionDist(root, OG); + expect(readFileSync(join(root, "commands/branch/index.html"), "utf8")).toBe( + metas(`${OG}commands/branch.png?v=${HASH}`), + ); + }); + + it("names the page and the URL when the PNG is missing", () => { + write("faq/index.html", metas(`${OG}faq.png`)); + expect(() => versionDist(root, OG)).toThrow( + new RegExp(`faq/index\\.html.*${OG}faq\\.png`), + ); + }); +}); diff --git a/docs/src/lib/og-image-version.ts b/docs/src/lib/og-image-version.ts new file mode 100644 index 00000000..12c5c44f --- /dev/null +++ b/docs/src/lib/og-image-version.ts @@ -0,0 +1,106 @@ +/** + * Puts `?v=<hash>` on the share image URLs of the built pages (plan #286 D5). + * + * Platforms cache an image by its URL, so a redrawn card under the same URL stays stale. The hash is the first 12 hex + * characters of the SHA-256 of the PNG's bytes, so the URL changes exactly when the image does. The PNGs and the pages + * are made in the same build in no fixed order, so the rewrite runs afterwards, on `astro:build:done`, over the built HTML. + * + * It is listed before `starlight()` in astro.config.mjs: hooks run in list order, so every later hook reads the final HTML. + */ +import { createHash } from "node:crypto"; +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { AstroIntegration } from "astro"; + +/** Where the cards are served: the `og:image` URL of every page starts with this. */ +export const OG_URL_PREFIX = "https://northguild.dev/worktree/og/"; + +/** The first 12 hex characters of the SHA-256 of a file's bytes. */ +export function imageHash(bytes: Uint8Array): string { + return createHash("sha256").update(bytes).digest("hex").slice(0, 12); +} + +/** A start tag of `<meta property="og:image">` or `<meta name="twitter:image">` (not `og:image:alt` and the like). */ +const IMAGE_META = + /<meta\b(?=[^>]*\b(?:property="og:image"|name="twitter:image")[\s/>])[^>]*>/g; + +const CONTENT = /(\bcontent=")([^"]*)(")/; + +/** + * `html` with `?v=<hash>` after the URL in `og:image` and `twitter:image`, every other byte unchanged. `hashOf` gets + * the PNG's path under the prefix (`commands/branch.png`) and returns its hash, or undefined when the build has no such + * file. Throws for a URL with a query already, one that is not a PNG under `prefix`, and a PNG `hashOf` does not know. + */ +export function versionImageUrls( + html: string, + prefix: string, + hashOf: (path: string) => string | undefined, +): string { + return html.replace(IMAGE_META, (tag) => + tag.replace(CONTENT, (_all, open: string, url: string, close: string) => { + if (url.includes("?")) { + throw new Error(`share image URL "${url}" already has a query`); + } + if (!url.startsWith(prefix) || !url.endsWith(".png")) { + throw new Error( + `share image URL "${url}" is not a PNG under ${prefix}`, + ); + } + const path = url.slice(prefix.length); + const hash = hashOf(path); + if (hash === undefined) { + throw new Error(`share image ${url} is not in the build (og/${path})`); + } + return `${open}${url}?v=${hash}${close}`; + }), + ); +} + +function htmlFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = join(dir, entry.name); + if (entry.isDirectory()) return htmlFiles(full); + return entry.name.endsWith(".html") ? [full] : []; + }); +} + +/** Versions the share image URLs of every page under `root` (the build output, whose `og/` folder holds the cards). */ +export function versionDist(root: string, prefix: string): void { + const hashes = new Map<string, string | undefined>(); + const hashOf = (path: string): string | undefined => { + if (!hashes.has(path)) { + const file = join(root, "og", path); + hashes.set( + path, + existsSync(file) ? imageHash(readFileSync(file)) : undefined, + ); + } + return hashes.get(path); + }; + for (const file of htmlFiles(root)) { + const html = readFileSync(file, "utf8"); + try { + const next = versionImageUrls(html, prefix, hashOf); + if (next !== html) writeFileSync(file, next); + } catch (error) { + throw new Error( + `[og-image-version] ${file}: ${error instanceof Error ? error.message : String(error)}`, + { + cause: error, + }, + ); + } + } +} + +export function versionOgImages(): AstroIntegration { + return { + name: "worktree-version-og-images", + hooks: { + "astro:build:done": ({ dir }) => { + versionDist(fileURLToPath(dir), OG_URL_PREFIX); + }, + }, + }; +} diff --git a/docs/src/pages/og/[...route].ts b/docs/src/pages/og/[...route].ts new file mode 100644 index 00000000..9cc54115 --- /dev/null +++ b/docs/src/pages/og/[...route].ts @@ -0,0 +1,25 @@ +/** + * /worktree/og/<id>.png (D2, D3): one share card per key of `ogCards`, `site` and one per docs page, drawn at + * build time by `renderCard`. The key keeps its `/`, so `commands/branch` is `og/commands/branch.png`. + */ +import { getCollection } from "astro:content"; +import type { APIRoute, GetStaticPaths } from "astro"; +import { renderCard } from "../../lib/og-art"; +import { ogCards } from "../../lib/og-cards"; + +export const getStaticPaths = (async () => { + const cards = ogCards(await getCollection("docs")); + return Object.entries(cards).map(([key, card]) => ({ + params: { route: `${key}.png` }, + props: { card }, + })); +}) satisfies GetStaticPaths; + +export const GET: APIRoute< + Awaited<ReturnType<typeof getStaticPaths>>[number]["props"] +> = async ({ props }) => { + const png = await renderCard(props.card); + return new Response(png as Uint8Array<ArrayBuffer>, { + headers: { "Content-Type": "image/png" }, + }); +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6ed812b5..4ccf53c8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -321,6 +321,9 @@ importers: '@types/react-dom': specifier: ^19.3.0 version: 19.3.0(@types/react@19.3.0) + canvaskit-wasm: + specifier: 0.42.0 + version: 0.42.0 concurrently: specifier: ^10.0.6 version: 10.0.6 @@ -330,6 +333,9 @@ importers: playwright: specifier: ^1.65.0 version: 1.65.0 + sharp: + specifier: 0.35.5 + version: 0.35.5(@types/node@24.19.2) tsup: specifier: ^9.0.0 version: 9.0.0(jiti@2.7.0)(postcss@8.5.31)(typescript@5.9.3)(yaml@2.9.1) @@ -2315,6 +2321,9 @@ packages: '@vscode/l10n@0.0.18': resolution: {integrity: sha512-KYSIHVmslkaCDyw013pphY+d7x1qV8IZupYfeIfzNA+nsaWHbn5uPuQRvdRFsa9zFzGeudPuoGoZ1Op4jrJXIQ==} + '@webgpu/types@0.1.21': + resolution: {integrity: sha512-pUrWq3V5PiSGFLeLxoGqReTZmiiXwY3jRkIG5sLLKjyqNxrwm/04b4nw7LSmGWJcKk59XOM/YRTUwOzo4MMlow==} + acorn-walk@8.3.5: resolution: {integrity: sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==} engines: {node: '>=0.4.0'} @@ -2468,6 +2477,9 @@ packages: resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} engines: {node: '>=20.19.0'} + canvaskit-wasm@0.42.0: + resolution: {integrity: sha512-N3ikotmzYwDVAcpQKDMptBT2P5pIEWS9ywdmrQA2awwaMF9cxKEFuxZZHv9ay1Em9kDjxDsPtwUzDm1uNj136g==} + ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -6616,6 +6628,8 @@ snapshots: '@vscode/l10n@0.0.18': {} + '@webgpu/types@0.1.21': {} + acorn-walk@8.3.5: dependencies: acorn: 8.19.0 @@ -6816,6 +6830,10 @@ snapshots: cac@7.1.0: {} + canvaskit-wasm@0.42.0: + dependencies: + '@webgpu/types': 0.1.21 + ccount@2.0.1: {} chai@6.3.0: {}