systemscan.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. #!/usr/bin/env node
  2. /**
  3. * systemscan.mjs — the multi-screen gate: does this product still have ONE design system?
  4. *
  5. * slopscan reads source and catches defaults. shoot.mjs photographs one page. Neither can see the
  6. * failure mode of a real app: drift. Screen 1 has three button variants, screen 7 invents a fourth,
  7. * and nobody notices because every screen looks fine on its own. This crawls every route, reads what
  8. * the browser ACTUALLY PAINTED, and reports the system as built rather than as documented.
  9. *
  10. * Usage:
  11. * node scripts/systemscan.mjs <url> [<url>...]
  12. * node scripts/systemscan.mjs http://localhost:3000 --routes /,/settings,/billing
  13. *
  14. * Options:
  15. * --routes a,b,c paths to append to the first url (instead of listing full urls)
  16. * --out DIR output dir (default design/system)
  17. * --max-variants B variant budget: a number, or per kind — `button=5,select=1,4` (default 4)
  18. * --width N viewport width (default 1440)
  19. * --no-shots skip the component contact sheet
  20. *
  21. * Writes DIR/SYSTEM-REPORT.md (read it), DIR/system.json, DIR/components.png.
  22. * Exit 1 when the system is provably broken: a control type over budget, an interactive element with
  23. * no visible focus state, or a token used on exactly one route.
  24. */
  25. import { mkdir, writeFile } from 'fs/promises';
  26. import { resolve, join } from 'path';
  27. const args = process.argv.slice(2);
  28. if (!args.length || args.includes('--help')) {
  29. console.log(`systemscan.mjs — cross-route design-system drift gate
  30. node scripts/systemscan.mjs <url> [<url>...]
  31. node scripts/systemscan.mjs http://localhost:3000 --routes /,/settings,/billing
  32. --out DIR --max-variants 4|button=5,select=1 --width 1440 --no-shots`);
  33. process.exit(0);
  34. }
  35. const get = (f, d) => { const i = args.indexOf(f); return i !== -1 ? args[i + 1] : d; };
  36. const has = f => args.includes(f);
  37. const outDir = resolve(get('--out', 'design/system'));
  38. // Per-kind budgets: `--max-variants button=5,select=1` (a bare number sets the default for the rest).
  39. // One global number meant a sheet declaring button:5 and select:1 had to pass 5, leaving every
  40. // smaller kind unpoliced — the sheet's central promise enforced for exactly one control kind.
  41. const rawBudget = get('--max-variants', '4');
  42. const budget = { default: 4, byKind: {} };
  43. for (const part of String(rawBudget).split(',').map(s => s.trim()).filter(Boolean)) {
  44. const m = part.match(/^([a-z]+)\s*=\s*(\d+)$/i);
  45. if (m) budget.byKind[m[1].toLowerCase()] = +m[2];
  46. else if (/^\d+$/.test(part)) budget.default = +part;
  47. else console.error(`[systemscan] ignoring unparseable budget "${part}" — use 4 or button=5,select=1`);
  48. }
  49. const budgetFor = kind => budget.byKind[kind] ?? budget.default;
  50. const width = parseInt(get('--width', '1440'), 10) || 1440;
  51. const shots = !has('--no-shots');
  52. let urls = args.filter(a => /^https?:\/\//.test(a) || a.startsWith('file://'));
  53. const routes = get('--routes', null);
  54. if (routes && urls.length) {
  55. const base = urls[0].replace(/\/$/, '');
  56. urls = routes.split(',').map(r => base + (r.startsWith('/') ? r : '/' + r));
  57. }
  58. if (!urls.length) { console.error('[systemscan] no urls. Pass them, or a base url + --routes /a,/b'); process.exit(1); }
  59. let chromium;
  60. try { ({ chromium } = await import('playwright')); }
  61. catch { console.error('playwright not found. Install: npm i -D playwright && npx playwright install chromium'); process.exit(2); }
  62. // Everything below is read off getComputedStyle, i.e. the system as PAINTED. A token that exists in
  63. // the stylesheet but is never rendered is not part of the system; a one-off inline style is.
  64. const COLLECT = () => {
  65. const cs = getComputedStyle;
  66. const px = v => Math.round(parseFloat(v) || 0);
  67. const vis = el => {
  68. const s = cs(el);
  69. if (s.display === 'none' || s.visibility === 'hidden' || +s.opacity === 0) return false;
  70. const r = el.getBoundingClientRect();
  71. return r.width > 1 && r.height > 1;
  72. };
  73. const all = [...document.querySelectorAll('*')].slice(0, 6000).filter(vis);
  74. const controlKind = el => {
  75. const t = el.tagName.toLowerCase();
  76. const role = el.getAttribute('role');
  77. if (t === 'button' || role === 'button') return 'button';
  78. if (t === 'a' && /(^|\s)(btn|button)/i.test(el.className || '')) return 'button';
  79. if (t === 'a') return 'link';
  80. if (t === 'input') return ['checkbox', 'radio'].includes(el.type) ? 'toggle' : 'input';
  81. if (t === 'select') return 'select';
  82. if (t === 'textarea') return 'input';
  83. if (role === 'tab') return 'tab';
  84. return null;
  85. };
  86. // The signature is what a user can SEE. Two buttons with different class names but identical
  87. // paint are one variant; two with the same class and different paint are two.
  88. const sig = el => {
  89. const s = cs(el);
  90. return [
  91. s.backgroundColor, s.color, s.borderColor,
  92. `${px(s.borderTopWidth)}b`, `${px(s.borderTopLeftRadius)}r`,
  93. `${px(s.fontSize)}/${s.fontWeight}`,
  94. `${px(s.paddingTop)}x${px(s.paddingLeft)}`,
  95. s.boxShadow === 'none' ? 'noshadow' : 'shadow',
  96. ].join(' | ');
  97. };
  98. // A STATE is not a variant. A disabled secondary button paints differently from an enabled one by
  99. // design — that is the state matrix system.md demands, and counting it as a fifth button punishes
  100. // the team that built it while a system with no disabled state at all sails through. Same for a
  101. // control that inverts because the row it sits in is in an alert state: the component did not
  102. // multiply, its container changed colour underneath it. Both are counted and reported separately.
  103. const stateOf = el => {
  104. if (el.disabled || el.getAttribute('aria-disabled') === 'true') return 'disabled';
  105. if (el.getAttribute('aria-current') || el.getAttribute('aria-selected') === 'true') return 'current';
  106. for (let n = el.parentElement, hops = 0; n && hops < 4; n = n.parentElement, hops++) {
  107. const st = n.getAttribute?.('data-state');
  108. if (st && st !== 'default') return `in-${st}`;
  109. }
  110. return null;
  111. };
  112. const controls = {};
  113. const states = {};
  114. let shotId = 0;
  115. for (const el of all) {
  116. const kind = controlKind(el);
  117. if (!kind) continue;
  118. const state = stateOf(el);
  119. if (state) { (states[kind] ??= {})[state] = ((states[kind] ??= {})[state] || 0) + 1; continue; }
  120. const k = sig(el);
  121. (controls[kind] ??= {});
  122. if (!controls[kind][k]) {
  123. // Tag the exemplar NOW and re-select it by attribute in the screenshot pass. Handing a
  124. // positional index between two independent DOM walks produced tiles that showed a parent or a
  125. // sibling rather than the control they were captioned with — which destroys the sheet's whole
  126. // purpose, because a tile showing the wrong element looks different for the wrong reason.
  127. const tag = `ss${shotId++}`;
  128. el.setAttribute('data-ss-shot', tag);
  129. controls[kind][k] = { count: 0, sample: (el.innerText || el.value || el.type || '').trim().slice(0, 24), tag };
  130. }
  131. controls[kind][k].count++;
  132. }
  133. const tally = (map, key) => { map[key] = (map[key] || 0) + 1; };
  134. const colors = {}, type = {}, radii = {}, shadows = {}, space = {};
  135. for (const el of all) {
  136. const s = cs(el);
  137. if (s.backgroundColor && s.backgroundColor !== 'rgba(0, 0, 0, 0)') tally(colors, s.backgroundColor);
  138. // `color` on a wrapper paints no glyph. Tallying it unfiltered made <html>'s inherited initial
  139. // colour the most common "colour in the product" and inflates the headline count for everyone.
  140. const leafText = el.children.length === 0 && (el.textContent || '').trim();
  141. if (s.color && leafText) tally(colors, s.color);
  142. if (leafText) {
  143. tally(type, `${px(s.fontSize)}px/${s.fontWeight}/${s.fontFamily.split(',')[0].replace(/["']/g, '')}`);
  144. }
  145. const r = px(s.borderTopLeftRadius); if (r) tally(radii, `${r}px`);
  146. if (s.boxShadow && s.boxShadow !== 'none') tally(shadows, s.boxShadow.slice(0, 60));
  147. for (const v of [s.paddingTop, s.paddingLeft, s.marginTop]) { const n = px(v); if (n) tally(space, `${n}px`); }
  148. }
  149. return {
  150. controls, states, colors, type, radii, shadows, space,
  151. focusable: all.filter(el => el.matches('a[href],button,input,select,textarea,[tabindex]:not([tabindex="-1"])')).length,
  152. hasDisabled: all.some(el => el.matches('[disabled],[aria-disabled="true"]')),
  153. title: document.title.slice(0, 60),
  154. landmarks: ['header', 'nav', 'main', 'footer', 'aside'].filter(t => document.querySelector(t)).join(','),
  155. h1: document.querySelectorAll('h1').length,
  156. };
  157. };
  158. /**
  159. * Focus state cannot be read from a stylesheet: a `:focus-visible` rule may exist and be overridden,
  160. * and `:focus-visible` itself is a heuristic that programmatic `.focus()` does not reliably trigger.
  161. * So drive the real thing — press Tab and look at what the browser actually paints. Tabbing also
  162. * skips disabled and unfocusable elements for free, which a `.focus()` loop reports as failures.
  163. */
  164. const PROBE_FOCUS = async (page, maxStops = 40) => {
  165. const paint = () => {
  166. const cs = getComputedStyle;
  167. // Only properties that actually PAINT. outline-offset alone draws nothing, and including it
  168. // let an element that kills its outline still read as "focus state changed".
  169. const sig = el => { const s = cs(el); return `${s.outlineStyle === 'none' ? 'no-outline' : s.outline} ${s.boxShadow} ${s.borderColor} ${s.backgroundColor} ${s.color} ${s.textDecorationLine}`; };
  170. const els = [...document.querySelectorAll('a[href],button,input,select,textarea,summary,[tabindex]:not([tabindex="-1"])')];
  171. els.forEach((el, i) => el.setAttribute('data-ss-i', String(i)));
  172. return els.map(sig);
  173. };
  174. const unfocused = await page.evaluate(paint);
  175. await page.evaluate(() => (document.activeElement || document.body).blur?.());
  176. const bad = [], seen = new Set();
  177. for (let i = 0; i < maxStops; i++) {
  178. await page.keyboard.press('Tab');
  179. const stop = await page.evaluate(() => {
  180. const el = document.activeElement;
  181. if (!el || el === document.body || !el.hasAttribute?.('data-ss-i')) return null;
  182. const s = getComputedStyle(el);
  183. const r = el.getBoundingClientRect();
  184. return {
  185. i: +el.getAttribute('data-ss-i'),
  186. sig: `${s.outlineStyle === 'none' ? 'no-outline' : s.outline} ${s.boxShadow} ${s.borderColor} ${s.backgroundColor} ${s.color} ${s.textDecorationLine}`,
  187. label: el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + ' “' + (el.innerText || el.value || el.getAttribute('aria-label') || '').trim().slice(0, 20) + '”',
  188. offscreen: r.width < 1 || r.height < 1,
  189. };
  190. });
  191. if (!stop) continue;
  192. if (seen.has(stop.i)) break; // wrapped around the tab ring
  193. seen.add(stop.i);
  194. if (!stop.offscreen && unfocused[stop.i] === stop.sig) bad.push(stop.label);
  195. }
  196. return { probed: seen.size, noFocusRing: bad };
  197. };
  198. const browser = await chromium.launch({ headless: true });
  199. const ctx = await browser.newContext({ viewport: { width, height: 900 } });
  200. await mkdir(outDir, { recursive: true });
  201. const perRoute = [];
  202. for (const url of urls) {
  203. const page = await ctx.newPage();
  204. const errs = [];
  205. page.on('pageerror', e => errs.push(e.message));
  206. page.on('console', m => m.type() === 'error' && errs.push(m.text()));
  207. try {
  208. process.stderr.write(`[systemscan] ${url}\n`);
  209. const resp = await page.goto(url, { waitUntil: 'commit', timeout: 30_000 });
  210. const dcl = await page.waitForLoadState('domcontentloaded', { timeout: 15_000 }).then(() => true).catch(() => false);
  211. await page.waitForTimeout(dcl ? 2500 : 6000);
  212. if (!dcl) await page.evaluate(() => window.stop()).catch(() => {});
  213. const data = await page.evaluate(COLLECT);
  214. const focus = await PROBE_FOCUS(page);
  215. const status = resp?.status?.() ?? 0;
  216. // A route that renders nothing contributes nothing to the counts, so a mistyped route list made
  217. // the gate QUIETER instead of louder. A gate that goes green on a 404 is worse than no gate.
  218. const empty = !data.landmarks && !data.h1 && !data.focusable;
  219. perRoute.push({ url, ...data, focus, errors: errs, status, empty });
  220. if (status >= 400) console.error(`[systemscan] ${url} → HTTP ${status}`);
  221. else if (empty) console.error(`[systemscan] ${url} → rendered nothing measurable (no landmark, no h1, no focusable)`);
  222. if (shots) {
  223. // one exemplar screenshot per distinct control variant, so the report has a picture of the
  224. // drift and not only a count of it
  225. for (const [kind, variants] of Object.entries(data.controls)) {
  226. let i = 0;
  227. for (const [, v] of Object.entries(variants)) {
  228. if (!v.tag) continue;
  229. const name = `${kind}-${perRoute.length}-${i++}.png`;
  230. try {
  231. const box = await page.$(`[data-ss-shot="${v.tag}"]`); // the element we actually measured
  232. if (box) { await box.scrollIntoViewIfNeeded({ timeout: 4000 }); await box.screenshot({ path: join(outDir, 'components', name), timeout: 8000 }); v.shot = `components/${name}`; }
  233. } catch { /* an element that will not sit still is not worth failing the run over */ }
  234. }
  235. }
  236. }
  237. } catch (e) {
  238. perRoute.push({ url, error: e.message.split('\n')[0] });
  239. } finally { await page.close(); }
  240. }
  241. // ---- aggregate across routes -------------------------------------------------
  242. const ok = perRoute.filter(r => !r.error);
  243. if (!ok.length) { console.error('[systemscan] no route could be read.'); await browser.close(); process.exit(1); }
  244. // A document scanned twice (`/settings` and `/settings#state-error` are the same DOM) must not count
  245. // twice — summing across URLs meant scanning MORE thoroughly hid genuine one-off variants, which is
  246. // the opposite of what `system.md` tells you to do. Count per document, take the max, then sum.
  247. const docOf = u => u.split('#')[0];
  248. const docs = [...new Set(ok.map(r => docOf(r.url)))];
  249. const mergeCount = key => {
  250. const m = {};
  251. for (const r of ok) for (const [k, n] of Object.entries(r[key] || {})) {
  252. (m[k] ??= { perDoc: {} });
  253. const d = docOf(r.url);
  254. m[k].perDoc[d] = Math.max(m[k].perDoc[d] || 0, n);
  255. }
  256. return Object.entries(m)
  257. .map(([k, v]) => ({ k, total: Object.values(v.perDoc).reduce((a, b) => a + b, 0), routes: Object.keys(v.perDoc).length }))
  258. .sort((a, b) => b.total - a.total);
  259. };
  260. const controlVariants = {};
  261. for (const r of ok) for (const [kind, vars] of Object.entries(r.controls || {})) {
  262. (controlVariants[kind] ??= {});
  263. for (const [sig, v] of Object.entries(vars)) {
  264. const slot = (controlVariants[kind][sig] ??= { perDoc: {}, sample: v.sample, shot: v.shot });
  265. const d = docOf(r.url);
  266. slot.perDoc[d] = Math.max(slot.perDoc[d] || 0, v.count);
  267. slot.shot ??= v.shot;
  268. }
  269. }
  270. for (const vars of Object.values(controlVariants)) for (const v of Object.values(vars)) {
  271. v.count = Object.values(v.perDoc).reduce((a, b) => a + b, 0);
  272. v.routes = new Set(Object.keys(v.perDoc));
  273. }
  274. // States, gathered the same way but never counted against the variant budget.
  275. const controlStates = {};
  276. for (const r of ok) for (const [kind, st] of Object.entries(r.states || {}))
  277. for (const [name, n] of Object.entries(st)) {
  278. ((controlStates[kind] ??= {})[name] ??= 0);
  279. controlStates[kind][name] += n;
  280. }
  281. const fails = [], warns = [];
  282. for (const [kind, vars] of Object.entries(controlVariants)) {
  283. const n = Object.keys(vars).length, b = budgetFor(kind);
  284. if (n > b) fails.push(`${kind}: ${n} distinct rendered variants (budget ${b}). A variant nobody can name is drift.`);
  285. for (const [sig, v] of Object.entries(vars)) {
  286. if (v.count === 1 && n > 1) warns.push(`${kind} variant used exactly once ("${v.sample}") — either promote it into the system or delete it: ${sig}`);
  287. }
  288. }
  289. const blank = perRoute.filter(r => !r.error && (r.status >= 400 || r.empty));
  290. if (blank.length) fails.push(`${blank.length} route(s) rendered nothing measurable or returned an error status — a gate that goes green on a 404 is worse than no gate: ${blank.map(r => `${r.url}${r.status >= 400 ? ` (HTTP ${r.status})` : ''}`).join(', ')}`);
  291. const noFocus = ok.flatMap(r => (r.focus?.noFocusRing || []).map(t => `${r.url} → ${t}`));
  292. if (noFocus.length) fails.push(`${noFocus.length} interactive element(s) paint identically when focused — keyboard users cannot see where they are`);
  293. const colors = mergeCount('colors'), type = mergeCount('type'), radii = mergeCount('radii'), shadows = mergeCount('shadows');
  294. if (docs.length > 1) {
  295. for (const [label, list] of [['colour', colors], ['type step', type], ['radius', radii]]) {
  296. const singles = list.filter(x => x.routes === 1 && x.total >= 3);
  297. if (singles.length) warns.push(`${singles.length} ${label}(s) appear on exactly one route and nowhere else — that is where the system is splitting: ${singles.slice(0, 4).map(s => s.k).join(' · ')}`);
  298. }
  299. }
  300. if (type.length > 12) warns.push(`${type.length} distinct type steps across the product — a scale nobody can hold in their head is not a scale`);
  301. if (!ok.some(r => r.hasDisabled)) warns.push('no disabled control appeared on any route — the disabled state is probably undesigned, not absent');
  302. // ---- component contact sheet -------------------------------------------------
  303. let sheet = null;
  304. const tiles = Object.entries(controlVariants).flatMap(([kind, vars]) =>
  305. Object.entries(vars).filter(([, v]) => v.shot).map(([, v], i) => ({ kind, i, ...v })));
  306. if (shots && tiles.length) {
  307. const html = `<!doctype html><meta charset="utf-8"><style>
  308. body{margin:0;background:#141414;font:12px/1.3 ui-monospace,monospace;color:#ddd}
  309. .g{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;padding:12px}
  310. figure{margin:0;background:#1e1e1e;border-radius:4px;overflow:hidden;padding:10px}
  311. img{display:block;max-width:100%;margin:0 auto 8px}
  312. b{color:#fff}
  313. </style><div class=g>${tiles.map(t =>
  314. `<figure><img src="${t.shot}"><figcaption><b>${t.kind}</b> ×${t.count} · ${t.routes.size} route(s)</figcaption></figure>`).join('')}</div>`;
  315. const f = join(outDir, '_components.html');
  316. await writeFile(f, html, 'utf8');
  317. const p = await ctx.newPage();
  318. await p.setViewportSize({ width: 1200, height: 900 });
  319. await p.goto('file:///' + f.replace(/\\/g, '/'), { waitUntil: 'load', timeout: 20_000 }).catch(() => {});
  320. await p.waitForTimeout(900);
  321. // shoot the grid, not the viewport — a fullPage shot of a two-row sheet is mostly empty canvas
  322. const grid = await p.$('.g');
  323. await (grid || p).screenshot({ path: join(outDir, 'components.png') });
  324. await p.close();
  325. sheet = 'components.png';
  326. }
  327. await browser.close();
  328. // ---- report ------------------------------------------------------------------
  329. const L = [];
  330. L.push(`# SYSTEM-REPORT — ${ok.length} route(s), ${new Date().toISOString().slice(0, 10)}`);
  331. L.push('');
  332. L.push('The system as **painted**, not as documented. A token in the stylesheet that never renders is');
  333. L.push('not part of the system; a one-off inline style is. Read this against `design/DESIGN.md` — every');
  334. L.push('number below that DESIGN.md does not account for is drift.');
  335. L.push('');
  336. if (sheet) L.push(`**Look at \`${sheet}\`** — one tile per distinct rendered control variant. Two tiles that look the same to you but appear separately are the drift.\n`);
  337. L.push('## Controls');
  338. L.push('');
  339. L.push('| kind | distinct variants | budget | total instances |');
  340. L.push('|---|---|---|---|');
  341. for (const [kind, vars] of Object.entries(controlVariants)) {
  342. const n = Object.keys(vars).length;
  343. L.push(`| ${kind} | **${n}** | ${budgetFor(kind)} | ${Object.values(vars).reduce((s, v) => s + v.count, 0)} |`);
  344. }
  345. L.push('');
  346. for (const [kind, vars] of Object.entries(controlVariants)) {
  347. L.push(`### ${kind}`);
  348. for (const [sig, v] of Object.entries(vars)) L.push(`- ×${v.count} on ${v.routes.size} route(s) — "${v.sample}" — \`${sig}\``);
  349. if (controlStates[kind]) {
  350. const st = Object.entries(controlStates[kind]).map(([n, c]) => `${n} ×${c}`).join(' · ');
  351. L.push(`- *states (not counted as variants): ${st}*`);
  352. }
  353. L.push('');
  354. }
  355. if (Object.keys(controlStates).length) {
  356. L.push('> States — disabled, current, and controls inside a row carrying a `data-state` — are');
  357. L.push('> excluded from the variant budget. A disabled button paints differently on purpose; a');
  358. L.push('> product that has no disabled state at all should not score better than one that does.');
  359. L.push('');
  360. }
  361. L.push('## Tokens as rendered');
  362. L.push('');
  363. for (const [label, list] of [['Colour', colors], ['Type step', type], ['Radius', radii], ['Shadow', shadows]]) {
  364. L.push(`**${label}** (${list.length} distinct)`);
  365. for (const x of list.slice(0, 10)) L.push(`- \`${x.k}\` — ${x.total}× on ${x.routes} route(s)`);
  366. if (list.length > 10) L.push(`- …and ${list.length - 10} more`);
  367. L.push('');
  368. }
  369. L.push('## Per route');
  370. L.push('');
  371. L.push('| route | landmarks | h1 | focusable | console errors |');
  372. L.push('|---|---|---|---|---|');
  373. for (const r of ok) L.push(`| ${r.url} | ${r.landmarks || '—'} | ${r.h1} | ${r.focusable} | ${r.errors.length} |`);
  374. for (const r of perRoute.filter(r => r.error)) L.push(`| ${r.url} | **unreachable** — ${r.error} | | | |`);
  375. L.push('');
  376. if (fails.length) { L.push('## FAIL'); fails.forEach(f => L.push(`- ${f}`)); L.push(''); }
  377. if (noFocus.length) { L.push('### Elements with no visible focus state'); noFocus.slice(0, 20).forEach(t => L.push(`- ${t}`)); L.push(''); }
  378. if (warns.length) { L.push('## WARN'); warns.forEach(w => L.push(`- ${w}`)); L.push(''); }
  379. if (!fails.length && !warns.length) L.push('No drift detected. The product renders one system.\n');
  380. await writeFile(join(outDir, 'SYSTEM-REPORT.md'), L.join('\n'), 'utf8');
  381. await writeFile(join(outDir, 'system.json'), JSON.stringify({
  382. routes: perRoute.map(r => ({ ...r, controls: undefined })),
  383. controls: Object.fromEntries(Object.entries(controlVariants).map(([k, v]) =>
  384. [k, Object.entries(v).map(([sig, x]) => ({ sig, count: x.count, routes: [...x.routes], sample: x.sample }))])),
  385. colors, type, radii, shadows, fails, warns,
  386. }, null, 2), 'utf8');
  387. console.log(`\n=== systemscan ===`);
  388. console.log(`routes : ${ok.length}/${perRoute.length} read (${docs.length} distinct document(s))`);
  389. console.log(`controls: ${Object.entries(controlVariants).map(([k, v]) => `${k} ${Object.keys(v).length}`).join(' · ') || '—'}`);
  390. console.log(`tokens : ${colors.length} colours · ${type.length} type steps · ${radii.length} radii · ${shadows.length} shadows`);
  391. console.log(`report : ${join(outDir, 'SYSTEM-REPORT.md')}${sheet ? `\nsheet : ${join(outDir, sheet)}` : ''}`);
  392. for (const f of fails) console.log(`FAIL ${f}`);
  393. for (const w of warns.slice(0, 5)) console.log(`WARN ${w}`);
  394. process.exit(fails.length ? 1 : 0);