trykeyline-browser 0.0.0-stage → 0.3.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,301 @@
1
+ /**
2
+ * Render a run (findings.json) as one HTML page beside it: index.html, with
3
+ * the shots folder next to it. No dependencies and no network: the page opens
4
+ * from disk, prints, and can be published as-is.
5
+ *
6
+ * Each finding shows a crop of the screenshot it was seen in with the element
7
+ * outlined. The crop is CSS: the shot is a background image sized and offset
8
+ * so only the region around the box shows, which keeps the report folder to
9
+ * one PNG per page however many findings point into it.
10
+ */
11
+ import { writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { counts, readRun, sortFindings } from "./findings.mjs";
14
+ import { SHIP, scoreCaps } from "./score.mjs";
15
+
16
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
17
+
18
+ const DOMAIN_NAMES = {
19
+ type: "Type",
20
+ color: "Colour",
21
+ layout: "Layout",
22
+ depth: "Depth",
23
+ motion: "Motion",
24
+ patterns: "Patterns",
25
+ a11y: "Accessibility",
26
+ copy: "Copy",
27
+ states: "States",
28
+ slop: "AI slop",
29
+ flow: "Flows",
30
+ runtime: "Runtime",
31
+ visual: "Visual change",
32
+ };
33
+ const CHANGE_WORDS = { new: "New", returned: "Back", still: "Still" };
34
+ const KIND_TITLES = { audit: "Audit", smoke: "Smoke test", capture: "Capture", check: "Detector" };
35
+ const SCORE_WORDS = ["Broken", "Weak", "Mixed", "Good", "Excellent"];
36
+ const PAD = 72;
37
+
38
+ /** The crop around a box, clamped to the shot. All numbers in shot pixels. */
39
+ function crop(box, shot) {
40
+ // Wide enough that the report's 832px column doesn't enlarge it much, tall enough to show context.
41
+ const w = Math.min(shot.width, Math.max(box.w + PAD * 2, 880));
42
+ const h = Math.min(shot.height, Math.max(box.h + PAD * 2, Math.round(w * 0.4)));
43
+ const x = Math.max(0, Math.min(box.x + box.w / 2 - w / 2, shot.width - w));
44
+ const y = Math.max(0, Math.min(box.y + box.h / 2 - h / 2, shot.height - h));
45
+ return { x, y, w, h };
46
+ }
47
+
48
+ function figure(f, page) {
49
+ const shot = f.shot && page?.shots?.[f.shot];
50
+ if (!shot) return "";
51
+ // An element outside the shot (scrolled away in a strip) can't be outlined; show the page instead.
52
+ if (!f.box || f.box.x >= shot.width || f.box.x + f.box.w <= 0 || f.box.y >= shot.height) {
53
+ return `<a class="shot shot--whole" href="${esc(shot.path)}" target="_blank" rel="noopener"><img src="${esc(shot.path)}" alt="" loading="lazy"></a>`;
54
+ }
55
+ const c = crop(f.box, shot);
56
+ const pct = (n, d) => ((n / d) * 100).toFixed(3) + "%";
57
+ const bgSize = `${pct(shot.width, c.w)} auto`;
58
+ const bgPos = `${c.w >= shot.width ? "0%" : pct(c.x, shot.width - c.w)} ${c.h >= shot.height ? "0%" : pct(c.y, shot.height - c.h)}`;
59
+ const mark = `left:${pct(f.box.x - c.x, c.w)};top:${pct(f.box.y - c.y, c.h)};width:${pct(f.box.w, c.w)};height:${pct(f.box.h, c.h)}`;
60
+ // Never wider than 1.25× the pixels it has, so a phone crop stays sharp.
61
+ return `<a class="shot" href="${esc(shot.path)}" target="_blank" rel="noopener" style="max-width:${Math.round(c.w * 1.25)}px;aspect-ratio:${c.w}/${c.h};background-image:url('${esc(shot.path)}');background-size:${bgSize};background-position:${bgPos}" aria-label="Open the full screenshot"><span class="shot__mark" style="${mark}"></span></a>`;
62
+ }
63
+
64
+ /** A change can span the whole page; the crop shows where it starts, and the full shot and diff are a click away. */
65
+ const VISUAL_CROP = 560;
66
+ const firstPart = (box) => (box && box.h > VISUAL_CROP ? { ...box, h: VISUAL_CROP } : box);
67
+
68
+ /** A visual change shows the diff under the crop: the same region, changed pixels in red. */
69
+ function diffFigure(f) {
70
+ if (!f.diff?.path) return "";
71
+ const box = firstPart(f.diff.box ?? f.box);
72
+ const shown = figure({ ...f, shot: "diff", box }, { shots: { diff: { path: f.diff.path, width: f.diff.width, height: f.diff.height } } });
73
+ return `<p class="f__caption">The diff: red is what changed.</p>${shown}`;
74
+ }
75
+
76
+ function card(f, page) {
77
+ const where = [f.page, f.viewport, f.theme].filter(Boolean).join(" · ");
78
+ const source = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
79
+ const change = f.rule?.startsWith("visual/") ? "changed" : f.change;
80
+ const badge = change === "changed" ? `<span class="chg chg--changed">Changed</span>` : CHANGE_WORDS[change] ? `<span class="chg chg--${esc(change)}">${CHANGE_WORDS[change]}</span>` : "";
81
+ return `<article class="f" data-severity="${esc(f.severity)}" data-domain="${esc(f.domain)}" data-page="${esc(f.page ?? "")}" data-status="${esc(f.status ?? "open")}" data-change="${esc(change ?? "")}" id="${esc(f.id)}">
82
+ <header class="f__head">
83
+ <span class="sev sev--${esc(f.severity)}">${esc(f.severity)}</span>${badge}
84
+ <h3 class="f__title">${esc(f.title)}</h3>
85
+ </header>
86
+ <p class="f__meta"><span>${esc(DOMAIN_NAMES[f.domain] ?? f.domain)}</span><code>${esc(f.rule)}</code>${f.law ? `<span>${esc(f.law)}</span>` : ""}${where ? `<span>${esc(where)}</span>` : ""}</p>
87
+ ${f.detail ? `<p class="f__detail">${esc(f.detail)}</p>` : ""}
88
+ ${f.evidence ? `<p class="f__evidence"><span>Measured</span> ${esc(f.evidence)}</p>` : ""}
89
+ ${f.steps?.length ? `<ol class="f__steps">${f.steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ol>` : ""}
90
+ ${figure(f.diff ? { ...f, box: firstPart(f.box) } : f, page)}
91
+ ${diffFigure(f)}
92
+ <dl class="f__facts">
93
+ ${f.selector ? `<div><dt>Element</dt><dd><code>${esc(f.selector)}</code></dd></div>` : ""}
94
+ ${source ? `<div><dt>Source</dt><dd><code>${esc(source)}</code></dd></div>` : ""}
95
+ ${f.fix ? `<div><dt>Fix with</dt><dd><code>${esc(f.fix)}</code></dd></div>` : ""}
96
+ </dl>
97
+ </article>`;
98
+ }
99
+
100
+ /** What a score out of 10 means, in the words the audit's anchors use (commands/audit.md). */
101
+ export function scoreWord(n) {
102
+ if (n >= 9) return "Excellent";
103
+ if (n >= SHIP) return "Ready to ship";
104
+ if (n >= 7) return "Close to the bar";
105
+ if (n >= 5) return "Works, but a reader feels the faults";
106
+ if (n >= 3) return "Broken for someone";
107
+ return "Broken";
108
+ }
109
+
110
+ const fmt = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
111
+
112
+ /** The headline: the score out of 10, how it got here, and what holds it down. */
113
+ function headline(run) {
114
+ if (typeof run.score !== "number") return "";
115
+ const caps = scoreCaps(run.scores, run.findings);
116
+ const cap = caps.length ? caps[0].max : 10;
117
+ const trail = [...(run.history ?? []), run.score].map(fmt).join(" → ");
118
+ const over = run.score > cap ? `<p class="headline__warn">Settled above what the evidence allows: at most ${fmt(cap)} while ${esc(caps[0].why)}.</p>` : "";
119
+ const held = caps.length ? `<ul class="headline__caps">${caps.map((c) => `<li>At most ${fmt(c.max)}: ${esc(c.why)}</li>`).join("")}</ul>` : "";
120
+ return `<section class="block headline"><h2>Score${run.scoresDraft ? ` <small class="draft">drafted from the measurements; not yet reviewed</small>` : ""}</h2>
121
+ <p class="headline__score"><b>${esc(fmt(run.score))}</b><span>/10</span></p>
122
+ <p class="headline__word">${esc(scoreWord(run.score))} · the bar is ${SHIP}${run.history?.length ? ` · <span class="headline__trail">rounds ${esc(trail)}</span>` : ""}</p>
123
+ ${over}${held}</section>`;
124
+ }
125
+
126
+ function scoreTable(scores, draft, title = "Scores") {
127
+ if (!scores) return "";
128
+ const rows = Object.entries(scores)
129
+ .map(([d, s]) => `<tr><th scope="row">${esc(DOMAIN_NAMES[d] ?? d)}</th><td><span class="meter" style="--v:${Number(s) / 4}"></span></td><td>${esc(s)}/4</td><td>${esc(SCORE_WORDS[s] ?? "")}</td></tr>`)
130
+ .join("");
131
+ return `<section class="block"><h2>${esc(title)}${draft ? ` <small class="draft">drafted from the measurements; not yet reviewed</small>` : ""}</h2><table class="scores"><tbody>${rows}</tbody></table></section>`;
132
+ }
133
+
134
+ function sinceSection(run) {
135
+ const c = run.compare;
136
+ if (!c) return "";
137
+ const when = c.previous?.finished ? new Date(c.previous.finished).toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" }) : "an earlier run";
138
+ const v = c.visual;
139
+ const total = (n, label) => `<li><b>${n}</b><span>${label}</span></li>`;
140
+ const fixed = run.fixed ?? [];
141
+ const fixedList = fixed.length
142
+ ? `<h3>Fixed</h3><ul class="since__list">${fixed
143
+ .map((f) => `<li><span class="sev sev--${esc(f.severity)}">${esc(f.severity)}</span> ${esc(f.title)} <span class="since__where"><code>${esc(f.rule)}</code> ${esc([f.page, f.viewport, f.theme].filter(Boolean).join(" · "))}</span></li>`)
144
+ .join("")}</ul>`
145
+ : "";
146
+ const diffs = run.pages.flatMap((p) => Object.entries(p.diffs ?? {}).map(([key, d]) => ({ route: p.route, key, ...d })));
147
+ diffs.sort((a, b) => b.percent - a.percent);
148
+ const diffRows = diffs.length
149
+ ? `<h3>Screenshots</h3><table class="since__diffs"><tbody>${diffs
150
+ .map((d) => `<tr${d.percent > (v?.threshold ?? 0) ? "" : ` class="same"`}><th scope="row">${esc(d.route)}</th><td>${esc(d.key.replace("-", " · "))}</td><td>${d.percent > (v?.threshold ?? 0) ? `${esc(d.percent)}% changed` : d.percent > 0 ? `${esc(d.percent)}%, under the threshold` : "unchanged"}</td><td><a href="${esc(d.path)}" target="_blank" rel="noopener">diff</a></td></tr>`)
151
+ .join("")}</tbody></table>`
152
+ : v?.skipped
153
+ ? `<p class="since__note">Screenshots weren't diffed: ${esc(v.skipped)}</p>`
154
+ : "";
155
+ return `<section class="block since"><h2>Since last run</h2>
156
+ <p class="lede">Against <code>${esc(c.against ?? "the previous report")}</code>, ${esc(when)}.</p>
157
+ <ul class="totals">${total(c.new, "New")}${total(c.returned, "Back again")}${total(c.still, "Still open")}${total(c.fixed, "Fixed")}${v ? total(v.changed, v.changed === 1 ? "Page changed" : "Pages changed") : ""}</ul>
158
+ ${fixedList}${diffRows}</section>`;
159
+ }
160
+
161
+ const STYLE = `
162
+ :root{color-scheme:light dark;--bg:#fff;--fg:#171717;--muted:#5e5e5e;--faint:#737373;--line:rgba(0,0,0,.09);--chip:#f2f2f2;--err:#b42318;--err-bg:#fdecea;--warn:#8a5a00;--warn-bg:#fff4dc;--info:#1d4ed8;--info-bg:#e8efff;--mark:#c4321f}
163
+ @media (prefers-color-scheme:dark){:root{--bg:#0b0b0b;--fg:#ededed;--muted:#a0a0a0;--faint:#8f8f8f;--line:rgba(255,255,255,.1);--chip:#1a1a1a;--err:#ff8a80;--err-bg:#3a1512;--warn:#f5c26b;--warn-bg:#33270d;--info:#93b4ff;--info-bg:#152040;--mark:#ff6b57}}
164
+ *{box-sizing:border-box}
165
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,"Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased}
166
+ code{font:13px/1.4 ui-monospace,"SF Mono",Menlo,monospace}
167
+ .wrap{max-width:880px;margin:0 auto;padding:64px 24px 96px}
168
+ h1{margin:0;font-size:28px;font-weight:500;letter-spacing:-.02em;line-height:1.2}
169
+ h2{margin:0 0 12px;font-size:16px;font-weight:500;letter-spacing:-.015em}
170
+ .lede{margin:8px 0 0;color:var(--muted)}
171
+ .summary{margin:24px 0 0;max-width:62ch}
172
+ .totals{display:flex;flex-wrap:wrap;gap:24px;margin:32px 0 0;padding:0;list-style:none}
173
+ .totals b{display:block;font-size:20px;font-weight:500;font-variant-numeric:tabular-nums}
174
+ .totals span{font-size:13px;color:var(--faint)}
175
+ .block{margin-top:48px}
176
+ .headline__score{margin:0;display:flex;align-items:baseline;gap:4px}
177
+ .headline__score b{font-size:48px;font-weight:500;letter-spacing:-.03em;line-height:1;font-variant-numeric:tabular-nums}
178
+ .headline__score span{font-size:20px;color:var(--faint)}
179
+ .headline__word{margin:8px 0 0;color:var(--muted);font-size:14px}
180
+ .headline__trail{font-variant-numeric:tabular-nums}
181
+ .headline__warn{margin:12px 0 0;font-size:14px;color:var(--err)}
182
+ .headline__caps{margin:12px 0 0;padding-left:20px;font-size:14px;color:var(--muted)}
183
+ .headline+.block{margin-top:24px}
184
+ .scores{border-collapse:collapse;width:100%;font-size:14px}
185
+ .scores th,.scores td{padding:8px 12px 8px 0;border-top:.5px solid var(--line);text-align:left;font-weight:400}
186
+ .scores td:nth-child(3){font-variant-numeric:tabular-nums;color:var(--muted);width:4em}
187
+ .scores td:last-child{color:var(--faint);width:7em}
188
+ .meter{display:block;height:6px;border-radius:9px;background:var(--chip);position:relative;overflow:hidden;min-width:120px}
189
+ .meter::after{content:"";position:absolute;inset:0;width:calc(var(--v)*100%);background:var(--fg);border-radius:inherit}
190
+ .filters{position:sticky;top:0;z-index:2;display:flex;flex-wrap:wrap;gap:8px;margin:48px -24px 0;padding:12px 24px;background:var(--bg);border-bottom:.5px solid var(--line)}
191
+ .filters select,.filters button{font:inherit;font-size:13px;color:var(--fg);background:var(--chip);border:0;border-radius:10px;padding:6px 10px;cursor:pointer}
192
+ .filters .count{margin-left:auto;font-size:13px;color:var(--faint);align-self:center}
193
+ .page-group{margin-top:40px}
194
+ .page-group>h2{display:flex;gap:12px;align-items:baseline}
195
+ .page-group>h2 small{font-size:13px;font-weight:400;color:var(--faint)}
196
+ .f{padding:24px 0;border-top:.5px solid var(--line)}
197
+ .f[hidden]{display:none}
198
+ .f__head{display:flex;gap:12px;align-items:baseline}
199
+ .f__title{margin:0;font-size:16px;font-weight:500;letter-spacing:-.01em}
200
+ .sev{flex:none;font-size:12px;padding:1px 8px;border-radius:999px}
201
+ .sev--error{color:var(--err);background:var(--err-bg)}
202
+ .sev--warning{color:var(--warn);background:var(--warn-bg)}
203
+ .sev--info{color:var(--info);background:var(--info-bg)}
204
+ .f__meta{display:flex;flex-wrap:wrap;gap:4px 14px;margin:6px 0 0;font-size:13px;color:var(--faint)}
205
+ .f__detail{margin:10px 0 0;max-width:68ch;color:var(--muted);font-size:14px}
206
+ .f__evidence{margin:8px 0 0;font-size:14px}
207
+ .f__evidence span{color:var(--faint)}
208
+ .f__steps{margin:10px 0 0;padding-left:20px;font-size:14px;color:var(--muted)}
209
+ .shot{position:relative;display:block;margin-top:16px;border-radius:12px;border:.5px solid var(--line);background-repeat:no-repeat;overflow:hidden;max-height:420px}
210
+ .shot--whole img{display:block;width:100%;height:auto}
211
+ .shot__mark{position:absolute;outline:2px solid var(--mark);outline-offset:2px;border-radius:4px;box-shadow:0 0 0 9999px rgba(0,0,0,.18)}
212
+ .f__facts{display:grid;gap:4px;margin:14px 0 0;font-size:13px}
213
+ .f__facts div{display:flex;gap:12px}
214
+ .f__facts dt{width:6em;flex:none;color:var(--faint)}
215
+ .f__facts dd{margin:0;min-width:0;overflow-wrap:anywhere}
216
+ .empty{margin-top:48px;color:var(--muted)}
217
+ .draft{font-size:13px;font-weight:400;color:var(--faint);margin-left:8px}
218
+ .chg{flex:none;font-size:12px;padding:0 8px;border-radius:999px;border:.5px solid currentColor}
219
+ .chg--new{color:var(--err)}
220
+ .chg--returned{color:var(--warn)}
221
+ .chg--still{color:var(--faint)}
222
+ .chg--changed{color:var(--info)}
223
+ .f__caption{margin:12px 0 0;font-size:13px;color:var(--faint)}
224
+ .since h3{margin:28px 0 8px;font-size:14px;font-weight:500}
225
+ .since__list{margin:0;padding:0;list-style:none;font-size:14px}
226
+ .since__list li{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;padding:8px 0;border-top:.5px solid var(--line)}
227
+ .since__where{font-size:13px;color:var(--faint)}
228
+ .since__diffs{border-collapse:collapse;width:100%;font-size:14px}
229
+ .since__diffs th,.since__diffs td{padding:8px 12px 8px 0;border-top:.5px solid var(--line);text-align:left;font-weight:400}
230
+ .since__diffs td{font-variant-numeric:tabular-nums;color:var(--muted)}
231
+ .since__diffs tr.same{color:var(--faint)}
232
+ .since__diffs a{color:inherit}
233
+ .since__note{font-size:14px;color:var(--muted)}
234
+ footer{margin-top:64px;font-size:13px;color:var(--faint)}
235
+ @media print{.filters{display:none}.f{break-inside:avoid}}
236
+ `;
237
+
238
+ const SCRIPT = `
239
+ const sel=(n)=>document.querySelector('[name="'+n+'"]');
240
+ function apply(){const s=sel('severity').value,d=sel('domain').value,p=sel('page').value,c=sel('change')?sel('change').value:'';let n=0;
241
+ document.querySelectorAll('.f').forEach(f=>{const show=(!s||f.dataset.severity===s)&&(!d||f.dataset.domain===d)&&(!p||f.dataset.page===p)&&(!c||f.dataset.change===c);f.hidden=!show;if(show)n++;});
242
+ document.querySelectorAll('.page-group').forEach(g=>{g.hidden=!g.querySelector('.f:not([hidden])');});
243
+ document.querySelector('.count').textContent=n+(n===1?' finding':' findings');}
244
+ document.querySelectorAll('.filters select').forEach(x=>x.addEventListener('change',apply));apply();
245
+ `;
246
+
247
+ export function render(run) {
248
+ const findings = sortFindings(run.findings.filter((f) => f.status !== "dismissed" && f.status !== "fixed"));
249
+ const c = counts(findings);
250
+ const pagesByRoute = new Map(run.pages.map((p) => [p.route, p]));
251
+ const groups = new Map();
252
+ for (const f of findings) {
253
+ const key = f.page ?? "Whole product";
254
+ if (!groups.has(key)) groups.set(key, []);
255
+ groups.get(key).push(f);
256
+ }
257
+ const option = (v, label) => `<option value="${esc(v)}">${esc(label)}</option>`;
258
+ const domains = [...new Set(findings.map((f) => f.domain))];
259
+ const title = `${KIND_TITLES[run.kind] ?? "Report"}${run.title ? `: ${run.title}` : ""}`;
260
+ const when = run.finished ? new Date(run.finished) : new Date();
261
+
262
+ const body = findings.length
263
+ ? [...groups]
264
+ .map(([route, list]) => {
265
+ const page = pagesByRoute.get(route);
266
+ return `<section class="page-group"><h2>${esc(route)}${page?.title ? ` <small>${esc(page.title)}</small>` : ""}</h2>${list.map((f) => card(f, page)).join("\n")}</section>`;
267
+ })
268
+ .join("\n")
269
+ : `<p class="empty">Nothing found. ${run.pages.length} ${run.pages.length === 1 ? "page" : "pages"} checked.</p>`;
270
+
271
+ return `<!doctype html>
272
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
273
+ <title>${esc(title)}</title><style>${STYLE}</style></head>
274
+ <body><main class="wrap">
275
+ <h1>${esc(title)}</h1>
276
+ <p class="lede">${esc(run.base ?? run.root ?? "")} · ${esc(when.toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" }))} · ${run.pages.length} ${run.pages.length === 1 ? "page" : "pages"}</p>
277
+ ${run.summary ? `<p class="summary">${esc(run.summary)}</p>` : ""}
278
+ <ul class="totals"><li><b>${c.error}</b><span>Errors</span></li><li><b>${c.warning}</b><span>Warnings</span></li><li><b>${c.info}</b><span>Notes</span></li></ul>
279
+ ${sinceSection(run)}
280
+ ${headline(run)}
281
+ ${typeof run.score === "number" ? scoreTable(run.scores, false, "By area") : scoreTable(run.scores, run.scoresDraft)}
282
+ <nav class="filters" aria-label="Filter findings">
283
+ <select name="severity" aria-label="Severity">${option("", "Every severity")}${option("error", "Errors")}${option("warning", "Warnings")}${option("info", "Notes")}</select>
284
+ <select name="domain" aria-label="Area">${option("", "Every area")}${domains.map((d) => option(d, DOMAIN_NAMES[d] ?? d)).join("")}</select>
285
+ <select name="page" aria-label="Page">${option("", "Every page")}${[...groups.keys()].map((p) => option(p, p)).join("")}</select>
286
+ ${run.compare ? `<select name="change" aria-label="Since last run">${option("", "Old and new")}${option("new", "New")}${option("returned", "Back again")}${option("still", "Still open")}${run.compare.visual ? option("changed", "Visual changes") : ""}</select>` : ""}
287
+ <span class="count" aria-live="polite"></span>
288
+ </nav>
289
+ ${body}
290
+ <footer>Made by Keyline. The data is in findings.json beside this file; <code>/keyline polish --from ${esc(run.kind === "smoke" ? "smoke-report" : "keyline-report")}</code> fixes what's open.</footer>
291
+ </main><script>${SCRIPT}</script></body></html>
292
+ `;
293
+ }
294
+
295
+ /** Render `dir/findings.json` to `dir/index.html`. Returns the path. */
296
+ export function renderDir(dir) {
297
+ const run = readRun(dir);
298
+ const file = join(dir, "index.html");
299
+ writeFileSync(file, render(run));
300
+ return file;
301
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Every page a product has, found three ways and merged:
3
+ *
4
+ * 1. From the code: the router's own files (Next app and pages routers,
5
+ * SvelteKit, Astro, Nuxt, Remix/React Router file routes, route objects
6
+ * and <Route path> in a React Router app, plain .html files).
7
+ * 2. From /sitemap.xml on the running site.
8
+ * 3. From a crawl of the running site: same-origin links, breadth first.
9
+ *
10
+ * A route with a parameter (`/projects/[id]`) can't be visited until someone
11
+ * names an example; it's returned with `dynamic: true` and, when the crawl met a
12
+ * matching URL, that URL as its `sample`.
13
+ */
14
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
15
+ import { join, relative, sep } from "node:path";
16
+ import { walk } from "trykeyline/check/files";
17
+
18
+ /** Route files: what a router reads, and plain HTML. */
19
+ const ROUTE_FILES = new Set([".tsx", ".ts", ".jsx", ".js", ".mdx", ".md", ".svelte", ".astro", ".vue", ".html"]);
20
+
21
+ /** Every route-shaped file under `dir`, as absolute paths, skipping what the detector skips (dependencies, build output, reports, dot-folders). */
22
+ const files = (dir) => walk(dir, { accept: ROUTE_FILES, skip: null, maxSize: Infinity }).map((f) => f.abs);
23
+
24
+ const segs = (rel) => rel.split(sep).filter(Boolean);
25
+ const toPath = (parts) => "/" + parts.filter(Boolean).join("/");
26
+ const isDynamic = (path) => /\[|:|\$|\*/.test(path);
27
+
28
+ function readDeps(root) {
29
+ try {
30
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
31
+ return { ...pkg.dependencies, ...pkg.devDependencies };
32
+ } catch {
33
+ return {};
34
+ }
35
+ }
36
+
37
+ /** Next.js app router: every page.* under app/, route groups and slots dropped. */
38
+ function nextApp(root) {
39
+ const out = [];
40
+ for (const base of ["app", "src/app"]) {
41
+ const dir = join(root, base);
42
+ for (const file of files(dir)) {
43
+ if (!/[\\/]page\.(tsx|ts|jsx|js|mdx|md)$/.test(file)) continue;
44
+ const all = segs(relative(dir, file)).slice(0, -1);
45
+ // A _private folder opts its whole subtree out of routing.
46
+ if (all.some((s) => s.startsWith("_"))) continue;
47
+ const parts = all.filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@"));
48
+ out.push({ path: toPath(parts), file: relative(root, file), source: "next-app" });
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /** Next.js pages router: files under pages/, minus _app, _document, _error and api/. */
55
+ function nextPages(root) {
56
+ const out = [];
57
+ for (const base of ["pages", "src/pages"]) {
58
+ const dir = join(root, base);
59
+ for (const file of files(dir)) {
60
+ if (!/\.(tsx|ts|jsx|js|mdx|md)$/.test(file)) continue;
61
+ const parts = segs(relative(dir, file));
62
+ if (parts[0] === "api" || /^_(app|document|error)\./.test(parts.at(-1))) continue;
63
+ parts[parts.length - 1] = parts.at(-1).replace(/\.\w+$/, "");
64
+ if (parts.at(-1) === "index") parts.pop();
65
+ out.push({ path: toPath(parts), file: relative(root, file), source: "next-pages" });
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function sveltekit(root) {
72
+ const dir = join(root, "src/routes");
73
+ return files(dir)
74
+ .filter((f) => /[\\/]\+page\.svelte$/.test(f))
75
+ .map((file) => {
76
+ const parts = segs(relative(dir, file)).slice(0, -1).filter((s) => !/^\(.*\)$/.test(s));
77
+ return { path: toPath(parts), file: relative(root, file), source: "sveltekit" };
78
+ });
79
+ }
80
+
81
+ function astro(root) {
82
+ const dir = join(root, "src/pages");
83
+ return files(dir)
84
+ .filter((f) => /\.(astro|md|mdx|html)$/.test(f))
85
+ .map((file) => {
86
+ const parts = segs(relative(dir, file));
87
+ parts[parts.length - 1] = parts.at(-1).replace(/\.\w+$/, "");
88
+ if (parts.at(-1) === "index") parts.pop();
89
+ return { path: toPath(parts), file: relative(root, file), source: "astro" };
90
+ });
91
+ }
92
+
93
+ function nuxt(root) {
94
+ const dir = join(root, "pages");
95
+ return files(dir)
96
+ .filter((f) => f.endsWith(".vue"))
97
+ .map((file) => {
98
+ const parts = segs(relative(dir, file));
99
+ parts[parts.length - 1] = parts.at(-1).replace(/\.vue$/, "");
100
+ if (parts.at(-1) === "index") parts.pop();
101
+ return { path: toPath(parts), file: relative(root, file), source: "nuxt" };
102
+ });
103
+ }
104
+
105
+ /** Remix and React Router v7 flat routes: app/routes/a.b._index.tsx → /a/b. */
106
+ function flatRoutes(root) {
107
+ const dir = join(root, "app/routes");
108
+ if (!existsSync(dir)) return [];
109
+ return readdirSync(dir)
110
+ .filter((f) => /\.(tsx|ts|jsx|js|mdx)$/.test(f) || existsSync(join(dir, f, "route.tsx")))
111
+ .map((name) => {
112
+ const parts = name.replace(/\.(tsx|ts|jsx|js|mdx)$/, "").split(".").filter((s) => s !== "_index" && !s.startsWith("_"));
113
+ return { path: toPath(parts.map((p) => p.replace(/^\$/, ":"))), file: join("app/routes", name), source: "flat-routes" };
114
+ })
115
+ .filter((r) => !r.file.includes("resources") && !r.path.includes("api"));
116
+ }
117
+
118
+ /** React Router route objects and <Route path="…">, read from source text. */
119
+ function routerConfig(root) {
120
+ const out = [];
121
+ const re = /(?:<Route[^>]*\spath=|\bpath:\s*)["'`](\/?[^"'`]*)["'`]/g;
122
+ for (const file of files(join(root, "src"))) {
123
+ if (!/\.(tsx|ts|jsx|js)$/.test(file)) continue;
124
+ const text = readFileSync(file, "utf8");
125
+ if (!/react-router|createBrowserRouter|<Route\b/.test(text)) continue;
126
+ for (const m of text.matchAll(re)) {
127
+ if (m[1] === "*" || m[1].startsWith("http")) continue;
128
+ out.push({ path: m[1].startsWith("/") ? m[1] : "/" + m[1], file: relative(root, file), source: "react-router" });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /** Plain HTML: every .html file outside build output. */
135
+ function staticHtml(root) {
136
+ return files(root)
137
+ .filter((f) => f.endsWith(".html"))
138
+ .map((file) => {
139
+ const rel = relative(root, file).split(sep).join("/");
140
+ const path = "/" + rel.replace(/(^|\/)index\.html$/, "$1").replace(/\/$/, "");
141
+ return { path: path || "/", file: rel, source: "html" };
142
+ });
143
+ }
144
+
145
+ /** Routes the code declares. */
146
+ export function routesFromCode(root) {
147
+ const deps = readDeps(root);
148
+ const found = [];
149
+ if (deps.next) found.push(...nextApp(root), ...nextPages(root));
150
+ if (deps["@sveltejs/kit"]) found.push(...sveltekit(root));
151
+ if (deps.astro) found.push(...astro(root));
152
+ if (deps.nuxt) found.push(...nuxt(root));
153
+ if (deps["@remix-run/react"] || deps["@react-router/dev"]) found.push(...flatRoutes(root));
154
+ if (deps["react-router"] || deps["react-router-dom"]) found.push(...routerConfig(root));
155
+ if (!found.length) found.push(...staticHtml(root));
156
+ return found.map((r) => ({ ...r, path: r.path.replace(/\/+$/, "") || "/", dynamic: isDynamic(r.path) }));
157
+ }
158
+
159
+ /** Paths listed in the running site's sitemap, same origin only. */
160
+ export async function routesFromSitemap(base) {
161
+ try {
162
+ const res = await fetch(new URL("/sitemap.xml", base));
163
+ if (!res.ok) return [];
164
+ const xml = await res.text();
165
+ const origin = new URL(base).origin;
166
+ return [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)]
167
+ .map((m) => m[1])
168
+ .filter((u) => u.startsWith(origin))
169
+ .map((u) => ({ path: new URL(u).pathname.replace(/\/+$/, "") || "/", source: "sitemap", dynamic: false }));
170
+ } catch {
171
+ return [];
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Same-origin links, breadth first, read from server HTML. A client-rendered
177
+ * app shows few links this way; capture.mjs adds the links each page renders.
178
+ */
179
+ export async function crawl(base, { limit = 40, depth = 2 } = {}) {
180
+ const origin = new URL(base).origin;
181
+ const seen = new Set(["/"]);
182
+ const failed = new Set();
183
+ let frontier = ["/"];
184
+ for (let d = 0; d < depth && frontier.length && seen.size < limit; d++) {
185
+ const next = [];
186
+ for (const path of frontier) {
187
+ let html = "";
188
+ try {
189
+ const res = await fetch(new URL(path, base), { redirect: "follow" });
190
+ if (!res.ok || !(res.headers.get("content-type") ?? "").includes("html")) {
191
+ if (!res.ok) failed.add(path);
192
+ continue;
193
+ }
194
+ html = await res.text();
195
+ } catch {
196
+ failed.add(path);
197
+ continue;
198
+ }
199
+ for (const m of html.matchAll(/<a\b[^>]*\shref=["']([^"'#]+)/gi)) {
200
+ const p = linkPath(m[1], new URL(path, base).href, origin);
201
+ if (p && !seen.has(p) && seen.size < limit) {
202
+ seen.add(p);
203
+ next.push(p);
204
+ }
205
+ }
206
+ }
207
+ frontier = next;
208
+ }
209
+ // The seed is a guess; keep it only if it answered. Linked paths stay: a broken link is a finding, not noise.
210
+ if (failed.has("/")) seen.delete("/");
211
+ return [...seen].map((path) => ({ path, source: "crawl", dynamic: false }));
212
+ }
213
+
214
+ /** A same-origin page path for an href, or null (assets, mail, other sites). */
215
+ export function linkPath(href, from, origin) {
216
+ try {
217
+ const u = new URL(href, from);
218
+ if (u.origin !== origin) return null;
219
+ if (/\.(png|jpe?g|gif|svg|webp|avif|ico|pdf|zip|css|js|mjs|json|xml|txt|mp4|webm|woff2?)$/i.test(u.pathname)) return null;
220
+ return u.pathname.replace(/\/index\.html$/, "/").replace(/\/+$/, "") || "/";
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ /** Fill a dynamic route from a concrete path that matches its shape. */
227
+ function sampleFor(route, paths) {
228
+ // A catch-all ([...slug], *) matches any path, so no known page is an example of it.
229
+ if (/\[\.\.\.|\*/.test(route.path)) return null;
230
+ const re = new RegExp("^" + route.path.split("/").map((s) => (/^\[|^:|^\$/.test(s) ? "[^/]+" : s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))).join("/") + "$");
231
+ return paths.find((p) => re.test(p) && !isDynamic(p)) ?? null;
232
+ }
233
+
234
+ /**
235
+ * Everything, merged: code first (it knows files), then the sitemap and the
236
+ * crawl. Returns `{ routes, dynamic }` — routes to visit, and parameterised
237
+ * routes still waiting for an example.
238
+ */
239
+ export async function discover({ root, base = null, limit = 40 } = {}) {
240
+ const code = root ? routesFromCode(root) : [];
241
+ const live = base ? [...(await routesFromSitemap(base)), ...(await crawl(base, { limit }))] : [];
242
+ const byPath = new Map();
243
+ for (const r of [...code, ...live]) {
244
+ const prev = byPath.get(r.path);
245
+ byPath.set(r.path, prev ? { ...prev, sources: [...new Set([...prev.sources, r.source])] } : { ...r, sources: [r.source] });
246
+ }
247
+ const all = [...byPath.values()];
248
+ const concrete = all.filter((r) => !r.dynamic).map((r) => r.path);
249
+ const dynamic = all.filter((r) => r.dynamic).map((r) => ({ ...r, sample: sampleFor(r, concrete) }));
250
+ const routes = all.filter((r) => !r.dynamic).sort((a, b) => a.path.localeCompare(b.path)).slice(0, limit);
251
+ return { routes, dynamic };
252
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The score out of 10: one number a person reads first, drafted from the six
3
+ * domain scores (0–4) and held under caps that come from evidence. The audit
4
+ * drafts it; the agent settles it (commands/audit.md); the report renders it
5
+ * and recomputes the caps, so a score settled above them shows as such.
6
+ */
7
+
8
+ /** The score out of 10 a product has to reach before it ships. */
9
+ export const SHIP = 8;
10
+
11
+ const NAMES = { type: "type", color: "colour", layout: "layout", depth: "depth", motion: "motion", patterns: "patterns" };
12
+ const named = (ds) => ds.map((d) => NAMES[d] ?? d).join(", ");
13
+
14
+ const isOpen = (f) => f.status !== "dismissed" && f.status !== "fixed";
15
+
16
+ /**
17
+ * What holds the score out of 10 down, whatever the judgement: each cap is
18
+ * evidence a reader would meet. The agent settling the score may go lower
19
+ * than the lowest cap, never higher.
20
+ */
21
+ export function scoreCaps(scores, findings) {
22
+ const caps = [];
23
+ const errors = findings.filter((f) => isOpen(f) && f.severity === "error").length;
24
+ if (errors) caps.push({ max: 6, why: `${errors} open ${errors === 1 ? "error" : "errors"}: broken for someone` });
25
+ const warnings = findings.filter((f) => isOpen(f) && f.severity === "warning").length;
26
+ if (warnings) caps.push({ max: 7, why: `${warnings} open ${warnings === 1 ? "warning" : "warnings"}: a law a reader feels` });
27
+ const at = (test) => Object.entries(scores ?? {}).filter(([, s]) => test(s)).map(([d]) => d);
28
+ const broken = at((s) => s <= 1);
29
+ if (broken.length) caps.push({ max: 5, why: `${named(broken)} not working as a system` });
30
+ const felt = at((s) => s === 2);
31
+ if (felt.length) caps.push({ max: 7, why: `a law a reader feels is broken in ${named(felt)}` });
32
+ return caps.sort((a, b) => a.max - b.max);
33
+ }
34
+
35
+ /**
36
+ * A draft score out of 10 from the domain scores: 2 + 2 × their mean, so all
37
+ * 4s is 10, all 3s is 8 (ready to ship), all 2s is 6. Then held under the
38
+ * caps, and rounded to the half point.
39
+ */
40
+ export function draftScore(scores, findings) {
41
+ const values = Object.values(scores ?? {});
42
+ if (!values.length) return null;
43
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
44
+ const capped = Math.min(2 + 2 * mean, ...scoreCaps(scores, findings).map((c) => c.max));
45
+ return Math.round(capped * 2) / 2;
46
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A static file server for a folder, so a site with no dev server (plain HTML,
3
+ * a build output) can be walked like a running one. Localhost only, a free
4
+ * port, closed when the run ends.
5
+ */
6
+ import { createReadStream, existsSync, statSync } from "node:fs";
7
+ import { createServer } from "node:http";
8
+ import { extname, join, normalize, resolve } from "node:path";
9
+
10
+ const TYPES = {
11
+ ".html": "text/html; charset=utf-8",
12
+ ".css": "text/css; charset=utf-8",
13
+ ".js": "text/javascript; charset=utf-8",
14
+ ".mjs": "text/javascript; charset=utf-8",
15
+ ".json": "application/json",
16
+ ".svg": "image/svg+xml",
17
+ ".png": "image/png",
18
+ ".jpg": "image/jpeg",
19
+ ".jpeg": "image/jpeg",
20
+ ".gif": "image/gif",
21
+ ".webp": "image/webp",
22
+ ".avif": "image/avif",
23
+ ".ico": "image/x-icon",
24
+ ".woff": "font/woff",
25
+ ".woff2": "font/woff2",
26
+ ".txt": "text/plain; charset=utf-8",
27
+ ".xml": "application/xml",
28
+ };
29
+
30
+ export function serve(dir) {
31
+ const root = resolve(dir);
32
+ const server = createServer((req, res) => {
33
+ const url = new URL(req.url, "http://localhost");
34
+ let path = normalize(join(root, decodeURIComponent(url.pathname)));
35
+ if (!path.startsWith(root)) {
36
+ res.writeHead(403).end();
37
+ return;
38
+ }
39
+ if (existsSync(path) && statSync(path).isDirectory()) {
40
+ // As every static host does: a folder without its slash redirects, so relative links resolve inside it.
41
+ if (!url.pathname.endsWith("/")) {
42
+ res.writeHead(301, { location: url.pathname + "/" + url.search }).end();
43
+ return;
44
+ }
45
+ path = join(path, "index.html");
46
+ }
47
+ else if (!existsSync(path) && existsSync(path + ".html")) path += ".html";
48
+ if (!existsSync(path)) {
49
+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
50
+ return;
51
+ }
52
+ res.writeHead(200, { "content-type": TYPES[extname(path).toLowerCase()] ?? "application/octet-stream" });
53
+ createReadStream(path).pipe(res);
54
+ });
55
+ return new Promise((ok) => {
56
+ server.listen(0, "127.0.0.1", () => {
57
+ const { port } = server.address();
58
+ ok({ url: `http://127.0.0.1:${port}`, close: () => new Promise((done) => server.close(done)) });
59
+ });
60
+ });
61
+ }