@jonandev/longbeard 0.9.0 → 0.11.0

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.
@@ -0,0 +1,189 @@
1
+ # Design rules
2
+
3
+ How a screen is checked. Read by `design` before it prototypes and by `design-check` on every frame and build.
4
+
5
+ These rules decide execution, never the look. The direction and `DESIGN.md` decide the look. A rule that seems to ask for a colour, a typeface or a style is misread. It asks only that whatever was chosen is used with intent.
6
+
7
+ ## How to use this
8
+
9
+ - Check from a screenshot. Every check below can be passed or failed by looking at a rendered screen at its real size. When a check needs a state you cannot see (focus, error, empty), it needs that state's frame, and a missing frame fails rule 8.
10
+ - Go in order: **Idea** first, then every **hard** check, then **soft**.
11
+ - **Hard** is the floor: structure, contrast, targets, focus and states. A hard failure blocks the screen. `DESIGN.md` cannot waive it.
12
+ - **Soft** is a default. `DESIGN.md` may override a soft check on purpose, with a written reason. A soft finding with no reason in `DESIGN.md` is reported, not blocked.
13
+ - A finding is four things: the rule (number and check), hard or soft, where on the screen, and the fix.
14
+ - The shared core applies to everything. Then add the site list or the app list, whichever the brief's surface says.
15
+
16
+ ## 0. Idea
17
+
18
+ **Principle:** the screen says one thing about this product that a screen from another product would not.
19
+
20
+ - [soft] Cover the logo and the name. Is it still recognisably this product, from its content, imagery, voice or structure? A screen that could belong to any product in the category fails.
21
+ - [soft] You can say what the screen is for in one sentence, and the most visible element serves that sentence.
22
+ - [soft] The ownable idea in `DESIGN.md` (or the direction, before `DESIGN.md` exists) shows up somewhere you can point to.
23
+
24
+ ## 1. Hierarchy
25
+
26
+ **Principle:** the eye lands first on what matters most, then moves in the order the task needs.
27
+
28
+ - [hard] Exactly one element is the most prominent on the screen. Squint or blur the shot: one thing still stands out.
29
+ - [hard] The primary action is easier to find than any secondary action. If two actions look equally important, only one of them should be.
30
+ - [soft] Prominence comes from at most two of size, weight, colour and position at once. Using all four on one element is shouting.
31
+ - [soft] Secondary text (meta, captions, help) is visibly quieter than body text, by lighter colour or smaller size, not both pushed to the limit.
32
+
33
+ ## 2. Grouping
34
+
35
+ **Principle:** things that belong together look together, and things that do not are kept apart.
36
+
37
+ - [hard] The space between related items is clearly smaller than the space between groups. A label sits closer to its field than to the field above.
38
+ - [soft] Each group is separated by one device: space, a tone step, a box, or a line. Two at once (a boxed card with a divider inside a tinted panel) is noise.
39
+ - [soft] A reader can count the groups on the screen at a glance, and the count matches the sections the brief describes.
40
+
41
+ ## 3. Alignment and grid
42
+
43
+ **Principle:** every element sits on a line shared with something else.
44
+
45
+ - [hard] Left edges of text blocks in one column line up. No block is nudged a few pixels off its neighbours.
46
+ - [soft] The screen has a small number of alignment lines (often a column grid). Draw them on the shot: an element that touches none of them needs a reason.
47
+ - [soft] Centred alignment is used for a single moment (an empty state, a hero line), not as the default for whole sections of left-reading content.
48
+ - [soft] Numbers in a column align on the right or on the decimal, so they compare.
49
+
50
+ ## 4. Spacing rhythm
51
+
52
+ **Principle:** space comes from a short scale, and bigger gaps mean bigger separations.
53
+
54
+ - [soft] Every gap on the screen comes from the spacing scale in `DESIGN.md`. Measure five gaps at random: all are on the scale.
55
+ - [soft] There are at most three or four distinct gap sizes in one view, and each has a job (inside a component, between items, between groups, between sections).
56
+ - [soft] Nothing touches the edge of its container. Text inside a box has padding at least as large as the gap between its lines.
57
+ - [soft] Dense views stay dense on purpose: a table or list keeps tight rows rather than inheriting marketing-page spacing.
58
+
59
+ ## 5. Typography
60
+
61
+ **Principle:** a few sizes, far apart, set for reading.
62
+
63
+ - [soft] The view uses at most five font sizes, and adjacent sizes are clearly different (roughly a 1.2× step or more), not 15, 16 and 17.
64
+ - [soft] Body text runs about 45 to 80 characters per line on desktop. Count one line.
65
+ - [soft] Body line height is visibly looser than heading line height. Headings of two lines do not drift apart.
66
+ - [soft] Weight does the work before size. A label is not set larger to be noticed when bold would do.
67
+ - [hard] No text is clipped, overlapped, or cut mid-word by its container, in any language the product ships.
68
+
69
+ ## 6. Colour
70
+
71
+ **Principle:** colour carries meaning, and the meaning stays the same everywhere.
72
+
73
+ - [hard] Body text has a contrast ratio of at least 4.5:1 against its background. Large text (24px, or 18.66px bold, and up) and the visible parts of controls and icons have at least 3:1.
74
+ - [hard] Colour is never the only signal. An error, a selected item or a required field also changes shape, weight, an icon or text.
75
+ - [soft] Every colour on the screen is a token in `DESIGN.md`. Pick three at random: each maps to a named token.
76
+ - [hard] A product with more than one theme has one set of colour tokens, with a value for each theme, and passes every check here in each theme. A colour that stays the same when the theme changes, and should not, fails.
77
+ - [soft] The accent colour marks action or state, and is not also used for decoration on the same screen.
78
+ - [soft] Status colours (error, warning, success) are used for status only.
79
+
80
+ ## 7. Consistency
81
+
82
+ **Principle:** the same thing looks and behaves the same everywhere.
83
+
84
+ - [hard] One action has one look. Two primary buttons on different screens are the same component, same size and same label case.
85
+ - [soft] Components come from the Figma library or the codebase's components. A one-off that looks like a library component, but is slightly different, fails.
86
+ - [soft] Icons share a style: one stroke weight or one fill style, one corner treatment, one optical size.
87
+ - [soft] The same word means the same thing. "Delete" and "Remove" are not both used for one action.
88
+
89
+ ## 8. States
90
+
91
+ **Principle:** every screen is shown in every state a person will meet.
92
+
93
+ - [hard] The screen has a frame for each of empty, loading and error that a person can reach, next to the default. A state nobody can reach is recorded as not needed, with the reason. A reachable state with no frame is a failure, not a later task.
94
+ - [hard] Empty says what goes here and gives the one action that fills it. Error says what went wrong in plain words and how to recover.
95
+ - [hard] Interactive components show hover (pointer surfaces), focus, pressed, disabled, and selected where they apply. Each state is visibly different from default.
96
+ - [soft] Loading keeps the layout's shape (skeleton or reserved space), so content does not jump when it arrives.
97
+ - [soft] Long content is shown: the longest real name, a big number, a two-line title. Short sample text hides overflow.
98
+
99
+ ## 9. Affordance and feedback
100
+
101
+ **Principle:** what can be acted on looks like it, and every action visibly answers.
102
+
103
+ - [hard] Every interactive element looks interactive without hovering. Text links are distinct from body text by more than colour alone, unless their position makes them obvious (a nav bar).
104
+ - [hard] Nothing that looks interactive is not. A card that looks clickable is clickable, or loses the look.
105
+ - [soft] Each action has a visible result frame: a saved state, a toast, the item appearing in the list, a progress indicator for anything over a second.
106
+ - [soft] Destructive actions look different from safe ones and are never the default or most prominent option.
107
+
108
+ ## 10. Accessibility
109
+
110
+ **Principle:** the screen works for people who see, move and read differently.
111
+
112
+ - [hard] The focused state of every interactive element shows a visible indicator with at least 3:1 contrast against what is around it. Check it in the focus frame.
113
+ - [hard] Targets are at least 24×24 CSS pixels, or have that much space around them (WCAG 2.2 AA). The app list raises this for touch.
114
+ - [hard] Every input has a visible label. A placeholder alone is not a label.
115
+ - [hard] Text is real text, not text in an image, except in logos.
116
+ - [soft] The screen still reads at 200% text size: nothing important is cut off in the zoomed frame.
117
+
118
+ ## 11. Copy
119
+
120
+ **Principle:** words do the job of the screen in the product's own voice.
121
+
122
+ - [hard] No placeholder copy: no lorem ipsum, no "Title", no "Button", no "User Name".
123
+ - [soft] Buttons say what happens: "Send invoice", not "Submit", "OK", "Get started" or "Learn more".
124
+ - [soft] Headings are short. A heading that runs over two lines at its size is a sentence that belongs in the body.
125
+ - [soft] The voice matches `DESIGN.md`. Read three strings aloud: they sound like one product.
126
+ - [soft] No genre filler: unlock, supercharge, seamless, elevate, effortless, all-in-one, and "not just X, it's Y".
127
+
128
+ ## 12. Imagery
129
+
130
+ **Principle:** pictures show the real thing, or there are none.
131
+
132
+ - [soft] Images show this product's subject, people or interface. A stock scene that fits any product in the category fails.
133
+ - [soft] Where a picture belongs, there is a picture, not a grey box, a gradient or a text block pretending.
134
+ - [soft] Images share one treatment: one crop logic, one colour handling, one corner shape.
135
+ - [hard] Text over an image meets the contrast floor in rule 6 across the whole text area, not only on the darkest part.
136
+
137
+ ## 13. Responsive
138
+
139
+ **Principle:** each size is designed, not squeezed.
140
+
141
+ - [hard] At mobile width (360–390px) nothing scrolls sideways, nothing is clipped, and nothing overlaps.
142
+ - [hard] The primary action is reachable at every size without hunting: visible, or one obvious step away.
143
+ - [soft] The layout changes structure between sizes where it should: columns stack, tables become lists or scroll inside their own box, navigation collapses into one control.
144
+ - [soft] Type and spacing scale down a step on mobile, not to illegible sizes. Body text stays at least 16px.
145
+
146
+ ## 14. Tells
147
+
148
+ **Dated 2026-11-03. Reviewed each release.** Add new tells, retire ones that stopped being defaults.
149
+
150
+ A tell is a device that makes a screen look produced by default rather than designed for this product. Most began as good ideas. They are tells because they arrive without a reason. Every check here is **soft**: present, and `DESIGN.md` gives no reason for it. This list never says what to use instead. That comes from the direction.
151
+
152
+ - [soft] Purple-to-blue gradients on backgrounds, buttons, glows or headline text.
153
+ - [soft] Translucent blurred panels used on two or more surfaces.
154
+ - [soft] The same soft grey shadow under every card.
155
+ - [soft] A row of three identical feature cards, each an icon in a rounded square, a heading and two lines.
156
+ - [soft] Emoji used as icons or bullets.
157
+ - [soft] A tiny tracked uppercase label above every heading, or a pill badge ("New", "Beta") above the hero line.
158
+ - [soft] One word of a headline singled out in another face, colour or underline.
159
+ - [soft] A cream ground with a terracotta or rust accent, used as a shortcut to "warm".
160
+ - [soft] Decorative monospace labels, index numbering (01 / 02 / 03) as ornament, hairline rules boxing everything, or design-tool marks (crosshairs, crop marks) as decoration.
161
+ - [soft] A fake dashboard made of grey bars and donut charts where a real interface fragment should be.
162
+ - [soft] Invented social proof: logos, quotes, star rows or user counts the product does not have.
163
+ - [soft] Every section in the same layout, or the stock order hero, logos, features, testimonial, pricing, call to action, when the argument needs another.
164
+ - [soft] One medium corner radius on everything, chosen by default rather than on purpose.
165
+
166
+ Removing tells is not the goal. A screen with none and no idea fails rule 0.
167
+
168
+ ## Sites
169
+
170
+ Add these when the brief's surface is a site: the page a person lands on to understand or choose.
171
+
172
+ - [hard] The first screen at mobile and desktop says what this is and who it is for, without scrolling.
173
+ - [soft] Sections follow the order of the argument the brief makes, and each section is composed differently from the one before.
174
+ - [soft] There is one primary call to action, repeated at most at the end, with the same label.
175
+ - [soft] Proof is real (product shots, named customers the product has, numbers it can stand behind) or absent.
176
+
177
+ ## Apps
178
+
179
+ Add these when the brief's surface is an app: the tool a person comes back to.
180
+
181
+ - [hard] Touch targets on touch platforms are at least 44×44 pt (Apple) or 48×48 dp (Material), whichever platform it ships on. The web floor in rule 10 still applies.
182
+ - [hard] The person always knows where they are: the current place in navigation is marked, and the screen title matches the nav item.
183
+ - [soft] Density fits repeated use. Lists and tables show enough rows to work, not marketing-sized cards.
184
+ - [soft] Navigation keeps the same place and shape on every screen of the flow.
185
+ - [soft] Frequent actions are one step away. Rare and destructive ones may be further.
186
+
187
+ ## Sources
188
+
189
+ Ideas drawn from, in our own words: Gestalt principles of grouping; WCAG 2.2 (contrast 1.4.3 and 1.4.11, focus visible 2.4.7, target size 2.5.8, labels 3.3.2); Refactoring UI practice (Adam Wathan and Steve Schoger); Apple Human Interface Guidelines and Material Design basics (touch targets, navigation, states); and the tells registry of taste-skill by Leonxlnx (MIT).
@@ -0,0 +1,489 @@
1
+ #!/usr/bin/env node
2
+ // Full-page capture. Unsticks fixed/sticky chrome first so Chrome does not
3
+ // repeat the same fold. Node 22+. Uses an installed Chrome/Edge/Chromium.
4
+ //
5
+ // node capture.mjs <url> --out design-exploration/<slug>/refs/name.jpg
6
+ // node capture.mjs <url> --out design-exploration/<slug>/refs/name.jpg --review /tmp/name-review.jpg
7
+ // node capture.mjs <url> --out design-exploration/<slug>/refs/name.jpg --clip x,y,w,h
8
+ // node capture.mjs <url> --out design-exploration/<slug>/refs/name.jpg --clip-selector "main"
9
+ // node capture.mjs <url> --out /tmp/mobile.png --width 390
10
+ // node capture.mjs http://localhost:3000/app --out /tmp/app.png --cookie "session=abc; theme=dark" --strict
11
+ //
12
+ // A page that ends up at another address (a login, or a site's canonical
13
+ // www) is named on stderr. With --strict that is exit 1, so a 0 means the
14
+ // shot is of the page asked for.
15
+ // node capture.mjs file:///abs/path/moodboard.html --out /tmp/moodboard.jpg
16
+ // node capture.mjs file:///abs/path/shot.jpg --out design-exploration/<slug>/refs/name.jpg --clip x,y,w,h
17
+ import { spawn, execSync } from "node:child_process";
18
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { dirname, isAbsolute, join, resolve } from "node:path";
21
+
22
+ const args = process.argv.slice(2);
23
+ const flag = (name, def) => {
24
+ const i = args.indexOf(`--${name}`);
25
+ if (i === -1) return def;
26
+ const v = args[i + 1];
27
+ args.splice(i, 2);
28
+ return v;
29
+ };
30
+ const url = args[0];
31
+ const outArg = flag("out", "") || "";
32
+ const reviewArg = flag("review", "") || "";
33
+ const clipArg = flag("clip", "") || "";
34
+ const clipSelector = flag("clip-selector", "") || "";
35
+ // Sent with every request to the page's own origin, as a logged-in browser would.
36
+ const cookieArg = flag("cookie", "") || "";
37
+ const strictAt = args.indexOf("--strict");
38
+ const strict = strictAt !== -1;
39
+ if (strict) args.splice(strictAt, 1);
40
+ // Below 768 the page gets a phone viewport: mobile layout, 2x pixels.
41
+ const width = Math.round(Number(flag("width", "1440")));
42
+ if (!url || !/^(https?|file):\/\//.test(url) || !outArg) {
43
+ console.error(
44
+ 'usage: node capture.mjs <https://url | file:///path> --out design-exploration/<slug>/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h | --clip-selector "css"] [--width 390] [--cookie "name=value; …"] [--strict]',
45
+ );
46
+ process.exit(2);
47
+ }
48
+ if (!Number.isFinite(width) || width < 200 || width > 3840) {
49
+ console.error("width must be a number from 200 to 3840");
50
+ process.exit(2);
51
+ }
52
+ const mobile = width < 768;
53
+ const height = mobile ? 844 : 900;
54
+ if (clipArg && clipSelector) {
55
+ console.error("pass --clip or --clip-selector, not both");
56
+ process.exit(2);
57
+ }
58
+
59
+ function projectRoot() {
60
+ try {
61
+ return execSync("git rev-parse --show-toplevel", { encoding: "utf8" }).trim();
62
+ } catch {
63
+ return process.cwd();
64
+ }
65
+ }
66
+
67
+ function resolveOut(path) {
68
+ if (!path) return "";
69
+ if (isAbsolute(path)) return path;
70
+ return resolve(projectRoot(), path);
71
+ }
72
+
73
+ const out = resolveOut(outArg);
74
+ const reviewOut = resolveOut(reviewArg);
75
+
76
+ function parseClip(s) {
77
+ if (!s) return null;
78
+ const parts = s.split(",").map((n) => Number(n.trim()));
79
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
80
+ console.error("clip must be x,y,w,h (non-negative numbers)");
81
+ process.exit(2);
82
+ }
83
+ const [x, y, w, h] = parts;
84
+ if (w < 1 || h < 1) {
85
+ console.error("clip width and height must be >= 1");
86
+ process.exit(2);
87
+ }
88
+ return { x, y, width: w, height: h, scale: 1 };
89
+ }
90
+
91
+ const clip = parseClip(clipArg);
92
+
93
+ function findChrome() {
94
+ const env = process.env.CHROME_PATH;
95
+ if (env && existsSync(env)) return env;
96
+ const home = process.env.HOME || process.env.USERPROFILE || "";
97
+ const local = process.env.LOCALAPPDATA || "";
98
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
99
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
100
+ const candidates = [
101
+ join(pf, "Google/Chrome/Application/chrome.exe"),
102
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
103
+ join(local, "Google/Chrome/Application/chrome.exe"),
104
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
105
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
106
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
107
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
108
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
109
+ "/usr/bin/google-chrome",
110
+ "/usr/bin/google-chrome-stable",
111
+ "/usr/bin/chromium",
112
+ "/usr/bin/chromium-browser",
113
+ ];
114
+ return candidates.find((path) => path && existsSync(path)) || null;
115
+ }
116
+
117
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
118
+
119
+ const exe = findChrome();
120
+ if (!exe) {
121
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
122
+ process.exit(1);
123
+ }
124
+ if (typeof WebSocket === "undefined") {
125
+ console.error("Node 22+ is required.");
126
+ process.exit(1);
127
+ }
128
+
129
+ const dir = mkdtempSync(join(tmpdir(), "hunt-chrome-"));
130
+ let proc;
131
+ const drop = () => {
132
+ try {
133
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
134
+ } catch {}
135
+ try {
136
+ rmSync(dir, { recursive: true, force: true });
137
+ } catch {}
138
+ };
139
+ process.once("exit", drop);
140
+
141
+ proc = spawn(
142
+ exe,
143
+ [
144
+ "--headless=new",
145
+ "--remote-debugging-port=0",
146
+ `--user-data-dir=${dir}`,
147
+ "--no-first-run",
148
+ "--hide-scrollbars",
149
+ "--mute-audio",
150
+ "--force-color-profile=srgb",
151
+ `--window-size=${width},${height}`,
152
+ "about:blank",
153
+ ],
154
+ { stdio: ["ignore", "ignore", "pipe"] },
155
+ );
156
+
157
+ let buf = "";
158
+ const wsUrl = await new Promise((resolveWs, reject) => {
159
+ const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
160
+ proc.stderr.on("data", (d) => {
161
+ buf += d.toString();
162
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
163
+ if (m) {
164
+ clearTimeout(t);
165
+ resolveWs(m[1]);
166
+ }
167
+ });
168
+ proc.on("exit", (code) => {
169
+ clearTimeout(t);
170
+ reject(new Error(`Chrome exited ${code}`));
171
+ });
172
+ });
173
+
174
+ const ws = new WebSocket(wsUrl);
175
+ await new Promise((res, rej) => {
176
+ ws.onopen = res;
177
+ ws.onerror = () => rej(new Error("CDP socket failed"));
178
+ });
179
+ let nextId = 1;
180
+ const pending = new Map();
181
+ ws.onmessage = (ev) => {
182
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
183
+ if (msg.id && pending.has(msg.id)) {
184
+ const { resolve: ok, reject: bad } = pending.get(msg.id);
185
+ pending.delete(msg.id);
186
+ if (msg.error) bad(new Error(msg.error.message));
187
+ else ok(msg.result);
188
+ }
189
+ };
190
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
191
+ const id = nextId++;
192
+ return new Promise((resolveSend, reject) => {
193
+ const timer = setTimeout(() => {
194
+ pending.delete(id);
195
+ reject(new Error(`CDP timeout: ${method}`));
196
+ }, timeoutMs);
197
+ pending.set(id, {
198
+ resolve: (v) => {
199
+ clearTimeout(timer);
200
+ resolveSend(v);
201
+ },
202
+ reject: (e) => {
203
+ clearTimeout(timer);
204
+ reject(e);
205
+ },
206
+ });
207
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
208
+ });
209
+ };
210
+
211
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
212
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
213
+ const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
214
+
215
+ await page("Page.enable");
216
+ await page("Runtime.enable");
217
+ await page("Emulation.setDeviceMetricsOverride", {
218
+ width,
219
+ height,
220
+ deviceScaleFactor: mobile ? 2 : 1,
221
+ mobile,
222
+ });
223
+ // Chrome centres an image file and shrinks it to the window. A page that holds
224
+ // it at full size from 0,0 makes --clip x,y,w,h the image's own pixels.
225
+ let target = url;
226
+ if (/^file:\/\/.*\.(png|jpe?g|webp|gif)$/i.test(url)) {
227
+ target = `file://${join(dir, "image.html")}`;
228
+ writeFileSync(join(dir, "image.html"), `<!doctype html><body style="margin:0;background:#000"><img src="${url.replace(/"/g, "%22")}" style="display:block">`);
229
+ }
230
+ if (cookieArg && /^https?:/.test(url)) {
231
+ const cookies = cookieArg
232
+ .split(";")
233
+ .map((pair) => pair.trim())
234
+ .filter(Boolean)
235
+ .map((pair) => {
236
+ const at = pair.indexOf("=");
237
+ return { name: pair.slice(0, at), value: pair.slice(at + 1), url: new URL(url).origin };
238
+ });
239
+ if (cookies.some((cookie) => !cookie.name)) {
240
+ console.error('cookie must be "name=value; name=value"');
241
+ drop();
242
+ process.exit(2);
243
+ }
244
+ await page("Network.setCookies", { cookies });
245
+ }
246
+ await page("Page.navigate", { url: target }, 40000);
247
+ await sleep(2500);
248
+
249
+ const beforeHref = (
250
+ await page("Runtime.evaluate", {
251
+ expression: "location.href",
252
+ returnByValue: true,
253
+ })
254
+ ).result.value;
255
+
256
+ await page("Runtime.evaluate", {
257
+ expression: `(() => {
258
+ const labels = /^(accept( all)?( cookies)?|agree|ok|okay|got it|allow( all)?|i understand|acepto|aceptar)$/i;
259
+ const clickable = document.querySelectorAll("button, [role=button]");
260
+ for (const el of clickable) {
261
+ const t = (el.innerText || el.textContent || "").trim().replace(/\\s+/g, " ");
262
+ if (t.length < 40 && labels.test(t)) { el.click(); break; }
263
+ }
264
+ // Strip short privacy/cookie dialogs (e.g. Google Fonts "×" banner).
265
+ const privacy = /uses cookies|privacy and google fonts|cookie settings/i;
266
+ for (const el of [...document.querySelectorAll("div, section, aside, dialog")]) {
267
+ const t = (el.innerText || el.textContent || "").trim();
268
+ if (t.length > 0 && t.length < 300 && privacy.test(t) && el.children.length < 12) {
269
+ el.remove();
270
+ }
271
+ }
272
+ })()`,
273
+ awaitPromise: true,
274
+ returnByValue: true,
275
+ });
276
+ await sleep(800);
277
+
278
+ const afterHref = (
279
+ await page("Runtime.evaluate", {
280
+ expression: "location.href",
281
+ returnByValue: true,
282
+ })
283
+ ).result.value;
284
+
285
+ if (afterHref !== beforeHref) {
286
+ console.error(`navigated away: ${afterHref}`);
287
+ drop();
288
+ process.exit(1);
289
+ }
290
+
291
+ await page(
292
+ "Runtime.evaluate",
293
+ {
294
+ expression: `(() => new Promise((done) => {
295
+ (async () => {
296
+ for (const img of document.images) {
297
+ if (img.loading === "lazy") img.loading = "eager";
298
+ }
299
+ const dwell = (ms) => new Promise((r) => setTimeout(r, ms));
300
+ const step = Math.max(480, Math.round(window.innerHeight * 0.65));
301
+ const limit = Math.min(
302
+ Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0),
303
+ 14000
304
+ );
305
+ let y = 0;
306
+ while (y < limit) {
307
+ y = Math.min(limit, y + step);
308
+ window.scrollTo(0, y);
309
+ await dwell(600);
310
+ }
311
+ await Promise.race([
312
+ Promise.all([...document.images].map((img) => img.decode().catch(() => {}))),
313
+ dwell(8000),
314
+ ]);
315
+ window.scrollTo(0, 0);
316
+ await dwell(700);
317
+ done();
318
+ })().catch(() => done());
319
+ }))()`,
320
+ awaitPromise: true,
321
+ returnByValue: true,
322
+ },
323
+ 90000,
324
+ );
325
+
326
+ await page("Runtime.evaluate", {
327
+ expression: `(() => {
328
+ const style = document.createElement("style");
329
+ style.textContent = \`
330
+ html, body { height: auto !important; max-height: none !important; overflow: visible !important; }
331
+ * { animation-play-state: paused !important; transition: none !important; scroll-behavior: auto !important; }
332
+ \`;
333
+ document.head.appendChild(style);
334
+ for (const el of document.querySelectorAll("*")) {
335
+ const pos = getComputedStyle(el).position;
336
+ if (pos === "fixed" || pos === "sticky") {
337
+ el.style.setProperty("position", "relative", "important");
338
+ el.style.setProperty("top", "auto", "important");
339
+ el.style.setProperty("bottom", "auto", "important");
340
+ }
341
+ }
342
+ })()`,
343
+ awaitPromise: true,
344
+ returnByValue: true,
345
+ });
346
+ await sleep(400);
347
+
348
+ // A redirect can land late (an app checks the session after it loads), so
349
+ // the address is checked last, right before the shot.
350
+ if (target === url) {
351
+ const landed = (await page("Runtime.evaluate", { expression: "location.href", returnByValue: true })).result.value;
352
+ const where = (href) => {
353
+ const u = new URL(href);
354
+ return `${u.origin}${u.pathname.replace(/\/$/, "")}`;
355
+ };
356
+ if (where(landed) !== where(url)) {
357
+ console.error(`landed on ${landed}, not ${url}.${/^https?:/.test(landed) ? " Behind a login? Pass --cookie." : " Check the address."}`);
358
+ if (strict) {
359
+ drop();
360
+ process.exit(1);
361
+ }
362
+ }
363
+ }
364
+
365
+ // --clip-selector takes the element's box in document coordinates, measured
366
+ // after the unstick pass so the numbers match what the capture sees.
367
+ let selected = null;
368
+ if (clipSelector) {
369
+ const { result } = await page("Runtime.evaluate", {
370
+ expression: `(() => {
371
+ const el = document.querySelector(${JSON.stringify(clipSelector)});
372
+ if (!el) return null;
373
+ const r = el.getBoundingClientRect();
374
+ return {
375
+ x: Math.max(0, Math.round(r.left + window.scrollX)),
376
+ y: Math.max(0, Math.round(r.top + window.scrollY)),
377
+ width: Math.round(r.width),
378
+ height: Math.round(r.height),
379
+ };
380
+ })()`,
381
+ returnByValue: true,
382
+ });
383
+ selected = result?.value || null;
384
+ if (!selected) {
385
+ console.error(`no element matches ${clipSelector}`);
386
+ drop();
387
+ process.exit(1);
388
+ }
389
+ if (selected.width < 1 || selected.height < 1) {
390
+ console.error(`${clipSelector} has no box (width ${selected.width}, height ${selected.height})`);
391
+ drop();
392
+ process.exit(1);
393
+ }
394
+ }
395
+
396
+ const metrics = await page("Page.getLayoutMetrics");
397
+ const size = metrics.cssContentSize || metrics.contentSize;
398
+ const fullWidth = Math.max(1, Math.ceil(size.width || width));
399
+ const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || height), 14000));
400
+ const clipBox = clip || (selected ? { ...selected, scale: 1 } : null);
401
+ const shotClip = clipBox
402
+ ? {
403
+ x: Math.min(clipBox.x, fullWidth - 1),
404
+ y: Math.min(clipBox.y, fullHeight - 1),
405
+ width: Math.min(clipBox.width, fullWidth - Math.min(clipBox.x, fullWidth - 1)),
406
+ height: Math.min(clipBox.height, fullHeight - Math.min(clipBox.y, fullHeight - 1)),
407
+ scale: 1,
408
+ }
409
+ : { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
410
+
411
+ // The file is what its name says, so a reader that trusts the extension is right.
412
+ const format = /\.png$/i.test(out) ? "png" : /\.webp$/i.test(out) ? "webp" : "jpeg";
413
+ const { data } = await page(
414
+ "Page.captureScreenshot",
415
+ {
416
+ format,
417
+ ...(format === "png" ? {} : { quality: 70 }),
418
+ captureBeyondViewport: true,
419
+ clip: shotClip,
420
+ },
421
+ 60000,
422
+ );
423
+
424
+ mkdirSync(dirname(out), { recursive: true });
425
+ writeFileSync(out, Buffer.from(data, "base64"));
426
+ console.log(out);
427
+
428
+ if (reviewOut) {
429
+ // Side-by-side columns ~2800 px tall so a tall capture stays readable.
430
+ // Real capture stays the single tall file; review is scratch only.
431
+ const reviewHtml = `<!doctype html><meta charset=utf-8>
432
+ <canvas id=c></canvas>
433
+ <script>
434
+ const src = "data:image/${format};base64,${data}";
435
+ const img = new Image();
436
+ img.onload = () => {
437
+ const colH = 2800;
438
+ const gap = 20;
439
+ const cols = Math.max(1, Math.ceil(img.height / colH));
440
+ const c = document.getElementById("c");
441
+ c.width = cols * img.width + (cols - 1) * gap;
442
+ c.height = Math.min(colH, img.height);
443
+ const ctx = c.getContext("2d");
444
+ ctx.fillStyle = "#111";
445
+ ctx.fillRect(0, 0, c.width, c.height);
446
+ for (let i = 0; i < cols; i++) {
447
+ const sy = i * colH;
448
+ const sh = Math.min(colH, img.height - sy);
449
+ ctx.drawImage(img, 0, sy, img.width, sh, i * (img.width + gap), 0, img.width, sh);
450
+ }
451
+ document.title = "ready";
452
+ };
453
+ img.src = src;
454
+ </script>`;
455
+ const reviewPage = join(dir, "review.html");
456
+ writeFileSync(reviewPage, reviewHtml);
457
+ await page("Page.navigate", { url: `file://${reviewPage}` }, 20000);
458
+ await sleep(400);
459
+ for (let i = 0; i < 40; i++) {
460
+ const title = (
461
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
462
+ ).result.value;
463
+ if (title === "ready") break;
464
+ await sleep(100);
465
+ }
466
+ const { result: sizeResult } = await page("Runtime.evaluate", {
467
+ expression: `(() => {
468
+ const c = document.getElementById("c");
469
+ return { w: c.width, h: c.height };
470
+ })()`,
471
+ returnByValue: true,
472
+ });
473
+ const { data: reviewData } = await page(
474
+ "Page.captureScreenshot",
475
+ {
476
+ format: /\.png$/i.test(reviewOut) ? "png" : "jpeg",
477
+ quality: 75,
478
+ clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
479
+ captureBeyondViewport: true,
480
+ },
481
+ 60000,
482
+ );
483
+ mkdirSync(dirname(reviewOut), { recursive: true });
484
+ writeFileSync(reviewOut, Buffer.from(reviewData, "base64"));
485
+ console.log(reviewOut);
486
+ }
487
+
488
+ drop();
489
+ process.exit(0);