@jonandev/longbeard 0.11.2 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AGENTS.md +4 -5
  2. package/CHANGELOG.md +72 -0
  3. package/README.md +64 -43
  4. package/beard.json +124 -28
  5. package/bin/long-beard.js +171 -36
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +51 -126
  8. package/skills/design-brief/SKILL.md +146 -0
  9. package/skills/design-brief/references/graphic.md +59 -0
  10. package/skills/design-check/SKILL.md +27 -11
  11. package/skills/design-check/references/design-rules.md +21 -7
  12. package/skills/design-check/scripts/capture.mjs +121 -37
  13. package/skills/design-check/scripts/contrast.mjs +23 -9
  14. package/skills/design-check/scripts/rules.mjs +613 -0
  15. package/skills/design-check/scripts/screen-contrast.mjs +428 -0
  16. package/skills/design-check/scripts/tokens.mjs +346 -0
  17. package/skills/design-content/SKILL.md +118 -0
  18. package/skills/design-content/scripts/contact-sheet.mjs +259 -0
  19. package/skills/design-content/scripts/pictures.mjs +197 -0
  20. package/skills/design-direction/SKILL.md +115 -200
  21. package/skills/design-direction/references/controls.md +58 -0
  22. package/skills/{design → design-direction}/references/design-rules.md +21 -7
  23. package/skills/design-direction/references/five-second.md +47 -0
  24. package/skills/design-direction/references/full-build.md +19 -0
  25. package/skills/design-direction/references/graphic.md +35 -0
  26. package/skills/design-direction/references/grid.md +114 -0
  27. package/skills/design-direction/references/library.md +75 -0
  28. package/skills/design-direction/references/screen-template.html +233 -0
  29. package/skills/design-direction/references/subject.md +33 -0
  30. package/skills/design-direction/scripts/capture.mjs +121 -37
  31. package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
  32. package/skills/design-direction/scripts/fonts.mjs +276 -0
  33. package/skills/design-direction/scripts/layout-diff.mjs +118 -0
  34. package/skills/design-direction/scripts/measure.mjs +1728 -0
  35. package/skills/design-direction/scripts/moodboard.mjs +123 -32
  36. package/skills/design-direction/scripts/picture-cast.mjs +270 -0
  37. package/skills/design-direction/scripts/pictures.mjs +197 -0
  38. package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
  39. package/skills/design-direction/scripts/sheet.mjs +67 -0
  40. package/skills/design-direction/scripts/subject-colours.mjs +410 -0
  41. package/skills/design-families/SKILL.md +138 -0
  42. package/skills/design-families/scripts/contact-sheet.mjs +259 -0
  43. package/skills/design-families/scripts/families.mjs +606 -0
  44. package/skills/design-families/scripts/measure.mjs +1728 -0
  45. package/skills/design-families/scripts/moodboard.mjs +467 -0
  46. package/skills/design-families/scripts/tag.mjs +289 -0
  47. package/skills/design-figma/SKILL.md +69 -0
  48. package/skills/design-figma/references/graphic.md +26 -0
  49. package/skills/design-identity/SKILL.md +134 -0
  50. package/skills/design-identity/references/graphic.md +8 -0
  51. package/skills/design-identity/references/identity-board.html +140 -0
  52. package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
  53. package/skills/design-identity/scripts/colours.mjs +213 -0
  54. package/skills/design-identity/scripts/contrast.mjs +41 -0
  55. package/skills/design-identity/scripts/fonts.mjs +276 -0
  56. package/skills/design-identity/scripts/measure.mjs +1728 -0
  57. package/skills/design-identity/scripts/sheet.mjs +67 -0
  58. package/skills/design-identity/scripts/subject-colours.mjs +410 -0
  59. package/skills/design-moodboard/SKILL.md +184 -0
  60. package/skills/design-moodboard/references/graphic.md +25 -0
  61. package/skills/{design-direction → design-moodboard}/references/sources.md +21 -11
  62. package/skills/design-moodboard/scripts/capture.mjs +893 -0
  63. package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
  64. package/skills/design-moodboard/scripts/crops.mjs +256 -0
  65. package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
  66. package/skills/design-moodboard/scripts/families.mjs +606 -0
  67. package/skills/design-moodboard/scripts/group.mjs +221 -0
  68. package/skills/design-moodboard/scripts/measure.mjs +1728 -0
  69. package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
  70. package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
  71. package/skills/design-moodboard/scripts/pictures.mjs +197 -0
  72. package/skills/design-moodboard/scripts/tag.mjs +289 -0
  73. package/skills/design-prototype/SKILL.md +149 -0
  74. package/skills/design-prototype/references/design-md-template.md +82 -0
  75. package/skills/design-prototype/references/design-rules.md +203 -0
  76. package/skills/design-prototype/references/five-second.md +47 -0
  77. package/skills/design-prototype/references/graphic.md +27 -0
  78. package/skills/design-prototype/scripts/capture.mjs +893 -0
  79. package/skills/design-prototype/scripts/contrast.mjs +41 -0
  80. package/skills/design-prototype/scripts/links.mjs +308 -0
  81. package/skills/design-prototype/scripts/pictures.mjs +197 -0
  82. package/skills/design-prototype/scripts/rules.mjs +613 -0
  83. package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
  84. package/skills/design-prototype/scripts/sheet.mjs +67 -0
  85. package/skills/design-prototype/scripts/tokens.mjs +346 -0
  86. package/skills/design-wordmark/SKILL.md +65 -0
  87. package/skills/design-wordmark/scripts/capture.mjs +893 -0
  88. package/skills/design-wordmark/scripts/sheet.mjs +67 -0
  89. package/skills/framework-skills/SKILL.md +71 -0
  90. package/skills/idea/SKILL.md +13 -7
  91. package/skills/idea/references/graphic.md +64 -0
  92. package/skills/design/references/design-md-template.md +0 -58
  93. package/skills/design/scripts/contrast.mjs +0 -27
  94. package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ // WCAG 2.x contrast for colour pairs.
