Skip to content

Commit d22b975

Browse files
TMHSDigitalclaude
andcommitted
Give every entry page its own social card (#117)
All entry pages shared the site's og-card.png, so a shared link to one entry looked like the home page on Discord, X or Slack. - site/entry-cards.mjs renders entry/<id>/card.png for every entry page: the entry's name, category, licence, commercial verdict, status when not active, and the date the licence was read, in the site's fonts and colours. One headless Chrome is driven over the DevTools protocol with Node's built-in WebSocket (no dependencies), so all 426 cards take about a minute (npm run entry-cards). - ci.yml renders them before the Pages upload; they are build output, never committed. A render failure stops the deploy rather than shipping a missing og:image. - Entry pages point og:image, twitter:image and the alt text at their own card (baseHeadHtml ownCard); other pages keep the site card. - Tests cover the card template, its escaping and the head tags. The badge half of #117 shipped earlier; publishers displaying it is outreach, not code. Fixes #117 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f134aae commit d22b975

7 files changed

Lines changed: 245 additions & 8 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,14 @@ jobs:
5757
git fetch --no-tags --depth=1 origin "$BASE_SHA"
5858
node site/pr-diff.mjs --base "$BASE_SHA" --out "$GITHUB_STEP_SUMMARY"
5959
60+
# Deploys only: each entry page's own social card (#117), rendered with
61+
# the runner's Chrome into site/dist/entry/<id>/card.png. Build output,
62+
# never committed; a failure stops the deploy rather than shipping pages
63+
# whose og:image is missing.
64+
- name: Render per-entry social cards
65+
if: ${{ inputs.upload-dist }}
66+
run: npm run entry-cards
67+
6068
- name: Upload Pages artifact
6169
if: ${{ inputs.upload-dist }}
6270
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"reverify": "node site/reverify-batch.mjs",
2424
"serve": "node site/serve.mjs",
2525
"og-card": "node site/og-card.mjs",
26-
"coverage": "node site/coverage.mjs"
26+
"coverage": "node site/coverage.mjs",
27+
"entry-cards": "node site/entry-cards.mjs"
2728
}
2829
}

