Skip to content

Commit 41018dd

Browse files
TMHSDigitalclaude
andcommitted
Retake the README screenshot automatically after pushes to main
docs/images/readme/og-card.png (the README hero and the og:image) shows the entry count, and was retaken by hand, so it lagged every new source: the README read 421 sources above a screenshot saying 420. - site/og-card.mjs (npm run og-card): serves site/dist in-process and captures the top 1200x630 of the home page with headless Chrome, light mode, no scrollbar, fresh profile. No dependencies; CHROME_PATH picks the browser. Writes only when the bytes differ. - .github/workflows/og-card.yml: after a push to main touching catalog/, docs/, site/ or top-level Markdown, builds, captures, and commits the PNG to main when it changed, then dispatches pages.yml so the deployed og:image matches. Capture runs read-only; publish takes only a checked 1200x630 PNG from the artifact (the thumbs.yml split). - serve.mjs exports createSiteServer for the in-process server. - sync-counts and site/README "Social preview" describe the new flow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 791d4b3 commit 41018dd

8 files changed

Lines changed: 330 additions & 22 deletions

File tree

‎.github/workflows/og-card.yml‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
name: Retake the README screenshot
2+
3+
# docs/images/readme/og-card.png is the README screenshot and the site's
4+
# og:image, and it shows the entry count. After a push to main that can change
5+
# the home page, build the site, capture its first 1200x630 (site/og-card.mjs,
6+
# headless Chrome), and commit the PNG to main only when it differs. Then
7+
# redeploy Pages, because a push made with GITHUB_TOKEN does not start
8+
# pages.yml, and the deployed og:image would otherwise lag a week.
9+
#
10+
# Two jobs, as in thumbs.yml. `capture` runs the build and a browser with a
11+
# read-only token and no stored git credentials. `publish` holds the write
12+
# token, runs no repository code, and takes only one checked PNG from the
13+
# first job's artifact.
14+
on:
15+
push:
16+
branches: [main]
17+
paths:
18+
- "catalog/**"
19+
- "docs/**"
20+
- "site/**"
21+
- "*.md"
22+
- "!docs/images/readme/og-card.png"
23+
workflow_dispatch:
24+
25+
permissions:
26+
contents: read
27+
28+
# A newer push supersedes a capture that has not landed yet.
29+
concurrency:
30+
group: og-card
31+
cancel-in-progress: true
32+
33+
jobs:
34+
capture:
35+
runs-on: ubuntu-latest
36+
timeout-minutes: 10
37+
permissions:
38+
contents: read
39+
steps:
40+
- name: Checkout
41+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
42+
with:
43+
persist-credentials: false
44+
# The home page's "new in the last 30 days" reads git history, as in pages.yml.
45+
fetch-depth: 0
46+
47+
- name: Setup Node
48+
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
49+
with:
50+
node-version-file: .nvmrc
51+
52+
- name: Build
53+
run: npm run build
54+
55+
- name: Capture
56+
run: |
57+
google-chrome --version
58+
node site/og-card.mjs --out "$RUNNER_TEMP/og-card.png"
59+
60+
- name: Upload the capture
61+
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
62+
with:
63+
name: og-card
64+
path: ${{ runner.temp }}/og-card.png
65+
retention-days: 7
66+
if-no-files-found: error
67+
68+
publish:
69+
needs: capture
70+
runs-on: ubuntu-latest
71+
timeout-minutes: 10
72+
permissions:
73+
contents: write
74+
actions: write
75+
steps:
76+
- name: Checkout
77+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
78+
79+
- name: Download the capture
80+
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
81+
with:
82+
name: og-card
83+
path: ${{ runner.temp }}/og-card
84+
85+
- name: Take only a 1200x630 PNG
86+
env:
87+
SRC: ${{ runner.temp }}/og-card/og-card.png
88+
run: |
89+
test -f "$SRC" && ! test -L "$SRC"
90+
file -b "$SRC" | grep -Eq '^PNG image data, 1200 x 630,'
91+
cp "$SRC" docs/images/readme/og-card.png
92+
93+
- name: Commit to main and redeploy Pages
94+
env:
95+
GH_TOKEN: ${{ github.token }}
96+
run: |
97+
if git diff --quiet -- docs/images/readme/og-card.png; then
98+
echo "Screenshot unchanged."
99+
exit 0
100+
fi
101+
git config user.name "github-actions[bot]"
102+
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
103+
git add docs/images/readme/og-card.png
104+
git commit -m "Retake the README screenshot for ${GITHUB_SHA::7}"
105+
# main may have moved while the capture ran; the PNG is the only change.
106+
git pull --rebase --quiet origin main
107+
git push origin HEAD:main
108+
gh workflow run pages.yml --ref main

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"thumbs": "node site/thumbs.mjs",
2323
"reverify": "node site/reverify-batch.mjs",
2424
"serve": "node site/serve.mjs",
25+
"og-card": "node site/og-card.mjs",
2526
"coverage": "node site/coverage.mjs"
2627
}
2728
}