3
+ // node contrast.mjs "#2c2824 on #f6f1e7" "#b0563a on #f6f1e7:mark"
4
+ // Suffix :large or :mark checks against 3:1 instead of 4.5:1. --level AAA (the design brief's
5
+ // accessibility line) asks 7:1 for text and 4.5:1 for large text; a mark stays 3:1. Short hex (#abc) is read as #aabbcc.
6
+ // An argument it cannot read is an error: it exits 1 rather than pass unchecked.
7
+ // The ratio is cut, not rounded, to two places: 4.496 prints as 4.49 and fails, never as 4.50 FAIL.
8
+ const hex6 = (h) => (h.length === 4 ? `#${[...h.slice(1)].map((c) => c + c).join("")}` : h).toLowerCase();
9
+ const lum = (hex) => {
10
+ const [r, g, b] = [1, 3, 5]
11
+ .map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
12
+ .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
13
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
14
+ };
15
+ const args = process.argv.slice(2);
16
+ const at = args.indexOf("--level");
17
+ const level = at === -1 ? "AA" : String(args.splice(at, 2)[1] || "").toUpperCase();
18
+ if (level !== "AA" && level !== "AAA") {
19
+ console.error("contrast: --level is AA or AAA");
20
+ process.exit(2);
21
+ }
22
+ let failed = false;
23
+ for (const arg of args) {
24
+ const m = arg.trim().match(/^(#[0-9a-f]{3}(?:[0-9a-f]{3})?)\s+on\s+(#[0-9a-f]{3}(?:[0-9a-f]{3})?)(?::(large|mark))?$/i);
25
+ if (!m) {
26
+ console.error(`cannot read: ${arg} (write "#rrggbb on #rrggbb", optionally :large or :mark)`);
27
+ failed = true;
28
+ continue;
29
+ }
30
+ m[1] = hex6(m[1]);
31
+ m[2] = hex6(m[2]);
32
+ const [a, b] = [lum(m[1]), lum(m[2])];
33
+ const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
34
+ const kind = (m[3] || "").toLowerCase();
35
+ const need = kind === "mark" ? 3 : kind === "large" ? (level === "AAA" ? 4.5 : 3) : level === "AAA" ? 7 : 4.5;
36
+ const best = kind === "mark" ? "" : ratio >= (kind ? 4.5 : 7) ? "AAA" : "";
37
+ const verdict = ratio < need ? "FAIL" : best || "AA";
38
+ if (verdict === "FAIL") failed = true;
39
+ console.log(`${m[1]} on ${m[2]} ${(Math.floor(ratio * 100) / 100).toFixed(2)}:1 ${verdict}${kind || level === "AAA" ? ` (${[kind, `needs ${need}:1`].filter(Boolean).join(", ")})` : ""}`);
40
+ }
41
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,308 @@
1
+ #!/usr/bin/env node
2
+ // Scan a clickable prototype: every page in its folder, from its first page on, for
3
+ // links that break and pages with no way on, and for what it still stands in for.
4
+ // Whether a person can reach each screen is the flow walks' job, not this one's.
5
+ // Node 22+, an installed Chrome, no dependencies.
6
+ //
7
+ // node links.mjs "file://$PWD/.longbeard/design/prototype/home.html"
8
+ //
9
+ // Pages are rendered (links a script builds count). Links are followed from the first page, then
10
+ // every other page in the prototype's folder is opened too, so a page behind a state (an empty
11
+ // basket) is still scanned. A link elsewhere (a real site, mailto:) is listed, never followed. A form that submits to another page is a way on, and so is
12
+ // a button whose script navigates: each is clicked, and the page it lands on is followed. A query (?state=empty) or a hash is the same page, but the
13
+ // page is opened with the query it was first reached by, so state a prototype keeps in
14
+ // the address (a basket, a chosen slot) carries on as it does for a person.
15
+ //
16
+ // Says, one line each:
17
+ // broken a link to a page that is not there
18
+ // nowhere a link or button that goes nowhere: href "#", "", "javascript:…", or a
19
+ // button outside a form with no onclick and no link around it
20
+ // dead end a page with no way on to another page of the prototype (a link, a form, a button)
21
+ // then the pages scanned.
22
+ // Exit 1 when anything is broken, nowhere, a dead end or unmarked; 0 when the scan is clean.
23
+ //
24
+ // It also lists what the page does not really have yet: every element marked data-standin="picture"
25
+ // or data-standin="fact" (a stand-in picture; a price, an hour, a number or a name the brief does not
26
+ // give), with data-standin-note for what is assumed. One line each, "stand-in", then a count, or "none
27
+ // marked". The list never fails the walk. A picture whose file sits in a credits.tsv beside it (a
28
+ // stand-in from pictures.mjs) with no mark is "unmarked", and does.
29
+ // --width 1440, --wait 300 (ms per page), --json
30
+ import { spawn } from "node:child_process";
31
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
32
+ import { tmpdir } from "node:os";
33
+ import { basename, dirname, extname, join } from "node:path";
34
+ import { fileURLToPath, pathToFileURL } from "node:url";
35
+ if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
36
+
37
+ const args = process.argv.slice(2);
38
+ const flag = (name, def = "") => {
39
+ const i = args.indexOf(`--${name}`);
40
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
41
+ };
42
+ const has = (name) => {
43
+ const i = args.indexOf(`--${name}`);
44
+ return i === -1 ? false : (args.splice(i, 1), true);
45
+ };
46
+ const width = Number(flag("width", "1440"));
47
+ const wait = Number(flag("wait", "300"));
48
+ const json = has("json");
49
+ const [start] = args;
50
+ const usage = 'usage: node links.mjs "file:///…/prototype/home.html" [--width 1440] [--wait 300] [--json]';
51
+ if (!start || args.length !== 1 || !/^file:/.test(start) || !(width >= 200 && width <= 3840) || !(wait >= 0 && wait <= 10000)) {
52
+ console.error(usage);
53
+ process.exit(2);
54
+ }
55
+ const startPath = fileURLToPath(start.split(/[?#]/)[0]);
56
+ if (!existsSync(startPath)) {
57
+ console.error(`links: no page at ${startPath}`);
58
+ process.exit(1);
59
+ }
60
+ const root = dirname(startPath);
61
+ const pageName = (path) => basename(path, extname(path));
62
+ const inside = (path) => path === root || path.startsWith(root + "/") || path.startsWith(root + "\\");
63
+
64
+ function findChrome() {
65
+ const env = process.env.CHROME_PATH;
66
+ // CHROME_PATH=none: run as if no browser were installed (a quick test run).
67
+ if (env === "none") return null;
68
+ if (env && existsSync(env)) return env;
69
+ const home = process.env.HOME || process.env.USERPROFILE || "";
70
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
71
+ return [
72
+ join(pf, "Google/Chrome/Application/chrome.exe"),
73
+ join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
74
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
75
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
76
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
77
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
78
+ "/usr/bin/google-chrome",
79
+ "/usr/bin/google-chrome-stable",
80
+ "/usr/bin/chromium",
81
+ "/usr/bin/chromium-browser",
82
+ ].find((path) => path && existsSync(path));
83
+ }
84
+ const exe = findChrome();
85
+ if (!exe) {
86
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
87
+ process.exit(1);
88
+ }
89
+ const dir = mkdtempSync(join(tmpdir(), "links-"));
90
+ const proc = spawn(exe, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--allow-file-access-from-files", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
91
+ process.once("exit", () => {
92
+ try {
93
+ proc.kill("SIGKILL");
94
+ } catch {}
95
+ try {
96
+ rmSync(dir, { recursive: true, force: true });
97
+ } catch {}
98
+ });
99
+ const fail = (text) => {
100
+ console.error(`links: ${text}`);
101
+ process.exit(1);
102
+ };
103
+ let buf = "";
104
+ const wsUrl = await new Promise((done, no) => {
105
+ const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
106
+ proc.stderr.on("data", (d) => {
107
+ const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
108
+ if (m) done(m[1], clearTimeout(t));
109
+ });
110
+ }).catch((e) => fail(e.message));
111
+ const ws = new WebSocket(wsUrl);
112
+ await new Promise((done) => (ws.onopen = done));
113
+ let nextId = 0;
114
+ const pending = new Map();
115
+ let sessionId;
116
+ ws.onmessage = (ev) => {
117
+ const msg = JSON.parse(String(ev.data));
118
+ if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
119
+ // A script's alert or confirm would hold the page; answer it so a click can go on.
120
+ else if (msg.method === "Page.javascriptDialogOpening") ws.send(JSON.stringify({ id: ++nextId, method: "Page.handleJavaScriptDialog", params: { accept: true }, sessionId: msg.sessionId || sessionId }));
121
+ };
122
+ // Every call has a deadline: a page that never answers costs 20 s, never the walk.
123
+ const send = (method, params = {}, session) => new Promise((done) => {
124
+ const id = ++nextId;
125
+ const t = setTimeout(() => (pending.delete(id), done({ error: { message: `${method} timed out` } })), 20000);
126
+ pending.set(id, (msg) => (clearTimeout(t), done(msg)));
127
+ ws.send(JSON.stringify({ id, method, params, sessionId: session }));
128
+ });
129
+ const { result: target } = await send("Target.createTarget", { url: "about:blank" });
130
+ const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
131
+ sessionId = att.sessionId;
132
+ const call = (method, params) => send(method, params, att.sessionId);
133
+ await call("Page.enable");
134
+ const evaluate = async (expression) => {
135
+ const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
136
+ if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
137
+ return r.result?.result?.value;
138
+ };
139
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
140
+ await call("Emulation.setDeviceMetricsOverride", { width, height: 900, deviceScaleFactor: 1, mobile: width < 768 });
141
+
142
+ // Every link, form and button on the rendered page: where it goes, and its words.
143
+ const readPage = `(() => {
144
+ const words = (el) => (el.innerText || el.value || el.getAttribute("aria-label") || el.title || "").trim().replace(/\\s+/g, " ").slice(0, 40);
145
+ const links = [...document.querySelectorAll("a")].map((a) => ({ href: a.getAttribute("href"), url: a.href, words: words(a) }));
146
+ // A form whose action names a page submits there: a way on, like a link. One with no action, "#" or
147
+ // script as its action is left to its buttons below.
148
+ const real = (v) => { const t = (v || "").trim(); return Boolean(t) && t !== "#" && !/^javascript:/i.test(t); };
149
+ const forms = [...document.forms].filter((f) => real(f.getAttribute("action"))).map((f) => ({ href: f.getAttribute("action").trim(), url: new URL(f.getAttribute("action").trim(), document.baseURI).href, words: words(f.querySelector("button, input[type=submit], input[type=image]") || f) || "form" }));
150
+ // Controls that may do something. Whether a script listens on them is asked of DevTools below, and
151
+ // a click shows where they lead. A control in a form that already names its page is that form's.
152
+ window.__controls = [...document.querySelectorAll("button, [role=button], input[type=button], input[type=submit], input[type=image]")]
153
+ .filter((b) => !b.closest("a") && !b.disabled && !b.getAttribute("popovertarget") && !b.getAttribute("commandfor") && !(b.form && real(b.form.getAttribute("action"))))
154
+ .slice(0, 40);
155
+ return { links, forms, buttons: window.__controls.map((b) => ({ words: words(b), inForm: Boolean(b.form || b.closest("form")), inline: Boolean(b.onclick || b.getAttribute("onclick")) })) };
156
+ })()`;
157
+ // A button does something when a click listener sits on it or on anything above it (a menu wired
158
+ // on its parent, a handler on document).
159
+ async function listened(i) {
160
+ const chain = await call("Runtime.evaluate", { expression: `(() => { const a = []; for (let n = window.__controls[${i}]; n; n = n.parentNode) a.push(n); a.push(window); return a; })()` });
161
+ const arrayId = chain.result?.result?.objectId;
162
+ if (!arrayId) return true;
163
+ const props = await call("Runtime.getProperties", { objectId: arrayId, ownProperties: true });
164
+ for (const p of props.result?.result || []) {
165
+ if (!/^\d+$/.test(p.name) || !p.value?.objectId) continue;
166
+ const l = await call("DOMDebugger.getEventListeners", { objectId: p.value.objectId });
167
+ if ((l.result?.listeners || []).some((x) => /^(click|pointerdown|pointerup|mousedown|mouseup|touchstart|touchend)$/.test(x.type))) return true;
168
+ }
169
+ return false;
170
+ }
171
+ // Open a page and wait for it to settle.
172
+ async function open(url) {
173
+ const nav = await call("Page.navigate", { url });
174
+ if (nav.result?.errorText || nav.error) return false;
175
+ await settle();
176
+ return true;
177
+ }
178
+ async function settle() {
179
+ for (let i = 0; i < 50 && (await evaluate("document.readyState").catch(() => "")) !== "complete"; i++) await sleep(100);
180
+ await sleep(wait);
181
+ }
182
+ // Click the i-th control on a fresh copy of the page and say where the browser is afterwards: a
183
+ // script that navigates ends on another page, a form with a script on it likewise.
184
+ async function clickThrough(url, i) {
185
+ if (!(await open(url))) return "";
186
+ await evaluate(readPage).catch(() => null);
187
+ // A required field would stop the submit before the script sees it; the walk is of the way on, not the validation.
188
+ await evaluate("for (const f of document.forms) f.noValidate = true").catch(() => null);
189
+ await evaluate(`window.__controls && window.__controls[${i}] && window.__controls[${i}].click()`).catch(() => null);
190
+ await sleep(wait);
191
+ await settle();
192
+ return (await evaluate("location.href").catch(() => "")) || "";
193
+ }
194
+
195
+ // ---- Stand-ins: what a page shows that the product does not really have yet. ----
196
+ // Read on every page the walk reaches. Marked in the markup: data-standin="picture" or "fact",
197
+ // optional data-standin-note. Not part of the link checks above or below.
198
+ const standins = [], unmarked = [];
199
+ const readStandins = `(() => {
200
+ const text = (el) => (el.innerText || "").trim().replace(/\\s+/g, " ").slice(0, 40);
201
+ const marked = [...document.querySelectorAll("[data-standin]")].map((el) => {
202
+ const img = el.matches("img") ? el : el.querySelector("img");
203
+ return { kind: (el.getAttribute("data-standin") || "").trim() || "unspecified", note: (el.getAttribute("data-standin-note") || "").trim(), words: img ? "" : text(el), alt: img ? (img.getAttribute("alt") || "").trim() : "", src: img ? img.src : "" };
204
+ });
205
+ const imgs = [...document.querySelectorAll("img")].map((i) => ({ src: i.src, alt: (i.getAttribute("alt") || "").trim(), marked: !!i.closest("[data-standin]") }));
206
+ return { marked, imgs };
207
+ })()`;
208
+ const creditsOf = new Map();
209
+ const credited = (file) => {
210
+ const dir = dirname(file);
211
+ if (!creditsOf.has(dir)) {
212
+ const list = join(dir, "credits.tsv");
213
+ const rows = existsSync(list) ? readFileSync(list, "utf8").split("\n").filter((l) => l && !l.startsWith("#")) : [];
214
+ creditsOf.set(dir, new Set(rows.map((l) => basename(l.split("\t")[1] || ""))));
215
+ }
216
+ return creditsOf.get(dir).has(basename(file));
217
+ };
218
+ const fileOf = (url) => (/^file:/.test(url || "") ? fileURLToPath(url.split(/[?#]/)[0]) : "");
219
+ async function collectStandins(page) {
220
+ const { marked, imgs } = await evaluate(readStandins).catch(() => ({ marked: [], imgs: [] }));
221
+ const seen = new Set();
222
+ for (const m of marked) {
223
+ const file = fileOf(m.src);
224
+ const what = [m.alt || (file && basename(file)) || m.words || "(nothing to show)"].concat(m.alt && file ? [`(${basename(file)})`] : []).join(" ");
225
+ const key = `${m.kind}|${what}`;
226
+ if (seen.has(key)) continue;
227
+ seen.add(key);
228
+ standins.push({ page, kind: m.kind, what, note: m.note });
229
+ }
230
+ for (const i of imgs) {
231
+ const file = fileOf(i.src);
232
+ if (file && !i.marked && credited(file) && !unmarked.some((u) => u.page === page && u.file === basename(file))) unmarked.push({ page, file: basename(file) });
233
+ }
234
+ }
235
+ // ---- end of stand-ins ----
236
+
237
+ const seen = new Set([startPath]);
238
+ const firstUrl = new Map([[startPath, start.split("#")[0]]]);
239
+ const queue = [startPath];
240
+ const broken = [], nowhere = [], deadEnds = [], outside = new Set();
241
+ // When the links run out, every page in the folder not reached yet is opened by itself.
242
+ const rest = () => readdirSync(dirname(startPath)).filter((f) => /\.html?$/i.test(f)).sort().map((f) => join(dirname(startPath), f)).filter((p) => !seen.has(p));
243
+ while (queue.length || (queue.push(...rest().slice(0, 1)), queue.length)) {
244
+ const path = queue.shift();
245
+ seen.add(path);
246
+ const pageUrl = firstUrl.get(path) || pathToFileURL(path).href;
247
+ if (!(await open(pageUrl))) {
248
+ broken.push({ from: "(start)", to: path });
249
+ continue;
250
+ }
251
+ const { links, forms, buttons } = await evaluate(readPage).catch(() => ({ links: [], forms: [], buttons: [] }));
252
+ const name = pageName(path);
253
+ await collectStandins(name);
254
+ let out = 0;
255
+ // A way on to url: out of the prototype, to a page that is not there, to this page, or to another to walk.
256
+ const take = (href, url, words) => {
257
+ if (!/^file:/.test(url)) return void outside.add(url);
258
+ const to = fileURLToPath(url.split(/[?#]/)[0]);
259
+ if (!inside(to)) return void outside.add(url);
260
+ if (!existsSync(to)) return void broken.push({ from: name, to: href, words });
261
+ if (to !== path) out++;
262
+ if (!seen.has(to)) {
263
+ seen.add(to);
264
+ firstUrl.set(to, url.split("#")[0]);
265
+ queue.push(to);
266
+ }
267
+ };
268
+ for (const l of links) {
269
+ const href = (l.href ?? "").trim();
270
+ if (!href || href === "#" || /^javascript:/i.test(href)) {
271
+ nowhere.push({ page: name, what: `link "${l.words || href || "(no words)"}"`, href: href || "(empty)" });
272
+ continue;
273
+ }
274
+ if (href.startsWith("#")) continue; // a jump within the page
275
+ take(href, l.url, l.words);
276
+ }
277
+ for (const f of forms) take(f.href, f.url, f.words);
278
+ // Ask which controls are wired before any click: a click leaves the page.
279
+ const wired = [];
280
+ for (const [i, b] of buttons.entries()) wired.push(b.inForm || b.inline || (await listened(i)));
281
+ for (const [i, b] of buttons.entries()) {
282
+ if (!wired[i]) {
283
+ nowhere.push({ page: name, what: `button "${b.words || "(no words)"}"`, href: "no action" });
284
+ continue;
285
+ }
286
+ // Wired: click it and see whether the browser goes to another page.
287
+ const after = await clickThrough(pageUrl, i);
288
+ if (!after || !/^file:/.test(after) || fileURLToPath(after.split(/[?#]/)[0]) === path) {
289
+ if (after && !/^(file:|about:|chrome-error:)/.test(after)) outside.add(after);
290
+ continue;
291
+ }
292
+ take(after, after, b.words);
293
+ }
294
+ if (!out) deadEnds.push(name);
295
+ }
296
+ const pages = [...seen].map((p) => ({ page: pageName(p) }));
297
+
298
+ if (json) console.log(JSON.stringify({ pages, broken, nowhere, deadEnds, standins, unmarked, outside: [...outside] }, null, 1));
299
+ else {
300
+ for (const b of broken) console.log(`broken ${b.from} → ${b.to}${b.words ? ` ("${b.words}")` : ""}`);
301
+ for (const n of nowhere) console.log(`nowhere ${n.page}: ${n.what} (${n.href})`);
302
+ for (const d of deadEnds) console.log(`dead end ${d}: no link to another page`);
303
+ for (const u of unmarked) console.log(`unmarked ${u.page}: picture ${u.file} is a stand-in (credits.tsv) and has no data-standin`);
304
+ for (const s of standins) console.log(`stand-in ${s.page}: ${s.kind} ${s.kind === "fact" ? `"${s.what}"` : s.what}${s.note ? ` (${s.note})` : ""}`);
305
+ console.log(standins.length ? `stand-ins: ${standins.length} (${[...new Set(standins.map((s) => s.kind))].map((k) => `${standins.filter((s) => s.kind === k).length} ${k}`).join(", ")}), what they still need to supply` : "stand-ins: none marked");
306
+ console.log(`pages: ${pages.map((p) => p.page).join(", ")}${outside.size ? ` · ${outside.size} link${outside.size > 1 ? "s" : ""} out of the prototype, not followed` : ""}`);
307
+ }
308
+ process.exit(broken.length || nowhere.length || deadEnds.length || unmarked.length ? 1 : 0);
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ // A few clearly licensed pictures of the product's own subject, from Wikimedia Commons, to design
3
+ // with as stand-ins until the real ones come. It is not a bulk downloader: 4 by default, 12 at most.
4
+ // Only licences that hold in every country are kept: CC0, CC BY and CC BY-SA (any version), and
5
+ // public domain marked as worldwide (read from the file's templates, as the source's own licence
6
+ // name does not tell the two kinds apart). Public domain in one country only ("PD-US", "PD-Russia"),
7
+ // NC, ND, GFDL-only, fair use, unknown, and anything the source flags as restricted or non-free
8
+ // is left out. A licence that asks for credit needs an author to credit: with none, the picture
9
+ // is left out too. Node 22+, no dependencies.
10
+ //
11
+ // node pictures.mjs "sourdough bread" --out .longbeard/design/pictures
12
+ // node pictures.mjs "flour on a wooden bench" --out .longbeard/design/pictures --count 4 --min 1200 --orientation landscape
13
+ //
14
+ // Each picture is saved 1600 wide as <name>.jpg (or .png, .webp) in --out. A picture already
15
+ // credited there is skipped, so running again adds, never duplicates. Each new one gets a row in <out>/credits.tsv:
16
+ // name, file, source, author, licence, licence link, a ready credit line, share-alike (yes or no). The
17
+ // first two columns are what contact-sheet.mjs reads; a credits.tsv from before the last three columns
18
+ // stays readable, its rows just stop at the licence.
19
+ // --count 4 (1 to 12), --min 1200 (the longer side, in pixels), --orientation landscape|portrait|square,
20
+ // --timeout 30 (seconds to wait for each request), --api <url> (the Commons endpoint: for tests)
21
+ // Search the subject, not a mood: "sourdough loaf on a board", not "cosy".
22
+ import { existsSync, mkdirSync, readFileSync, appendFileSync, writeFileSync } from "node:fs";
23
+ import { extname, join } from "node:path";
24
+
25
+ const args = process.argv.slice(2);
26
+ const flag = (name, def = "") => {
27
+ const i = args.indexOf(`--${name}`);
28
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
29
+ };
30
+ const fail = (text) => {
31
+ console.error(`pictures: ${text}`);
32
+ process.exit(2);
33
+ };
34
+ const api = flag("api", "https://commons.wikimedia.org/w/api.php");
35
+ const outArg = flag("out");
36
+ const count = Number(flag("count", "4"));
37
+ const min = Number(flag("min", "1200"));
38
+ const orientation = flag("orientation").toLowerCase();
39
+ const timeout = Number(flag("timeout", "30"));
40
+ const query = args.join(" ").trim();
41
+ if (!query || !outArg || !Number.isInteger(count) || count < 1 || count > 12 || !(min >= 0) || !(timeout > 0) || (orientation && !["landscape", "portrait", "square"].includes(orientation))) {
42
+ console.error(`usage: node pictures.mjs "subject" --out <dir> [--count 4] [--min 1200] [--orientation landscape|portrait|square] [--timeout 30]`);
43
+ process.exit(2);
44
+ }
45
+ const headers = { "User-Agent": "longbeard-pictures (https://github.com/jonanderdev/longbeard)" };
46
+
47
+ // Public domain is not one thing. Commons gives nearly every such file the same short name, "Public
48
+ // domain", whether it is so everywhere or only in one country (a US government photograph, a work
49
+ // old enough in the US alone), so the name cannot tell them apart; the templates on the file page
50
+ // can. A public-domain file is kept only when its page carries a template that says it holds
51
+ // everywhere: the worldwide public-domain mark, or the author's own dedication. The search asks for
52
+ // just these, so a page's list is short, and a page that shows none is left out.
53
+ const WORLDWIDE_PD_TEMPLATES = ["Cc-pd-mark-footer", "PD-self", "PD-author"];
54
+ const WORLDWIDE_PD = /^(public domain|public domain mark|pdm|pd|pd-self|pd-old|pd-old-100(-expired)?|pd-author)$/i;
55
+ // The licence as { name, link, shareAlike, credit } (credit: the licence asks for one), or
56
+ // { reason } when the picture is not one we can design with freely. templates: the names of the
57
+ // worldwide public-domain templates found on the file's page.
58
+ function licence(meta = {}, templates = []) {
59
+ const val = (k) => String(meta[k]?.value ?? "").trim();
60
+ const short = val("LicenseShortName"), code = val("License"), terms = val("UsageTerms"), link = val("LicenseUrl");
61
+ const text = `${short} ${code}`;
62
+ if (!text.trim()) return { reason: "licence" };
63
+ if (val("NonFree") && !/^(false|0|no)$/i.test(val("NonFree"))) return { reason: "restricted" };
64
+ if (val("Restrictions")) return { reason: "restricted" };
65
+ if (/\bNC\b|\bND\b|-nc\b|-nd\b|non-?commercial|no-?deriv|fair use/i.test(`${text} ${terms}`)) return { reason: "licence" };
66
+ if (/\bcc0\b|cc-zero/i.test(text)) {
67
+ return { name: "CC0", link: link || "https://creativecommons.org/publicdomain/zero/1.0/", shareAlike: false, credit: false };
68
+ }
69
+ for (const s of [short, code]) {
70
+ const m = s.match(/^cc[ -]by(?:[ -](sa))?(?:[ -](\d(?:\.\d)?))?(?:[ -]([a-z]{2,3})(?![a-z]))?/i);
71
+ if (m) {
72
+ const version = m[2] ? (m[2].includes(".") ? m[2] : `${m[2]}.0`) : "";
73
+ return {
74
+ // A ported licence keeps its country: "CC BY-SA 3.0 de".
75
+ name: `CC BY${m[1] ? "-SA" : ""}${version ? ` ${version}` : ""}${version && m[3] ? ` ${m[3].toLowerCase()}` : ""}`,
76
+ link: link || (version ? `https://creativecommons.org/licenses/${m[1] ? "by-sa" : "by"}/${version}/` : ""),
77
+ shareAlike: Boolean(m[1]), credit: true,
78
+ };
79
+ }
80
+ }
81
+ if (WORLDWIDE_PD.test(short) || (!short && WORLDWIDE_PD.test(code))) {
82
+ // The terms must not narrow it to a place or a condition, and the page must say it holds everywhere.
83
+ if (/\b(only|united states|u\.?s\.?a?\b|russia|country|countries|jurisdiction|if|except|unless)\b/i.test(terms)) return { reason: "licence" };
84
+ if (!templates.length) return { reason: "licence" };
85
+ return { name: "Public domain", link: /^https?:/i.test(link) ? link : "", shareAlike: false, credit: val("AttributionRequired") === "true" };
86
+ }
87
+ return { reason: "licence" };
88
+ }
89
+ const plain = (html) => String(html ?? "").replace(/<(\w+)[^>]*display:\s*none[^>]*>.*?<\/\1>/gis, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/\s+/g, " ").trim();
90
+ // An author we can credit: a name, not "unknown" or an empty field.
91
+ const usable = (author) => author && !/^(unknown|anonymous|anon|not specified|not known|n\/a|none|\?+|-+)( (author|artist|photographer|creator|source))?\.?$/i.test(author);
92
+ const name = (title) => title.replace(/^File:/i, "").replace(/\.[a-z0-9]+$/i, "").replace(/_/g, " ").trim();
93
+ const slug = (title) => name(title).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "picture";
94
+
95
+ const url = new URL(api);
96
+ for (const [k, v] of Object.entries({
97
+ action: "query", format: "json", generator: "search", gsrnamespace: "6", gsrsearch: `${query} filetype:bitmap`,
98
+ gsrlimit: String(Math.min(count * 6, 50)), prop: "imageinfo|templates", iiprop: "url|size|mime|extmetadata", iiurlwidth: "1600",
99
+ tlnamespace: "10", tllimit: "500", tltemplates: WORLDWIDE_PD_TEMPLATES.map((t) => `Template:${t}`).join("|"),
100
+ })) url.searchParams.set(k, v);
101
+
102
+ let data;
103
+ try {
104
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeout * 1000) });
105
+ if (!res.ok) fail(`Commons answered ${res.status} for the search`);
106
+ data = await res.json();
107
+ } catch (e) {
108
+ fail(e.name === "TimeoutError" ? `Commons did not answer the search within ${timeout}s` : `could not reach Commons (${e.cause?.code ?? e.message})`);
109
+ }
110
+ if (data?.error) fail(`Commons said: ${data.error.info ?? data.error.code}`);
111
+ const pages = Object.values(data?.query?.pages ?? {}).sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
112
+
113
+ const left = { licence: 0, restricted: 0, "no author": 0, "too small": 0, orientation: 0, type: 0 };
114
+ const passing = [];
115
+ for (const page of pages) {
116
+ const info = page.imageinfo?.[0];
117
+ if (!info || !["image/jpeg", "image/png", "image/webp"].includes(info.mime)) { left.type++; continue; }
118
+ const { width: w = 0, height: h = 0 } = info;
119
+ if (Math.max(w, h) < min) { left["too small"]++; continue; }
120
+ const shape = w > h * 1.1 ? "landscape" : h > w * 1.1 ? "portrait" : "square";
121
+ if (orientation && shape !== orientation) { left.orientation++; continue; }
122
+ const marks = (page.templates ?? []).map((t) => String(t.title ?? "").replace(/^Template:/i, "")).filter((t) => WORLDWIDE_PD_TEMPLATES.includes(t));
123
+ const lic = licence(info.extmetadata, marks);
124
+ if (lic.reason) { left[lic.reason]++; continue; }
125
+ const author = plain(info.extmetadata?.Artist?.value).slice(0, 200).trim();
126
+ if (lic.credit && !usable(author)) {
127
+ // A licence that asks for credit cannot be met without a name to give it to.
128
+ console.log(`left out ${name(page.title)}: ${lic.name} asks for credit and no author is given`);
129
+ left["no author"]++;
130
+ continue;
131
+ }
132
+ passing.push({ title: page.title, info, licence: lic, author: usable(author) ? author : "unknown" });
133
+ }
134
+
135
+ const why = Object.entries(left).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ");
136
+ if (!passing.length) {
137
+ console.error(`pictures: none of ${pages.length} found for "${query}" could be kept${why ? ` (left out: ${why})` : ""}. Try another query: search the subject, not a mood.`);
138
+ process.exit(1);
139
+ }
140
+
141
+ mkdirSync(outArg, { recursive: true });
142
+ const credits = join(outArg, "credits.tsv");
143
+ const HEADER = "# name\tfile\tsource\tauthor\tlicence\tlicence link\tcredit line\tshare-alike\n";
144
+ const OLD_HEADER = "# name\tfile\tsource\tauthor\tlicence\n";
145
+ if (!existsSync(credits)) writeFileSync(credits, HEADER);
146
+ else {
147
+ // A file from before the licence link: the new header over the old rows, which stay as they were.
148
+ const text = readFileSync(credits, "utf8");
149
+ if (text.startsWith(OLD_HEADER)) writeFileSync(credits, HEADER + text.slice(OLD_HEADER.length));
150
+ }
151
+ // Rows already credited: which files are taken, and which Commons pictures are already here. A
152
+ // picture is known by its source page (its name when there is none), never by its file name: two
153
+ // titles can cut down to the same name.
154
+ const rows = readFileSync(credits, "utf8").split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split("\t"));
155
+ const listed = new Set(rows.map((r) => r[1]));
156
+ const known = new Map(rows.map((r) => [r[2] || `name:${r[0]}`, r[1]]));
157
+ const clean = (s) => String(s).replace(/[\t\r\n]+/g, " ").trim();
158
+
159
+ let kept = 0, already = 0, broken = 0, shareAlike = 0;
160
+ for (const pic of passing) {
161
+ if (kept >= count) break;
162
+ const src = pic.info.thumburl || pic.info.url;
163
+ let ext = extname(new URL(src).pathname).toLowerCase();
164
+ if (ext === ".jpeg") ext = ".jpg";
165
+ if (![".jpg", ".png", ".webp"].includes(ext)) ext = ".jpg";
166
+ const key = clean(pic.info.descriptionurl ?? "") || `name:${clean(name(pic.title))}`;
167
+ if (known.has(key) && existsSync(known.get(key))) { already++; continue; }
168
+ // A name another picture (or a file of yours) already holds gets -2, -3 …
169
+ let path = join(outArg, `${slug(pic.title)}${ext}`);
170
+ for (let i = 2; existsSync(path) || listed.has(path); i++) path = join(outArg, `${slug(pic.title)}-${i}${ext}`);
171
+ let bytes;
172
+ try {
173
+ const res = await fetch(src, { headers, signal: AbortSignal.timeout(timeout * 1000) });
174
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
175
+ bytes = Buffer.from(await res.arrayBuffer());
176
+ } catch (e) {
177
+ console.error(`pictures: could not download ${pic.title} (${e.name === "TimeoutError" ? `no answer within ${timeout}s` : e.cause?.code ?? e.message}); skipped`);
178
+ broken++;
179
+ continue;
180
+ }
181
+ writeFileSync(path, bytes);
182
+ const lic = pic.licence;
183
+ const line = `"${clean(name(pic.title))}"${pic.author === "unknown" ? "" : ` by ${clean(pic.author)}`}, ${lic.name}${lic.link ? `, ${lic.link}` : ""}`;
184
+ appendFileSync(credits, [name(pic.title), path, pic.info.descriptionurl ?? "", pic.author, lic.name, lic.link, line, lic.shareAlike ? "yes" : "no"].map(clean).join("\t") + "\n");
185
+ if (lic.shareAlike) shareAlike++;
186
+ listed.add(path);
187
+ known.set(key, path);
188
+ kept++;
189
+ console.log(`kept ${path} ${lic.name} ${pic.author}`);
190
+ }
191
+ if (broken && !kept && !already) fail(`no picture could be downloaded from Commons`);
192
+ const notes = [`${kept} kept in ${outArg}`];
193
+ if (already) notes.push(`${already} already there`);
194
+ notes.push(why ? `left out: ${why}` : "none left out");
195
+ if (broken) notes.push(`${broken} failed to download`);
196
+ console.log(`${notes.join("; ")}. Credits in ${credits}.`);
197
+ if (shareAlike) console.log(`share-alike: a cropped or toned version of ${shareAlike === 1 ? "the share-alike picture" : "a share-alike picture"} must carry the same licence. The credit lines are in ${credits}.`);