@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.
- package/AGENTS.md +4 -5
- package/CHANGELOG.md +72 -0
- package/README.md +64 -43
- package/beard.json +124 -28
- package/bin/long-beard.js +171 -36
- package/package.json +1 -1
- package/skills/design/SKILL.md +51 -126
- package/skills/design-brief/SKILL.md +146 -0
- package/skills/design-brief/references/graphic.md +59 -0
- package/skills/design-check/SKILL.md +27 -11
- package/skills/design-check/references/design-rules.md +21 -7
- package/skills/design-check/scripts/capture.mjs +121 -37
- package/skills/design-check/scripts/contrast.mjs +23 -9
- package/skills/design-check/scripts/rules.mjs +613 -0
- package/skills/design-check/scripts/screen-contrast.mjs +428 -0
- package/skills/design-check/scripts/tokens.mjs +346 -0
- package/skills/design-content/SKILL.md +118 -0
- package/skills/design-content/scripts/contact-sheet.mjs +259 -0
- package/skills/design-content/scripts/pictures.mjs +197 -0
- package/skills/design-direction/SKILL.md +115 -200
- package/skills/design-direction/references/controls.md +58 -0
- package/skills/{design → design-direction}/references/design-rules.md +21 -7
- package/skills/design-direction/references/five-second.md +47 -0
- package/skills/design-direction/references/full-build.md +19 -0
- package/skills/design-direction/references/graphic.md +35 -0
- package/skills/design-direction/references/grid.md +114 -0
- package/skills/design-direction/references/library.md +75 -0
- package/skills/design-direction/references/screen-template.html +233 -0
- package/skills/design-direction/references/subject.md +33 -0
- package/skills/design-direction/scripts/capture.mjs +121 -37
- package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
- package/skills/design-direction/scripts/fonts.mjs +276 -0
- package/skills/design-direction/scripts/layout-diff.mjs +118 -0
- package/skills/design-direction/scripts/measure.mjs +1728 -0
- package/skills/design-direction/scripts/moodboard.mjs +123 -32
- package/skills/design-direction/scripts/picture-cast.mjs +270 -0
- package/skills/design-direction/scripts/pictures.mjs +197 -0
- package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
- package/skills/design-direction/scripts/sheet.mjs +67 -0
- package/skills/design-direction/scripts/subject-colours.mjs +410 -0
- package/skills/design-families/SKILL.md +138 -0
- package/skills/design-families/scripts/contact-sheet.mjs +259 -0
- package/skills/design-families/scripts/families.mjs +606 -0
- package/skills/design-families/scripts/measure.mjs +1728 -0
- package/skills/design-families/scripts/moodboard.mjs +467 -0
- package/skills/design-families/scripts/tag.mjs +289 -0
- package/skills/design-figma/SKILL.md +69 -0
- package/skills/design-figma/references/graphic.md +26 -0
- package/skills/design-identity/SKILL.md +134 -0
- package/skills/design-identity/references/graphic.md +8 -0
- package/skills/design-identity/references/identity-board.html +140 -0
- package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
- package/skills/design-identity/scripts/colours.mjs +213 -0
- package/skills/design-identity/scripts/contrast.mjs +41 -0
- package/skills/design-identity/scripts/fonts.mjs +276 -0
- package/skills/design-identity/scripts/measure.mjs +1728 -0
- package/skills/design-identity/scripts/sheet.mjs +67 -0
- package/skills/design-identity/scripts/subject-colours.mjs +410 -0
- package/skills/design-moodboard/SKILL.md +184 -0
- package/skills/design-moodboard/references/graphic.md +25 -0
- package/skills/{design-direction → design-moodboard}/references/sources.md +21 -11
- package/skills/design-moodboard/scripts/capture.mjs +893 -0
- package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
- package/skills/design-moodboard/scripts/crops.mjs +256 -0
- package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
- package/skills/design-moodboard/scripts/families.mjs +606 -0
- package/skills/design-moodboard/scripts/group.mjs +221 -0
- package/skills/design-moodboard/scripts/measure.mjs +1728 -0
- package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
- package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
- package/skills/design-moodboard/scripts/pictures.mjs +197 -0
- package/skills/design-moodboard/scripts/tag.mjs +289 -0
- package/skills/design-prototype/SKILL.md +149 -0
- package/skills/design-prototype/references/design-md-template.md +82 -0
- package/skills/design-prototype/references/design-rules.md +203 -0
- package/skills/design-prototype/references/five-second.md +47 -0
- package/skills/design-prototype/references/graphic.md +27 -0
- package/skills/design-prototype/scripts/capture.mjs +893 -0
- package/skills/design-prototype/scripts/contrast.mjs +41 -0
- package/skills/design-prototype/scripts/links.mjs +308 -0
- package/skills/design-prototype/scripts/pictures.mjs +197 -0
- package/skills/design-prototype/scripts/rules.mjs +613 -0
- package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
- package/skills/design-prototype/scripts/sheet.mjs +67 -0
- package/skills/design-prototype/scripts/tokens.mjs +346 -0
- package/skills/design-wordmark/SKILL.md +65 -0
- package/skills/design-wordmark/scripts/capture.mjs +893 -0
- package/skills/design-wordmark/scripts/sheet.mjs +67 -0
- package/skills/framework-skills/SKILL.md +71 -0
- package/skills/idea/SKILL.md +13 -7
- package/skills/idea/references/graphic.md +64 -0
- package/skills/design/references/design-md-template.md +0 -58
- package/skills/design/scripts/contrast.mjs +0 -27
- package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Build labelled contact sheets from a TSV of label\timageURL. The image can
|
|
3
|
+
// be a local file too, so a family's references are sorted by eye from a few
|
|
4
|
+
// sheets of thumbnails, not opened one at a time.
|
|
5
|
+
// Writes JPEG grids (~36 per sheet) into an output directory (scratch, not .longbeard/design/).
|
|
6
|
+
// Viewing listing thumbnails is allowed; this is not a capture.
|
|
7
|
+
//
|
|
8
|
+
// node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets
|
|
9
|
+
// node contact-sheet.mjs family-f3.tsv --out <scratch>/f3 --contain # TSV: label<TAB>refs/name.jpg
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import {
|
|
12
|
+
existsSync,
|
|
13
|
+
mkdirSync,
|
|
14
|
+
mkdtempSync,
|
|
15
|
+
readFileSync,
|
|
16
|
+
rmSync,
|
|
17
|
+
writeFileSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { join, resolve } from "node:path";
|
|
21
|
+
import { pathToFileURL } from "node:url";
|
|
22
|
+
|
|
23
|
+
const args = process.argv.slice(2);
|
|
24
|
+
const flag = (name, def) => {
|
|
25
|
+
const i = args.indexOf(`--${name}`);
|
|
26
|
+
if (i === -1) return def;
|
|
27
|
+
const v = args[i + 1];
|
|
28
|
+
args.splice(i, 2);
|
|
29
|
+
return v;
|
|
30
|
+
};
|
|
31
|
+
const tsvPath = args[0];
|
|
32
|
+
const outDir = resolve(flag("out", "") || "");
|
|
33
|
+
const perSheet = Math.max(1, Number(flag("per", "36")) || 36);
|
|
34
|
+
const cols = Math.min(8, Math.max(1, Number(flag("cols", "6")) || 6));
|
|
35
|
+
const containAt = args.indexOf("--contain");
|
|
36
|
+
const contain = containAt !== -1;
|
|
37
|
+
if (contain) args.splice(containAt, 1);
|
|
38
|
+
if (!tsvPath || !outDir) {
|
|
39
|
+
console.error("usage: node contact-sheet.mjs candidates.tsv --out <scratch>/sheets [--per 36] [--cols 6] [--contain]");
|
|
40
|
+
process.exit(2);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const lines = readFileSync(tsvPath, "utf8")
|
|
44
|
+
.split(/\r?\n/)
|
|
45
|
+
.map((l) => l.trim())
|
|
46
|
+
.filter(Boolean)
|
|
47
|
+
.map((l) => {
|
|
48
|
+
// label\timageURL, and any columns after that (a listing URL) are ignored.
|
|
49
|
+
const cols = l.split("\t").map((c) => c.trim());
|
|
50
|
+
if (cols.length === 1) return { label: l, url: l };
|
|
51
|
+
return { label: cols[0], url: cols[1] };
|
|
52
|
+
})
|
|
53
|
+
.map((r) => (/^https?:\/\//i.test(r.url) || !existsSync(r.url) ? r : { ...r, url: pathToFileURL(resolve(r.url)).href }))
|
|
54
|
+
.filter((r) => /^(https?|file):\/\//i.test(r.url));
|
|
55
|
+
|
|
56
|
+
if (!lines.length) {
|
|
57
|
+
console.error("no label\timageURL rows found");
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function findChrome() {
|
|
62
|
+
const env = process.env.CHROME_PATH;
|
|
63
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
64
|
+
if (env === "none") return null;
|
|
65
|
+
if (env && existsSync(env)) return env;
|
|
66
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
67
|
+
const local = process.env.LOCALAPPDATA || "";
|
|
68
|
+
const pf = process.env.PROGRAMFILES || "C:\\Program Files";
|
|
69
|
+
const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
|
|
70
|
+
const candidates = [
|
|
71
|
+
join(pf, "Google/Chrome/Application/chrome.exe"),
|
|
72
|
+
join(pf86, "Google/Chrome/Application/chrome.exe"),
|
|
73
|
+
join(local, "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
|
+
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
78
|
+
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
|
79
|
+
"/usr/bin/google-chrome",
|
|
80
|
+
"/usr/bin/google-chrome-stable",
|
|
81
|
+
"/usr/bin/chromium",
|
|
82
|
+
"/usr/bin/chromium-browser",
|
|
83
|
+
];
|
|
84
|
+
return candidates.find((path) => path && existsSync(path)) || null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
88
|
+
const exe = findChrome();
|
|
89
|
+
if (!exe) {
|
|
90
|
+
console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
|
|
91
|
+
process.exit(1);
|
|
92
|
+
}
|
|
93
|
+
if (typeof WebSocket === "undefined") {
|
|
94
|
+
console.error("Node 22+ is required.");
|
|
95
|
+
process.exit(1);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const dir = mkdtempSync(join(tmpdir(), "hunt-sheet-"));
|
|
99
|
+
let proc;
|
|
100
|
+
const drop = () => {
|
|
101
|
+
try {
|
|
102
|
+
if (proc?.pid) process.kill(proc.pid, "SIGKILL");
|
|
103
|
+
} catch {}
|
|
104
|
+
try {
|
|
105
|
+
rmSync(dir, { recursive: true, force: true });
|
|
106
|
+
} catch {}
|
|
107
|
+
};
|
|
108
|
+
process.once("exit", drop);
|
|
109
|
+
|
|
110
|
+
proc = spawn(
|
|
111
|
+
exe,
|
|
112
|
+
[
|
|
113
|
+
"--headless=new",
|
|
114
|
+
"--remote-debugging-port=0",
|
|
115
|
+
`--user-data-dir=${dir}`,
|
|
116
|
+
"--no-first-run",
|
|
117
|
+
"--hide-scrollbars",
|
|
118
|
+
"--mute-audio",
|
|
119
|
+
"--force-color-profile=srgb",
|
|
120
|
+
"--window-size=1600,1200",
|
|
121
|
+
"about:blank",
|
|
122
|
+
],
|
|
123
|
+
{ stdio: ["ignore", "ignore", "pipe"] },
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
let buf = "";
|
|
127
|
+
const wsUrl = await new Promise((resolveWs, reject) => {
|
|
128
|
+
const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
|
|
129
|
+
proc.stderr.on("data", (d) => {
|
|
130
|
+
buf += d.toString();
|
|
131
|
+
const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
|
|
132
|
+
if (m) {
|
|
133
|
+
clearTimeout(t);
|
|
134
|
+
resolveWs(m[1]);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
proc.on("exit", (code) => {
|
|
138
|
+
clearTimeout(t);
|
|
139
|
+
reject(new Error(`Chrome exited ${code}`));
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const ws = new WebSocket(wsUrl);
|
|
144
|
+
await new Promise((res, rej) => {
|
|
145
|
+
ws.onopen = res;
|
|
146
|
+
ws.onerror = () => rej(new Error("CDP socket failed"));
|
|
147
|
+
});
|
|
148
|
+
let nextId = 1;
|
|
149
|
+
const pending = new Map();
|
|
150
|
+
ws.onmessage = (ev) => {
|
|
151
|
+
const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
|
|
152
|
+
if (msg.id && pending.has(msg.id)) {
|
|
153
|
+
const { resolve: ok, reject: bad } = pending.get(msg.id);
|
|
154
|
+
pending.delete(msg.id);
|
|
155
|
+
if (msg.error) bad(new Error(msg.error.message));
|
|
156
|
+
else ok(msg.result);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
|
|
160
|
+
const id = nextId++;
|
|
161
|
+
return new Promise((resolveSend, reject) => {
|
|
162
|
+
const timer = setTimeout(() => {
|
|
163
|
+
pending.delete(id);
|
|
164
|
+
reject(new Error(`CDP timeout: ${method}`));
|
|
165
|
+
}, timeoutMs);
|
|
166
|
+
pending.set(id, {
|
|
167
|
+
resolve: (v) => {
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
resolveSend(v);
|
|
170
|
+
},
|
|
171
|
+
reject: (e) => {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
reject(e);
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
|
|
181
|
+
const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
|
|
182
|
+
const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
|
|
183
|
+
|
|
184
|
+
await page("Page.enable");
|
|
185
|
+
await page("Runtime.enable");
|
|
186
|
+
await page("Emulation.setDeviceMetricsOverride", {
|
|
187
|
+
width: 1600,
|
|
188
|
+
height: 1200,
|
|
189
|
+
deviceScaleFactor: 1,
|
|
190
|
+
mobile: false,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
mkdirSync(outDir, { recursive: true });
|
|
194
|
+
const sheets = [];
|
|
195
|
+
for (let i = 0; i < lines.length; i += perSheet) {
|
|
196
|
+
sheets.push(lines.slice(i, i + perSheet));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const esc = (s) =>
|
|
200
|
+
String(s)
|
|
201
|
+
.replace(/&/g, "&")
|
|
202
|
+
.replace(/</g, "<")
|
|
203
|
+
.replace(/>/g, ">")
|
|
204
|
+
.replace(/"/g, """);
|
|
205
|
+
|
|
206
|
+
for (let s = 0; s < sheets.length; s++) {
|
|
207
|
+
const cells = sheets[s]
|
|
208
|
+
.map(
|
|
209
|
+
(r) =>
|
|
210
|
+
`<figure><img src="${esc(r.url)}" loading="eager"><figcaption>${esc(r.label)}</figcaption></figure>`,
|
|
211
|
+
)
|
|
212
|
+
.join("\n");
|
|
213
|
+
const html = `<!doctype html><meta charset=utf-8>
|
|
214
|
+
<style>
|
|
215
|
+
body { margin: 16px; background: #1a1a1a; color: #eee; font: 11px/1.2 system-ui, sans-serif; }
|
|
216
|
+
.grid { display: grid; grid-template-columns: repeat(${cols}, 1fr); gap: 10px; }
|
|
217
|
+
figure { margin: 0; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
|
|
218
|
+
img { display: block; width: 100%; height: ${contain ? Math.round(1200 / cols) : 140}px; object-fit: ${contain ? "contain" : "cover"}; background: #111; }
|
|
219
|
+
figcaption { padding: 6px 8px; word-break: break-word; max-height: 2.4em; overflow: hidden; }
|
|
220
|
+
</style>
|
|
221
|
+
<div class="grid">${cells}</div>
|
|
222
|
+
<script>
|
|
223
|
+
Promise.all([...document.images].map((img) => img.decode().catch(() => {}))).then(() => {
|
|
224
|
+
document.title = "ready";
|
|
225
|
+
});
|
|
226
|
+
</script>`;
|
|
227
|
+
const htmlPath = join(dir, `sheet-${s + 1}.html`);
|
|
228
|
+
writeFileSync(htmlPath, html);
|
|
229
|
+
await page("Page.navigate", { url: pathToFileURL(htmlPath).href }, 30000);
|
|
230
|
+
await sleep(500);
|
|
231
|
+
for (let i = 0; i < 60; i++) {
|
|
232
|
+
const title = (
|
|
233
|
+
await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
|
|
234
|
+
).result.value;
|
|
235
|
+
if (title === "ready") break;
|
|
236
|
+
await sleep(150);
|
|
237
|
+
}
|
|
238
|
+
await sleep(400);
|
|
239
|
+
const metrics = await page("Page.getLayoutMetrics");
|
|
240
|
+
const size = metrics.cssContentSize || metrics.contentSize;
|
|
241
|
+
const width = Math.max(1, Math.ceil(size.width || 1600));
|
|
242
|
+
const height = Math.max(1, Math.min(Math.ceil(size.height || 1200), 8000));
|
|
243
|
+
const { data } = await page(
|
|
244
|
+
"Page.captureScreenshot",
|
|
245
|
+
{
|
|
246
|
+
format: "jpeg",
|
|
247
|
+
quality: 80,
|
|
248
|
+
captureBeyondViewport: true,
|
|
249
|
+
clip: { x: 0, y: 0, width, height, scale: 1 },
|
|
250
|
+
},
|
|
251
|
+
60000,
|
|
252
|
+
);
|
|
253
|
+
const outPath = join(outDir, `sheet-${String(s + 1).padStart(2, "0")}.jpg`);
|
|
254
|
+
writeFileSync(outPath, Buffer.from(data, "base64"));
|
|
255
|
+
console.log(outPath);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
drop();
|
|
259
|
+
process.exit(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(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/�?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}.`);
|