‎site/README.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,13 @@ with `node site/reverify-batch.mjs` (`npm run reverify`).
196196

197197
`docs/images/readme/og-card.png` is a 1200x630 screenshot of this site's first screen.
198198
`build.mjs` copies it into `dist` and emits the `og:image` and `twitter:image` tags. The
199-
README shows it too, and the hero states the entry count, so retake it whenever that count
200-
changes (`npm run counts` reminds you) or the hero changes: `npm run build && npm run serve`,
201-
then capture the top 1200x630 of `http://127.0.0.1:3000/` in light mode, with no scrollbar.
199+
README shows it too, and the hero states the entry count, so it is retaken whenever the
200+
home page can change. `.github/workflows/og-card.yml` runs after each push to main that
201+
touches `catalog/`, `docs/`, `site/` or the top-level Markdown: it builds the site, captures
202+
the top 1200x630 of the home page in light mode with no scrollbar (`site/og-card.mjs`,
203+
headless Chrome), commits the PNG to main only when it differs, and redeploys Pages so the
204+
`og:image` matches. To retake it by hand: `npm run build && npm run og-card` (set
205+
`CHROME_PATH` if Chrome, Chromium or Edge is not found).
202206

203207
## Commands
204208

‎site/lib/lib.test.mjs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2825,6 +2825,28 @@ await section("plugin feed (#277)", async () => {
28252825
eq("plugin feed: schema refuses an unknown entry key", schemaErrors(schema, { ...feed, entries: [{ ...feed.entries[0], extra: 1 }] }).length > 0, true);
28262826
});
28272827