‎site/entry-cards.mjs‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Renders each listed entry's own social card, site/dist/entry/<id>/card.png
4+
* (#117), which the entry page's og:image points at. Run after the build:
5+
*
6+
* npm run build && node site/entry-cards.mjs
7+
*
8+
* One headless Chrome (or Chromium, or Edge; set CHROME_PATH to pick) is
9+
* driven over the DevTools protocol, so the whole catalog takes about a
10+
* minute instead of one browser launch per entry. No dependencies: Node's
11+
* built-in WebSocket speaks the protocol. The cards are build output only,
12+
* never committed; ci.yml renders them before the Pages upload.
13+
*/
14+
import { spawn, spawnSync } from "node:child_process";
15+
import fs from "node:fs";
16+
import os from "node:os";
17+
import path from "node:path";
18+
import { fileURLToPath } from "node:url";
19+
import { chromeCandidates, ENTRY_CARD_NAME, entryCardHtml, OG_CARD_HEIGHT, OG_CARD_WIDTH, pngSize } from "./lib/og-card.mjs";
20+
import { createSiteServer } from "./serve.mjs";
21+
22+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
23+
const DIST = path.join(__dirname, "dist");
24+
const STAGE = "_entry-cards";
25+
26+
function findChrome() {
27+
for (const bin of chromeCandidates(process.platform, process.env)) {
28+
if (path.isAbsolute(bin) && !fs.existsSync(bin)) continue;
29+
if (process.platform === "win32") return bin;
30+
const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 20000 });
31+
if (r.status === 0) return bin;
32+
}
33+
return null;
34+
}
35+
36+
/** Resolves the browser's DevTools WebSocket URL once Chrome writes DevToolsActivePort. */
37+
async function devtoolsUrl(profileDir, child) {
38+
const file = path.join(profileDir, "DevToolsActivePort");
39+
for (let i = 0; i < 300; i++) {
40+
if (child.exitCode !== null) throw new Error(`Chrome exited early (${child.exitCode})`);
41+
if (fs.existsSync(file)) {
42+
const [port, wsPath] = fs.readFileSync(file, "utf8").split("\n");
43+
if (port && wsPath) return `ws://127.0.0.1:${port.trim()}${wsPath.trim()}`;
44+
}
45+
await new Promise((r) => setTimeout(r, 100));
46+
}
47+
throw new Error("Chrome did not open a DevTools port in 30 s");
48+
}
49+
50+
/** A minimal DevTools protocol client: send(method, params, sessionId) and once(event, sessionId). */
51+
function cdp(ws) {
52+
let nextId = 1;
53+
const pending = new Map();
54+
const waiters = [];
55+
ws.addEventListener("message", (ev) => {
56+
const msg = JSON.parse(ev.data);
57+
if (msg.id && pending.has(msg.id)) {
58+
const { resolve, reject } = pending.get(msg.id);
59+
pending.delete(msg.id);
60+
if (msg.error) reject(new Error(`${msg.error.message} (${msg.error.code})`));
61+
else resolve(msg.result);
62+
return;
63+
}
64+
for (let i = waiters.length - 1; i >= 0; i--) {
65+
const w = waiters[i];
66+
if (w.method === msg.method && w.sessionId === msg.sessionId) {
67+
waiters.splice(i, 1);
68+
w.resolve(msg.params);
69+
}
70+
}
71+
});
72+
return {
73+
send(method, params = {}, sessionId) {
74+
const id = nextId++;
75+
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
76+
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
77+
},
78+
once(method, sessionId) {
79+
return new Promise((resolve) => waiters.push({ method, sessionId, resolve }));
80+
},
81+
};
82+
}
83+
84+
async function main() {
85+
const dataPath = path.join(DIST, "data.json");
86+
if (!fs.existsSync(dataPath)) {
87+
console.error("site/dist has no data.json; run npm run build first");
88+
process.exit(1);
89+
}
90+
const data = JSON.parse(fs.readFileSync(dataPath, "utf8"));
91+
const labels = Object.fromEntries(Object.entries(data.categories || {}).map(([id, c]) => [id, c.label]));
92+
const entries = data.entries.filter((e) => fs.existsSync(path.join(DIST, "entry", e.id, "index.html")));
93+
const chrome = findChrome();
94+
if (!chrome) {
95+
console.error("No Chrome, Chromium or Edge found; set CHROME_PATH");
96+
process.exit(1);
97+
}
98+
99+
// Stage one HTML file per card inside dist so the fonts load same-origin.
100+
const stageDir = path.join(DIST, STAGE);
101+
fs.rmSync(stageDir, { recursive: true, force: true });
102+
fs.mkdirSync(stageDir);
103+
for (const e of entries) {
104+
fs.writeFileSync(path.join(stageDir, `${e.id}.html`), entryCardHtml(e, { siteTitle: data.site?.title || "Free Game Dev Assets", categoryLabel: labels[e.category] || e.category, fontRoot: "/" }));
105+
}
106+
107+
const server = createSiteServer(DIST);
108+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
109+
const { port } = server.address();
110+
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), "entry-cards-"));
111+
const child = spawn(chrome, [
112+
"--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
113+
"--disable-extensions", "--force-color-profile=srgb", "--remote-debugging-port=0",
114+
`--user-data-dir=${profileDir}`, "about:blank",
115+
], { stdio: ["ignore", "ignore", "pipe"] });
116+
child.stderr.resume();
117+
118+
let written = 0;
119+
try {
120+
const ws = new WebSocket(await devtoolsUrl(profileDir, child));
121+
await new Promise((resolve, reject) => {
122+
ws.addEventListener("open", resolve, { once: true });
123+
ws.addEventListener("error", () => reject(new Error("DevTools WebSocket failed")), { once: true });
124+
});
125+
const c = cdp(ws);
126+
const { targetId } = await c.send("Target.createTarget", { url: "about:blank" });
127+
const { sessionId } = await c.send("Target.attachToTarget", { targetId, flatten: true });
128+
await c.send("Page.enable", {}, sessionId);
129+
await c.send("Emulation.setDeviceMetricsOverride", { width: OG_CARD_WIDTH, height: OG_CARD_HEIGHT, deviceScaleFactor: 1, mobile: false }, sessionId);
130+
for (const e of entries) {
131+
const loaded = c.once("Page.loadEventFired", sessionId);
132+
await c.send("Page.navigate", { url: `http://127.0.0.1:${port}/${STAGE}/${encodeURIComponent(e.id)}.html` }, sessionId);
133+
await loaded;
134+
await c.send("Runtime.evaluate", { expression: "document.fonts.ready.then(() => true)", awaitPromise: true }, sessionId);
135+
const { data: b64 } = await c.send("Page.captureScreenshot", { format: "png", clip: { x: 0, y: 0, width: OG_CARD_WIDTH, height: OG_CARD_HEIGHT, scale: 1 } }, sessionId);
136+
const png = Buffer.from(b64, "base64");
137+
const size = pngSize(png);
138+
if (!size || size.width !== OG_CARD_WIDTH || size.height !== OG_CARD_HEIGHT) throw new Error(`${e.id}: expected a ${OG_CARD_WIDTH}x${OG_CARD_HEIGHT} PNG`);
139+
fs.writeFileSync(path.join(DIST, "entry", e.id, ENTRY_CARD_NAME), png);
140+
written++;
141+
}
142+
await c.send("Browser.close").catch(() => {});
143+
ws.close();
144+
} finally {
145+
child.kill();
146+
server.close();
147+
fs.rmSync(stageDir, { recursive: true, force: true });
148+
fs.rmSync(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
149+
}
150+
console.log(`Rendered ${written} entry cards (${OG_CARD_WIDTH}x${OG_CARD_HEIGHT}) into site/dist/entry/<id>/${ENTRY_CARD_NAME}`);
151+
}
152+
153+
main().catch((err) => {
154+
console.error(err.message || err);
155+
process.exit(1);
156+
});

