Skip to content

Commit 10151a9

Browse files
TMHSDigitalclaude
andcommitted
site: parser for starter stack files
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Wc67NX9MM964uaVGn4bpZJ
1 parent 710d9a4 commit 10151a9

2 files changed

Lines changed: 187 additions & 0 deletions

File tree

‎site/lib/lib.test.mjs‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,66 @@ lacks("full has no relative links", lfLinks, "](../");
190190
has("full rewrites a link whose label is code", lfLinks, "[`docs/p.md`](https://github.com/o/r/blob/main/docs/p.md)");
191191
has("full leaves links inside code alone", lfLinks, "`[x](y)` stays literal");
192192

193+
/* stacks: parse ------------------------------------------------------------ */
194+
import { licenceTerms, namedLicence, parseStack, pickPath, STACK_SECTIONS } from "./stacks.mjs";
195+
const stackMd = [
196+
"---",
197+
"id: s1",
198+
"title: Make a thing",
199+
'task: "A game: to sell."',
200+
"walked: 2026-09-20",
201+
"---",
202+
"",
203+
"# Make a thing",
204+
"",
205+
"Lead line one.",
206+
"Lead line two.",
207+
"",
208+
"## Art",
209+
"",
210+
"- **Tiles:** [Kenney Pixel Platformer](../catalog/2d/kenney-pixel-platformer.md). 200 tiles on an 18x18 grid, see [UI](../catalog/2d/kenney-ui-pack.md).",
211+
"- **Player:** [Hero](../catalog/2d/luizmelo-martial-hero.md). Idle, run and jump.",
212+
"",
213+
"## Audio",
214+
"",
215+
"- **Music, no credit:** [Chips](../catalog/audio/subspaceaudio-5-chiptunes.md). Five loops.",
216+
"",
217+
"## Gaps",
218+
"",
219+
"- No parallax layers yet.",
220+
].join("\n");
221+
const st = parseStack(stackMd, { file: "stacks/s1.md", terms: ["MIT", "CC0"] });
222+
eq("stack id", st.meta.id, "s1");
223+
eq("stack task unquoted", st.meta.task, "A game: to sell.");
224+
eq("stack lead skips the h1", st.lead, "Lead line one.\nLead line two.");
225+
eq("stack lead line", st.leadLine, 10);
226+
eq("stack sections exclude Gaps", st.sections.map((s) => s.name).join(","), "Art,Audio");
227+
eq("stack pick need", st.sections[0].picks[0].need, "Tiles");
228+
eq("stack pick href", st.sections[0].picks[0].href, "../catalog/2d/kenney-pixel-platformer.md");
229+
eq("stack pick why keeps later links", st.sections[0].picks[0].why, "200 tiles on an 18x18 grid, see [UI](../catalog/2d/kenney-ui-pack.md).");
230+
eq("stack pick line", st.sections[0].picks[1].line, 16);
231+
eq("stack gaps", st.gaps[0].text, "No parallax layers yet.");
232+
eq("stack gap line", st.gaps[0].line, 24);
233+
eq("CRLF parses the same", JSON.stringify(parseStack(stackMd.replace(/\n/g, "\r\n"), { file: "stacks/s1.md", terms: ["MIT", "CC0"] })), JSON.stringify(st));
234+
const badStack = (edit) => () => parseStack(edit(stackMd), { file: "stacks/s1.md", terms: ["MIT", "CC0"] });
235+
throws("unknown section", badStack((m) => m.replace("## Audio", "## Levels")), 'stacks/s1.md:18: section "Levels" is not one of');
236+
throws("sections out of order", badStack((m) => m.replace("## Art", "## Tools")), 'stacks/s1.md:18: section "Audio" is out of order');
237+
throws("pick without a link", badStack((m) => m.replace("[Hero](../catalog/2d/luizmelo-martial-hero.md)", "Hero")), "stacks/s1.md:16: a pick line is");
238+
throws("pick without the bold need", badStack((m) => m.replace("- **Player:** ", "- Player: ")), "stacks/s1.md:16: a pick line is");
239+
throws("pick without a why", badStack((m) => m.replace("). Idle, run and jump.", ").")), "stacks/s1.md:16: a pick line is");
240+
throws("licence in a why sentence", badStack((m) => m.replace("Five loops.", "Five CC0 loops.")), 'stacks/s1.md:20: the why sentence names a licence ("CC0")');
241+
throws("licence phrase in a why sentence", badStack((m) => m.replace("Five loops.", "Five public domain loops.")), '("public domain")');
242+
throws("missing walked", badStack((m) => m.replace("walked: 2026-09-20\n", "")), "frontmatter is missing walked");
243+
throws("bad walked date", badStack((m) => m.replace("2026-09-20", "20 Sept")), "walked is not YYYY-MM-DD");
244+
throws("empty pick section", badStack((m) => m.replace("- **Music, no credit:** [Chips](../catalog/audio/subspaceaudio-5-chiptunes.md). Five loops.", "")), 'section "Audio" has no picks');
245+
throws("gaps line not a bullet", badStack((m) => m.replace("- No parallax layers yet.", "No parallax layers yet.")), "stacks/s1.md:24: a Gaps line is a bullet");
246+
eq("licence terms skip plain words", licenceTerms({ licenses: { custom: {}, MIT: { spdx: "MIT" }, CC0: { spdx: "CC0-1.0" } } }, ["OFL-1.1"]).sort().join(","), "CC0,CC0-1.0,MIT,OFL-1.1");
247+
eq("whole words only", namedLicence("A MITRE-style layout.", ["MIT"]), null);
248+
eq("finds a hyphenated id", namedLicence("Ships under OFL-1.1 terms.", ["OFL-1.1"]), "OFL-1.1");
249+
eq("licence in the label is not checked", parseStack(stackMd.replace("[Chips]", "[CC0 Chips]"), { file: "stacks/s1.md", terms: ["CC0"] }).sections[1].picks[0].label, "CC0 Chips");
250+
eq("pickPath resolves from stacks/", pickPath("stacks/s1.md", "../catalog/2d/x.md"), "catalog/2d/x.md");
251+
eq("section order constant", STACK_SECTIONS.join(","), "Art,Audio,Fonts,Tools,Gaps");
252+
193253
/* report (keep last) ------------------------------------------------------ */
194254
if (failures.length) {
195255
console.error(`lib.test failed (${failures.length}):`);

‎site/lib/stacks.mjs‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/**
2+
* Starter stacks: one markdown file per kind of game, one pick per need.
3+
* A stack names its picks; every licence fact on its page comes from the
4+
* picked entries at build time, so a stack cannot disagree with an entry.
5+
*/
6+
import path from "node:path";
7+
import { unquoteScalar } from "./shared.mjs";
8+
9+
export class StackError extends Error {}
10+
11+
/** The `##` sections a stack may have, in the order they must appear. */
12+
export const STACK_SECTIONS = ["Art", "Audio", "Fonts", "Tools", "Gaps"];
13+
14+
const REQUIRED = ["id", "title", "task", "walked"];
15+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
16+
// - **Need:** [Entry name](path/to/entry.md). Why this pick.
17+
const PICK_RE = /^- \*\*([^*]+?):\*\* \[([^\]]+)\]\(([^)\s]+)\)\.\s+(\S.*)$/;
18+
const LICENCE_PHRASES = ["Creative Commons", "public domain", "royalty-free"];
19+
// Vocabulary keys that are ordinary words, not licence names.
20+
const PLAIN_WORD_IDS = new Set(["custom", "unknown", "varies"]);
21+
22+
/** Licence ids and SPDX ids a why sentence must not name. */
23+
export function licenceTerms(vocab, spdxAllowed) {
24+
const ids = new Set();
25+
for (const [key, spec] of Object.entries(vocab.licenses || {})) {
26+
if (!PLAIN_WORD_IDS.has(key)) ids.add(key);
27+
for (const s of [].concat(spec?.spdx || [])) if (typeof s === "string") ids.add(s);
28+
}
29+
for (const id of spdxAllowed) ids.add(id);
30+
return [...ids];
31+
}
32+
33+
const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34+
35+
/** The first licence term or phrase the text names, or null. Ids match whole words. */
36+
export function namedLicence(text, terms) {
37+
for (const t of terms) {
38+
if (new RegExp(`(^|[^\\w-])${escRe(t)}(?!\\w)`).test(text)) return t;
39+
}
40+
const lower = text.toLowerCase();
41+
for (const p of LICENCE_PHRASES) if (lower.includes(p.toLowerCase())) return p;
42+
return null;
43+
}
44+
45+
/** Repo-relative path of a pick link written in `stackFile`. */
46+
export function pickPath(stackFile, href) {
47+
const target = href.split("#")[0];
48+
let decoded = target;
49+
try {
50+
decoded = decodeURI(target);
51+
} catch {
52+
// A malformed escape stays as written; the lookup then fails as a missing pick.
53+
}
54+
return path.posix.normalize(path.posix.join(path.posix.dirname(stackFile), decoded));
55+
}
56+
57+
export function parseStack(text, { file, terms = [] }) {
58+
const lines = String(text).replace(/\r\n?/g, "\n").split("\n");
59+
const fail = (i, msg) => {
60+
throw new StackError(`${file}:${i + 1}: ${msg}`);
61+
};
62+
if (lines[0] !== "---") fail(0, "a stack starts with frontmatter (---)");
63+
const end = lines.indexOf("---", 1);
64+
if (end === -1) fail(0, "frontmatter is not closed with ---");
65+
const meta = {};
66+
for (let i = 1; i < end; i++) {
67+
const line = lines[i];
68+
if (!line.trim()) continue;
69+
const at = line.indexOf(":");
70+
if (at === -1) fail(i, `frontmatter line "${line.trim()}" is not key: value`);
71+
meta[line.slice(0, at).trim()] = unquoteScalar(line.slice(at + 1).trim());
72+
}
73+
for (const key of REQUIRED) if (!meta[key]) fail(0, `frontmatter is missing ${key}`);
74+
if (!DATE_RE.test(meta.walked)) fail(0, "walked is not YYYY-MM-DD");
75+
76+
const lead = [];
77+
let leadLine = null;
78+
const sections = [];
79+
const gaps = [];
80+
let current = null;
81+
let order = -1;
82+
let gapsLine = null;
83+
for (let i = end + 1; i < lines.length; i++) {
84+
const line = lines[i];
85+
const h = line.match(/^##\s+(.+?)\s*$/);
86+
if (h) {
87+
const name = h[1];
88+
const at = STACK_SECTIONS.indexOf(name);
89+
if (at === -1) fail(i, `section "${name}" is not one of ${STACK_SECTIONS.join(", ")}`);
90+
if (at <= order) fail(i, `section "${name}" is out of order or repeated; the order is ${STACK_SECTIONS.join(", ")}`);
91+
order = at;
92+
current = { name, line: i + 1, picks: [] };
93+
if (name === "Gaps") gapsLine = i;
94+
else sections.push(current);
95+
continue;
96+
}
97+
if (!current) {
98+
if (/^#\s/.test(line)) continue; // the page shows the title as its h1
99+
if (line.trim() && leadLine === null) leadLine = i + 1;
100+
if (leadLine !== null) lead.push(line);
101+
continue;
102+
}
103+
if (!line.trim()) continue;
104+
if (current.name === "Gaps") {
105+
const g = line.match(/^- (\S.*)$/);
106+
if (!g) fail(i, "a Gaps line is a bullet (- text)");
107+
gaps.push({ text: g[1], line: i + 1 });
108+
continue;
109+
}
110+
const m = line.match(PICK_RE);
111+
if (!m) fail(i, "a pick line is: - **Need:** then a link to the entry, a full stop, and why this pick");
112+
const [, need, label, href, why] = m;
113+
const named = namedLicence(why, terms);
114+
if (named) fail(i, `the why sentence names a licence ("${named}"); licence facts come from the entry`);
115+
current.picks.push({ need: need.trim(), label, href, why, line: i + 1 });
116+
}
117+
for (const s of sections) if (!s.picks.length) fail(s.line - 1, `section "${s.name}" has no picks`);
118+
if (gapsLine !== null && !gaps.length) fail(gapsLine, `section "Gaps" has no bullets`);
119+
if (!sections.length) fail(end, "a stack needs at least one of Art, Audio, Fonts, Tools");
120+
return {
121+
meta: { id: meta.id, title: meta.title, task: meta.task, walked: meta.walked },
122+
lead: lead.join("\n").trim(),
123+
leadLine: leadLine || end + 2,
124+
sections,
125+
gaps,
126+
};
127+
}

0 commit comments

Comments
 (0)