2828+
await section("og card capture", async () => {
2829+
const { chromeArgs, chromeCandidates, pngSize } = await import("./og-card.mjs");
2830+
const ihdr = Buffer.alloc(24);
2831+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(ihdr, 0);
2832+
ihdr.write("IHDR", 12, "latin1");
2833+
ihdr.writeUInt32BE(1200, 16);
2834+
ihdr.writeUInt32BE(630, 20);
2835+
eq("og card: PNG size read from IHDR", JSON.stringify(pngSize(ihdr)), '{"width":1200,"height":630}');
2836+
eq("og card: not a PNG", pngSize(Buffer.from("GIF89a-not-a-png-at-all!")), null);
2837+
eq("og card: too short", pngSize(ihdr.subarray(0, 20)), null);
2838+
eq("og card: not a buffer", pngSize("png"), null);
2839+
eq("og card: CHROME_PATH first", chromeCandidates("linux", { CHROME_PATH: "/x/chrome" })[0], "/x/chrome");
2840+
eq("og card: linux looks on PATH", chromeCandidates("linux", {}).includes("google-chrome"), true);
2841+
eq("og card: windows uses Program Files", chromeCandidates("win32", { PROGRAMFILES: "C:\\PF" })[0], "C:\\PF\\Google\\Chrome\\Application\\chrome.exe");
2842+
const args = chromeArgs({ url: "http://127.0.0.1:1/", out: "/t/o.png", profileDir: "/t/p" });
2843+
eq("og card: url is the last argument", args.at(-1), "http://127.0.0.1:1/");
2844+
eq("og card: 1200x630 window", args.includes("--window-size=1200,630"), true);
2845+
eq("og card: no scrollbar", args.includes("--hide-scrollbars"), true);
2846+
eq("og card: light mode", args.includes("--blink-settings=preferredColorScheme=1"), true);
2847+
eq("og card: fresh profile", args.includes("--user-data-dir=/t/p"), true);
2848+
});
2849+
28282850
/* report (keep last) ------------------------------------------------------ */
28292851
if (failures.length) {
28302852
console.error(`lib.test failed (${failures.length}):`);

‎site/lib/og-card.mjs‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Pure helpers for site/og-card.mjs, the script that retakes
3+
* docs/images/readme/og-card.png (the README screenshot and the social card).
4+
*/
5+
import path from "node:path";
6+
7+
export const OG_CARD_WIDTH = 1200;
8+
export const OG_CARD_HEIGHT = 630;
9+
10+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11+
12+
/** `{ width, height }` from a PNG's IHDR chunk, or null when the bytes are not a PNG. */
13+
export function pngSize(buf) {
14+
if (!Buffer.isBuffer(buf) || buf.length < 24) return null;
15+
if (!buf.subarray(0, 8).equals(PNG_SIGNATURE)) return null;
16+
if (buf.toString("latin1", 12, 16) !== "IHDR") return null;
17+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
18+
}
19+
20+
/**
21+
* Where to look for Chrome, Chromium or Edge, most specific first. `env.CHROME_PATH`
22+
* wins; bare names are looked up on PATH by the caller.
23+
*/
24+
export function chromeCandidates(platform, env = {}) {
25+
const list = [];
26+
if (env.CHROME_PATH) list.push(env.CHROME_PATH);
27+
if (platform === "win32") {
28+
for (const base of [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].filter(Boolean)) {
29+
list.push(path.win32.join(base, "Google", "Chrome", "Application", "chrome.exe"));
30+
list.push(path.win32.join(base, "Microsoft", "Edge", "Application", "msedge.exe"));
31+
}
32+
} else if (platform === "darwin") {
33+
list.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
34+
list.push("/Applications/Chromium.app/Contents/MacOS/Chromium");
35+
list.push("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge");
36+
} else {
37+
list.push("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge");
38+
}
39+
return list;
40+
}
41+
42+
/**
43+
* The headless Chrome arguments for one 1200x630 light-mode capture of `url`
44+
* into `out`, with a fresh profile so no stored theme choice applies.
45+
*/
46+
export function chromeArgs({ url, out, profileDir }) {
47+
return [
48+
"--headless=new",
49+
"--disable-gpu",
50+
"--hide-scrollbars",
51+
"--no-first-run",
52+
"--no-default-browser-check",
53+
"--disable-extensions",
54+
"--force-color-profile=srgb",
55+
"--force-device-scale-factor=1",
56+
"--blink-settings=preferredColorScheme=1",
57+
`--user-data-dir=${profileDir}`,
58+
`--window-size=${OG_CARD_WIDTH},${OG_CARD_HEIGHT}`,
59+
// Lets fonts, scripts and the lazy thumbnails finish before the capture.
60+
"--virtual-time-budget=10000",
61+
`--screenshot=${out}`,
62+
url,
63+
];
64+
}

‎site/og-card.mjs‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Retakes docs/images/readme/og-card.png, the README screenshot and the
4+
* site's social card: the top 1200x630 of the built home page, light mode,
5+
* no scrollbar, through headless Chrome (or Chromium, or Edge). No dependencies.
6+
*
7+
* npm run build && node site/og-card.mjs [--out <file.png>]
8+
*
9+
* Set CHROME_PATH to pick the browser. .github/workflows/og-card.yml runs
10+
* this after each push to main that can change the home page, and commits
11+
* the result when it differs.
12+
*/
13+
import { spawn, spawnSync } from "node:child_process";
14+
import fs from "node:fs";
15+
import os from "node:os";
16+
import path from "node:path";
17+
import { fileURLToPath } from "node:url";
18+
import { cliArgs } from "./lib/cli.mjs";
19+
import { chromeArgs, chromeCandidates, OG_CARD_HEIGHT, OG_CARD_WIDTH, pngSize } from "./lib/og-card.mjs";
20+
import { OG_CARD_NAME } from "./lib/shared.mjs";
21+
import { createSiteServer } from "./serve.mjs";
22+
23+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
24+
const ROOT = path.join(__dirname, "..");
25+
const DIST = path.join(__dirname, "dist");
26+
const DEFAULT_OUT = path.join(ROOT, "docs", "images", "readme", OG_CARD_NAME);
27+
28+
/** The first candidate that runs `--version`, or null. */
29+
function findChrome() {
30+
for (const bin of chromeCandidates(process.platform, process.env)) {
31+
if (path.isAbsolute(bin) && !fs.existsSync(bin)) continue;
32+
// Chrome on Windows prints nothing for --version; existing is enough there.
33+
if (process.platform === "win32") return bin;
34+
const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 20000 });
35+
if (r.status === 0) return bin;
36+
}
37+
return null;
38+
}
39+
40+
/** Runs `bin` to completion (or kills it after `timeoutMs`); resolves `{ status, stderr }`. */
41+
function run(bin, args, timeoutMs) {
42+
return new Promise((resolve) => {
43+
const child = spawn(bin, args, { stdio: ["ignore", "ignore", "pipe"] });
44+
let stderr = "";
45+
child.stderr.on("data", (d) => (stderr += d));
46+
const timer = setTimeout(() => child.kill(), timeoutMs);
47+
child.on("error", (err) => {
48+
clearTimeout(timer);
49+
resolve({ status: null, stderr: String(err.message) });
50+
});
51+
child.on("close", (status) => {
52+
clearTimeout(timer);
53+
resolve({ status, stderr });
54+
});
55+
});
56+
}
57+
58+
async function main() {
59+
const { values: flags } = cliArgs({ out: { type: "string" } }, "node site/og-card.mjs [--out <file.png>]");
60+
const out = path.resolve(flags.out ?? DEFAULT_OUT);
61+
if (!fs.existsSync(path.join(DIST, "index.html"))) {
62+
console.error("site/dist has no index.html; run npm run build first");
63+
process.exit(1);
64+
}
65+
const chrome = findChrome();
66+
if (!chrome) {
67+
console.error("No Chrome, Chromium or Edge found; set CHROME_PATH");
68+
process.exit(1);
69+
}
70+
71+
const server = createSiteServer(DIST);
72+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
73+
const { port } = server.address();
74+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "og-card-"));
75+
const shot = path.join(tmp, "shot.png");
76+
try {
77+
// Async: the server runs in this process, so a blocking spawn would starve it.
78+
const r = await run(chrome, chromeArgs({ url: `http://127.0.0.1:${port}/`, out: shot, profileDir: path.join(tmp, "profile") }), 120000);
79+
if (!fs.existsSync(shot)) {
80+
console.error(`Chrome wrote no screenshot (exit ${r.status}).\n${r.stderr}`);
81+
process.exitCode = 1;
82+
return;
83+
}
84+
const size = pngSize(fs.readFileSync(shot));
85+
if (!size || size.width !== OG_CARD_WIDTH || size.height !== OG_CARD_HEIGHT) {
86+
console.error(`Expected a ${OG_CARD_WIDTH}x${OG_CARD_HEIGHT} PNG, got ${size ? `${size.width}x${size.height}` : "no PNG"}`);
87+
process.exitCode = 1;
88+
return;
89+
}
90+
const before = fs.existsSync(out) ? fs.readFileSync(out) : null;
91+
const after = fs.readFileSync(shot);
92+
if (before && before.equals(after)) {
93+
console.log(`${path.relative(ROOT, out)} unchanged`);
94+
} else {
95+
fs.mkdirSync(path.dirname(out), { recursive: true });
96+
fs.writeFileSync(out, after);
97+
console.log(`Wrote ${path.relative(ROOT, out)} (${OG_CARD_WIDTH}x${OG_CARD_HEIGHT}, ${after.length} bytes)`);
98+
}
99+
} finally {
100+
server.close();
101+
fs.rmSync(tmp, { recursive: true, force: true });
102+
}
103+
}
104+
105+
await main();