‎site/lib/entry-page.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { previewCredit } from "./thumbs.mjs";
2121
import { creditLineHtml, fillInNote } from "./owes.mjs";
2222
import { ENGINES, nativeEngines } from "./search.mjs";
2323
import { badgeSnippets } from "./badge.mjs";
24+
import { entryCardRef } from "./og-card.mjs";
2425

2526
export function jsonLd(entry, site, { categoryLabel } = {}) {
2627
const work = { "@type": "CreativeWork", name: entry.name, url: entry.url };
@@ -153,7 +154,7 @@ export function entryPageHtml({ entry, leadHtml, restHtml, deprecatedReasonHtml,
153154
<title>${esc(seoTitle(entry.name, entry.license))}</title>
154155
<meta name="description" content="${esc(seoDescription(entry, undefined, { scope }))}" />
155156
${deprecated ? '<meta name="robots" content="noindex" />' : ""}
156-
${baseHeadHtml({ site, title, description: desc, url, type: "article", hasCard, root: "../../", modules: PAGE_MODULES.entry })}
157+
${baseHeadHtml({ site, title, description: desc, url, type: "article", hasCard, root: "../../", modules: PAGE_MODULES.entry, ownCard: entryCardRef(entry) })}
157158
<script type="application/ld+json">${scriptJson(jsonLd(entry, site, { categoryLabel }))}</script>
158159
</head>
159160
<body>

‎site/lib/lib.test.mjs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -606,17 +606,19 @@ await section("block at line 599", async () => {
606606
'<link rel="alternate" type="application/atom+xml" title="Free Game Dev Assets: recently verified" href="https://x.test/s/reverified.xml" />',
607607
'<meta name="theme-color" content="#1a4d3e" media="(prefers-color-scheme: light)" />',
608608
'<meta name="theme-color" content="#0f1216" media="(prefers-color-scheme: dark)" />',
609-
'<meta property="og:image" content="https://x.test/s/og-card.png" />',
610609
'<meta property="og:image:width" content="1200" />',
611610
'<meta property="og:image:height" content="630" />',
612-
'<meta property="og:image:alt" content="Free Game Dev Assets: T" />',
613611
'<meta name="twitter:card" content="summary_large_image" />',
614612
'<meta property="og:site_name" content="Free Game Dev Assets" />',
615613
];
614+
// The site card on every page but entry pages, which have their own (#117).
615+
const siteCard = ['<meta property="og:image" content="https://x.test/s/og-card.png" />', '<meta property="og:image:alt" content="Free Game Dev Assets: T" />'];
616616
for (const [name, html] of [["home head", homeHead], ["entry page", p], ["stack page", spage], ["freshness page", fp]]) {
617617
for (const tag of baseline) has(`${name} has ${tag.slice(0, 40)}`, html, tag);
618+
if (name !== "entry page") for (const tag of siteCard) has(`${name} has ${tag.slice(0, 40)}`, html, tag);
618619
eq(`${name} has one canonical`, (html.match(/<link rel="canonical"/g) || []).length, 1);
619620
}
621+
has("entry page has its own card", p, '/card.png" />');
620622
has("entry page og:type is article", p, '<meta property="og:type" content="article" />');
621623
has("freshness og:type is website", fp, '<meta property="og:type" content="website" />');
622624
has("no card falls back to a summary card", baseHeadHtml({ site, title: "t", description: "d", url: "https://x.test/s/", hasCard: false }), '<meta name="twitter:card" content="summary" />');
@@ -2620,6 +2622,19 @@ await section("needs-review open question (#211)", async () => {
26202622
eq("singleton report: counts unique tags", report.unique, 3);
26212623
eq("singleton report: lists one-off tags", report.singles.join(), "b,c");
26222624
eq("singleton report: flags a share over a fifth", report.over, true);
2625+
// #117: every entry page has its own social card.
2626+
const { entryCardRef, entryCardHtml } = await import("./og-card.mjs");
2627+
const { baseHeadHtml } = await import("./shared.mjs");
2628+
const cardEntry = { id: "kit", name: "Kit <b>&", license: "CC0", commercial: true, verified: "2026-11-01", status: "active", category: "2d" };
2629+
eq("entry card: served next to the page", entryCardRef(cardEntry).path, "entry/kit/card.png");
2630+
has("entry card: alt names the licence and date", entryCardRef(cardEntry).alt, "CC0 licence, read at the source 2026-11-01");
2631+
const cardHtml = entryCardHtml(cardEntry, { siteTitle: "FGDA", categoryLabel: "2D" });
2632+
has("entry card: escapes the name", cardHtml, "Kit &lt;b&gt;&amp;");
2633+
has("entry card: shows the read date", cardHtml, "Licence read at the source 2026-11-01");
2634+
has("entry card: shows the commercial verdict", cardHtml, "Commercial use OK");
2635+
const ownHead = baseHeadHtml({ site: { siteUrl: "https://x.test/s/", title: "T", tagline: "g" }, title: "t", description: "d", url: "u", hasCard: true, ownCard: entryCardRef(cardEntry) });
2636+
has("entry card: og:image points at the entry's card", ownHead, 'property="og:image" content="https://x.test/s/entry/kit/card.png"');
2637+
has("entry card: twitter:image too", ownHead, 'name="twitter:image" content="https://x.test/s/entry/kit/card.png"');
26232638
// #97: delivery is a closed list beside formats, with its own filter.
26242639
const fv = JSON.parse(fsTest.readFileSync(new URL("../format-vocabulary.json", import.meta.url), "utf8"));
26252640
const { DELIVERY_GROUPS, passesFilters: pf, FILTER_DEFAULTS: FD } = await import("./search.mjs");

‎site/lib/og-card.mjs‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/**
22
* 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).
3+
* docs/images/readme/og-card.png (the README screenshot and the social card),
4+
* and for site/entry-cards.mjs, which renders each entry page's own card (#117).
45
*/
56
import path from "node:path";
67

@@ -62,3 +63,56 @@ export function chromeArgs({ url, out, profileDir }) {
6263
url,
6364
];
6465
}
66+
67+
/* --------------------------------------------------------- entry cards */
68+
69+
/** File name of an entry's own social card, next to its page (#117). */
70+
export const ENTRY_CARD_NAME = "card.png";
71+
72+
const escCard = (s) =>
73+
String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
74+
75+
/** Where an entry's card is served, and its alt text, for baseHeadHtml's `ownCard`. */
76+
export function entryCardRef(entry) {
77+
return {
78+
path: `entry/${entry.id}/${ENTRY_CARD_NAME}`,
79+
alt: `${entry.name}: ${entry.license} licence, read at the source ${entry.verified || "(date not recorded)"}`,
80+
};
81+
}
82+
83+
const COMMERCIAL_WORDS = { true: "Commercial use OK", false: "Not for commercial use", varies: "Commercial use varies per file", unknown: "Commercial use unclear" };
84+
85+
/**
86+
* The 1200x630 page site/entry-cards.mjs screenshots for one entry: its
87+
* name, category, licence, commercial verdict and the date the licence was
88+
* read. `fontRoot` is where the self-hosted fonts are served.
89+
*/
90+
export function entryCardHtml(entry, { siteTitle, categoryLabel = entry.category, fontRoot = "/" }) {
91+
const commercial = COMMERCIAL_WORDS[String(entry.commercial)] || COMMERCIAL_WORDS.unknown;
92+
const ok = entry.commercial === true;
93+
const long = String(entry.name).length > 38;
94+
return `<!DOCTYPE html>
95+
<html lang="en"><head><meta charset="utf-8" /><title>${escCard(entry.name)}</title>
96+
<style>
97+
@font-face { font-family: "Public Sans"; src: url("${fontRoot}fonts/public-sans.woff2") format("woff2"); font-weight: 100 900; }
98+
@font-face { font-family: "IBM Plex Mono"; src: url("${fontRoot}fonts/ibm-plex-mono-400.woff2") format("woff2"); }
99+
html, body { margin: 0; width: ${OG_CARD_WIDTH}px; height: ${OG_CARD_HEIGHT}px; overflow: hidden; }
100+
body { box-sizing: border-box; padding: 64px 72px; background: #eef1f4; color: #12151a; font-family: "Public Sans", sans-serif; display: flex; flex-direction: column; border-top: 14px solid #1a4d3e; }
101+
.site { font: 500 26px "IBM Plex Mono", monospace; color: #5a6472; letter-spacing: 0.02em; }
102+
.cat { margin-top: 44px; font: 600 28px "Public Sans", sans-serif; color: #1a4d3e; text-transform: uppercase; letter-spacing: 0.08em; }
103+
h1 { margin: 12px 0 0; font-weight: 800; font-size: ${long ? 60 : 76}px; line-height: 1.05; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
104+
.facts { margin-top: auto; display: flex; gap: 18px; flex-wrap: wrap; }
105+
.pill { font: 600 30px "Public Sans", sans-serif; padding: 12px 24px; border-radius: 999px; border: 3px solid #c5ccd6; background: #f7f8fa; }
106+
.pill.ok { border-color: #1a4d3e; color: #1a4d3e; }
107+
.pill.warn { border-color: #8a5a12; color: #8a5a12; }
108+
.read { margin-top: 26px; font: 400 28px "IBM Plex Mono", monospace; color: #5a6472; }
109+
</style></head>
110+
<body>
111+
<div class="site">${escCard(siteTitle)}</div>
112+
<div class="cat">${escCard(categoryLabel)}</div>
113+
<h1>${escCard(entry.name)}</h1>
114+
<div class="facts"><span class="pill">Licence: ${escCard(entry.license)}</span><span class="pill ${ok ? "ok" : "warn"}">${escCard(commercial)}</span>${entry.status === "active" ? "" : `<span class="pill warn">${escCard(entry.status)}</span>`}</div>
115+
<div class="read">Licence read at the source ${escCard(entry.verified || "(date not recorded)")}</div>
116+
</body></html>
117+
`;
118+
}

‎site/lib/shared.mjs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -398,15 +398,17 @@ export const OG_CARD_NAME = "og-card.png";
398398
* page's path back to the site root ("./", "../", "../../"): the icon, the
399399
* self-hosted font preloads and the stylesheet are resolved against it.
400400
*/
401-
export function baseHeadHtml({ site, title, description, url, type = "website", hasCard, indent = " ", root = "./", modules = [] }) {
401+
export function baseHeadHtml({ site, title, description, url, type = "website", hasCard, indent = " ", root = "./", modules = [], ownCard = null }) {
402402
const base = String(site.siteUrl).replace(/\/+$/, "");
403-
const card = `${base}/${OG_CARD_NAME}`;
403+
// An entry page has its own card (#117: entry/<id>/card.png, rendered at
404+
// deploy by site/entry-cards.mjs); every other page shares the site card.
405+
const card = ownCard ? `${base}/${ownCard.path}` : `${base}/${OG_CARD_NAME}`;
404406
const cardMeta = hasCard
405407
? [
406408
`<meta property="og:image" content="${esc(card)}" />`,
407409
`<meta property="og:image:width" content="1200" />`,
408410
`<meta property="og:image:height" content="630" />`,
409-
`<meta property="og:image:alt" content="${esc(`${site.title}: ${site.tagline}`)}" />`,
411+
`<meta property="og:image:alt" content="${esc(ownCard ? ownCard.alt : `${site.title}: ${site.tagline}`)}" />`,
410412
`<meta name="twitter:card" content="summary_large_image" />`,
411413
`<meta name="twitter:image" content="${esc(card)}" />`,
412414
]

0 commit comments

Comments
 (0)