‎site/serve.mjs‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -87,34 +87,38 @@ function send(req, res, status, file) {
8787
else fs.createReadStream(file).pipe(res);
8888
}
8989

90-
function main() {
91-
const { values: flags } = cliArgs({ port: { type: "string" } }, "node site/serve.mjs [--port <1-65535>]");
92-
const port = Number(flags.port ?? (process.env.PORT || 3000));
93-
if (!Number.isInteger(port) || port < 1 || port > 65535) {
94-
console.error("usage: node site/serve.mjs [--port <1-65535>]");
95-
process.exit(2);
96-
}
97-
if (!fs.existsSync(path.join(DIST, "index.html"))) {
98-
console.error("site/dist has no index.html; run npm run build first");
99-
process.exit(1);
100-
}
101-
const server = http.createServer((req, res) => {
90+
/** An http.Server (not yet listening) that serves `root` as described above. */
91+
export function createSiteServer(root = DIST) {
92+
return http.createServer((req, res) => {
10293
if (req.method !== "GET" && req.method !== "HEAD") {
10394
res.writeHead(405, { allow: "GET, HEAD" }).end();
10495
return;
10596
}
106-
const location = slashRedirect(DIST, req.url || "/");
97+
const location = slashRedirect(root, req.url || "/");
10798
if (location) {
10899
res.writeHead(301, { location, "cache-control": "no-store" }).end();
109100
return;
110101
}
111-
const file = resolveRequest(DIST, req.url || "/");
102+
const file = resolveRequest(root, req.url || "/");
112103
if (file) return send(req, res, 200, file);
113-
const notFound = path.join(DIST, "404.html");
104+
const notFound = path.join(root, "404.html");
114105
if (fs.existsSync(notFound)) return send(req, res, 404, notFound);
115106
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("Not found\n");
116107
});
117-
server.listen(port, "127.0.0.1", () => console.log(`Serving site/dist at http://127.0.0.1:${port}/ (Ctrl+C to stop)`));
108+
}
109+
110+
function main() {
111+
const { values: flags } = cliArgs({ port: { type: "string" } }, "node site/serve.mjs [--port <1-65535>]");
112+
const port = Number(flags.port ?? (process.env.PORT || 3000));
113+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
114+
console.error("usage: node site/serve.mjs [--port <1-65535>]");
115+
process.exit(2);
116+
}
117+
if (!fs.existsSync(path.join(DIST, "index.html"))) {
118+
console.error("site/dist has no index.html; run npm run build first");
119+
process.exit(1);
120+
}
121+
createSiteServer(DIST).listen(port, "127.0.0.1", () => console.log(`Serving site/dist at http://127.0.0.1:${port}/ (Ctrl+C to stop)`));
118122
}
119123

120124
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();

0 commit comments

Comments
 (0)