@uselazuli/cli 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +21 -0
  3. package/README.md +202 -2
  4. package/agents/lazuli-design-reviewer.md +30 -0
  5. package/agents/lazuli-first-look.md +22 -0
  6. package/agents/lazuli-task-tester.md +25 -0
  7. package/bin/lazuli.mjs +747 -0
  8. package/package.json +11 -4
  9. package/rules/accessibility/HYPOTHESES.md +8 -0
  10. package/rules/accessibility/_area.yaml +7 -0
  11. package/rules/accessibility/operable.yaml +100 -0
  12. package/rules/accessibility/perceivable.yaml +153 -0
  13. package/rules/accessibility/robust.yaml +24 -0
  14. package/rules/accessibility/understandable.yaml +72 -0
  15. package/rules/color/HYPOTHESES.md +27 -0
  16. package/rules/color/_area.yaml +10 -0
  17. package/rules/color/adapt.yaml +183 -0
  18. package/rules/color/create.yaml +259 -0
  19. package/rules/color/review.yaml +215 -0
  20. package/rules/color/signal.yaml +196 -0
  21. package/rules/content/HYPOTHESES.md +19 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +378 -0
  24. package/rules/content/voice.yaml +144 -0
  25. package/rules/content/writing.yaml +202 -0
  26. package/rules/data/HYPOTHESES.md +11 -0
  27. package/rules/data/_area.yaml +7 -0
  28. package/rules/data/charts.yaml +189 -0
  29. package/rules/data/dashboards.yaml +141 -0
  30. package/rules/data/review.yaml +159 -0
  31. package/rules/graphic/HYPOTHESES.md +18 -0
  32. package/rules/graphic/_area.yaml +8 -0
  33. package/rules/graphic/identity.yaml +141 -0
  34. package/rules/graphic/pieces.yaml +164 -0
  35. package/rules/graphic/review.yaml +271 -0
  36. package/rules/graphic/symbol.yaml +141 -0
  37. package/rules/motion/HYPOTHESES.md +19 -0
  38. package/rules/motion/_area.yaml +7 -0
  39. package/rules/motion/micro.yaml +143 -0
  40. package/rules/motion/review.yaml +347 -0
  41. package/rules/motion/transitions.yaml +169 -0
  42. package/rules/typography/HYPOTHESES.md +12 -0
  43. package/rules/typography/_area.yaml +8 -0
  44. package/rules/typography/adapt.yaml +45 -0
  45. package/rules/typography/create.yaml +126 -0
  46. package/rules/typography/review.yaml +127 -0
  47. package/rules/ui/HYPOTHESES.md +23 -0
  48. package/rules/ui/_area.yaml +9 -0
  49. package/rules/ui/compose.yaml +246 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +400 -0
  52. package/rules/ui/states.yaml +257 -0
  53. package/rules/ux/HYPOTHESES.md +13 -0
  54. package/rules/ux/_area.yaml +8 -0
  55. package/rules/ux/flows.yaml +164 -0
  56. package/rules/ux/forms.yaml +142 -0
  57. package/rules/ux/review.yaml +186 -0
  58. package/skills/lazuli/SKILL.md +183 -0
  59. package/skills/lazuli/procedures/create.md +29 -0
  60. package/skills/lazuli/procedures/explain-decisions.md +22 -0
  61. package/skills/lazuli/procedures/improve.md +30 -0
  62. package/skills/lazuli/procedures/remember-this.md +41 -0
  63. package/skills/lazuli/procedures/review-design.md +36 -0
  64. package/skills/lazuli/procedures/show-options.md +33 -0
  65. package/skills/lazuli-accessibility-check/SKILL.md +68 -0
  66. package/skills/lazuli-color-context-and-culture/SKILL.md +53 -0
  67. package/skills/lazuli-color-context-and-culture/references/sectors.md +26 -0
  68. package/skills/lazuli-color-palette-by-intent/SKILL.md +54 -0
  69. package/skills/lazuli-color-palette-by-intent/references/intent-chords.md +51 -0
  70. package/skills/lazuli-color-screen-review/SKILL.md +51 -0
  71. package/skills/lazuli-color-states-and-signals/SKILL.md +53 -0
  72. package/skills/lazuli-content-interface-writing/SKILL.md +53 -0
  73. package/skills/lazuli-content-voice/SKILL.md +40 -0
  74. package/skills/lazuli-data-charts-and-dashboards/SKILL.md +59 -0
  75. package/skills/lazuli-graphic-derived-pieces/SKILL.md +40 -0
  76. package/skills/lazuli-graphic-derived-pieces/references/piece-template.html +24 -0
  77. package/skills/lazuli-graphic-identity/SKILL.md +45 -0
  78. package/skills/lazuli-motion-micro-and-transitions/SKILL.md +49 -0
  79. package/skills/lazuli-typography-choose-and-pair/SKILL.md +50 -0
  80. package/skills/lazuli-typography-screen-review/SKILL.md +51 -0
  81. package/skills/lazuli-ui-composition/SKILL.md +42 -0
  82. package/skills/lazuli-ui-composition/references/option-template.html +34 -0
  83. package/skills/lazuli-ui-layout-review/SKILL.md +47 -0
  84. package/skills/lazuli-ui-states-and-system/SKILL.md +54 -0
  85. package/skills/lazuli-ux-flows-and-forms/SKILL.md +51 -0
  86. package/skills/lazuli-ux-task-test/SKILL.md +44 -0
  87. package/src/browser.mjs +162 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +463 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +160 -0
  93. package/src/commands/draft-memo.mjs +162 -0
  94. package/src/commands/hooks.mjs +345 -0
  95. package/src/commands/install-hooks.mjs +120 -0
  96. package/src/commands/install.mjs +132 -0
  97. package/src/commands/list-rules.mjs +49 -0
  98. package/src/commands/map-page.mjs +594 -0
  99. package/src/commands/record-answers.mjs +79 -0
  100. package/src/commands/record-log.mjs +325 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +227 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +391 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +566 -0
  108. package/src/measure/chart-read.mjs +401 -0
  109. package/src/measure/chart.mjs +264 -0
  110. package/src/measure/coherence.mjs +145 -0
  111. package/src/measure/color.mjs +86 -0
  112. package/src/measure/content.mjs +82 -0
  113. package/src/measure/cvd.mjs +24 -0
  114. package/src/measure/extreme.mjs +241 -0
  115. package/src/measure/forms.mjs +150 -0
  116. package/src/measure/in-page/a11y.js +522 -0
  117. package/src/measure/in-page/color.js +348 -0
  118. package/src/measure/in-page/composition.js +1496 -0
  119. package/src/measure/in-page/contrast.js +15 -0
  120. package/src/measure/in-page/cvd.js +173 -0
  121. package/src/measure/in-page/extreme.js +377 -0
  122. package/src/measure/in-page/frames.js +781 -0
  123. package/src/measure/in-page/look.js +28 -0
  124. package/src/measure/in-page/motion-probe.js +171 -0
  125. package/src/measure/in-page/style.js +107 -0
  126. package/src/measure/in-page/svg-strokes.js +112 -0
  127. package/src/measure/in-page/svg-uses.js +50 -0
  128. package/src/measure/in-page/symbol.js +123 -0
  129. package/src/measure/in-page/type.js +269 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +100 -0
  132. package/src/measure/motion.mjs +509 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +253 -0
  135. package/src/measure/rhythm.mjs +81 -0
  136. package/src/measure/signature.mjs +65 -0
  137. package/src/measure/states.mjs +240 -0
  138. package/src/measure/style.mjs +13 -0
  139. package/src/measure/symbol.mjs +268 -0
  140. package/src/measure/terms.mjs +153 -0
  141. package/src/measure/tiles.mjs +20 -0
  142. package/src/measure/timeline.mjs +621 -0
  143. package/src/measure/type.mjs +167 -0
  144. package/src/measure/weight.mjs +18 -0
  145. package/src/private-strings.mjs +81 -0
  146. package/src/project/blind.mjs +70 -0
  147. package/src/project/edits.mjs +154 -0
  148. package/src/project/gate.mjs +168 -0
  149. package/src/project/lazuli-md.mjs +521 -0
  150. package/src/project/log.mjs +335 -0
  151. package/src/project/match.mjs +200 -0
  152. package/src/project/records.mjs +380 -0
  153. package/src/project/tasks.mjs +153 -0
  154. package/src/report/evaluate.mjs +27 -0
  155. package/src/report/evaluators/a11y.mjs +227 -0
  156. package/src/report/evaluators/chart.mjs +151 -0
  157. package/src/report/evaluators/coherence.mjs +103 -0
  158. package/src/report/evaluators/color.mjs +133 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +87 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +103 -0
  163. package/src/report/evaluators/motion.mjs +280 -0
  164. package/src/report/evaluators/piece.mjs +69 -0
  165. package/src/report/evaluators/rhythm.mjs +99 -0
  166. package/src/report/evaluators/states.mjs +39 -0
  167. package/src/report/evaluators/style.mjs +35 -0
  168. package/src/report/evaluators/symbol.mjs +110 -0
  169. package/src/report/evaluators/terms.mjs +49 -0
  170. package/src/report/evaluators/type.mjs +166 -0
  171. package/src/report/evaluators/weight.mjs +51 -0
  172. package/src/report/evidence.mjs +4 -0
  173. package/src/report/finding.mjs +11 -0
  174. package/src/report/format.mjs +215 -0
  175. package/src/rules/hypotheses.mjs +28 -0
  176. package/src/rules/load.mjs +274 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +220 -0
  179. package/templates/LAZULI.md +88 -0
@@ -0,0 +1,227 @@
1
+ import fs from "node:fs/promises";
2
+ import { existsSync, statSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { VIEWPORT_HEIGHT, openBrowser, openTarget } from "../browser.mjs";
5
+ import { FULL_PAGE_CAP_PX } from "./capture.mjs";
6
+ import { checkHeight } from "./check-design.mjs";
7
+ import { baselineName, signatureAt } from "./compare-designs.mjs";
8
+ import { distance } from "../measure/signature.mjs";
9
+ import { measureLayout } from "../measure/layout.mjs";
10
+ import { MEASURERS } from "../measure/registry.mjs";
11
+ import { readLazuliMd } from "../project/lazuli-md.mjs";
12
+ import { applyBreaks, applyDeclarations, matchGoals, sameTarget } from "../project/match.mjs";
13
+ import { evaluate } from "../report/evaluate.mjs";
14
+ import { KIT_RULES_DIR, loadKit } from "../rules/load.mjs";
15
+
16
+ // show-options asks for 6 to 9 alternatives.
17
+ const MIN_OPTIONS = 6;
18
+ const MAX_OPTIONS = 9;
19
+ // Contact sheet layout, not a rule: the sheet page width in px and thumbnails per row.
20
+ const SHEET_PX = 1440;
21
+ const PER_ROW = 3;
22
+
23
+ export class OptionsInputError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "OptionsInputError";
27
+ this.code = "OPTIONS_INPUT";
28
+ }
29
+ }
30
+
31
+ const show = (v, unit = "") => (v === null || v === undefined ? "n/a" : `${v}${unit}`);
32
+
33
+ // One line under a thumbnail: the measures the agent reads to name scale, empty space, focal point and tension.
34
+ // The sheet gives no ranking and no combined score.
35
+ // A failed rule is never hidden: fails, breaks and declared moves are named next to the hints. A crop note, when given, is a third line.
36
+ export function optionLabel(layout, findings, note, screensLine, distanceLine) {
37
+ const f = layout.focal;
38
+ const focal = f ? `focal ${f.selector} ${show(f.dominance, "x")} at (${show(f.x)}, ${show(f.y)})` : "focal none";
39
+ const empty = layout.emptyShare === null ? "n/a" : `${Math.round(layout.emptyShare * 100)}%`;
40
+ const ids = (level) => [...new Set(findings.filter((x) => x.level === level).map((x) => x.ruleId))];
41
+ const named = [["fails", ids("fail")], ["breaks", ids("break")], ["declared", ids("declared")], ["hints", ids("hint")]]
42
+ .filter(([, list]) => list.length)
43
+ .map(([word, list]) => `${word} ${list.join(", ")}`);
44
+ return [
45
+ `scale ${show(layout.textRatio, "x")} text, ${show(layout.areaRatio, "x")} area; empty ${empty}, spread ${show(layout.emptySpread)}; ${focal}`,
46
+ named.length ? named.join("; ") : "no hints",
47
+ ...(note ? [note] : []),
48
+ ...(screensLine ? [screensLine] : []),
49
+ ...(distanceLine ? [distanceLine] : []),
50
+ ];
51
+ }
52
+
53
+ // The label line of a thumbnail that shows more than the first view; null for one screen.
54
+ export const screensNote = (screens, height) =>
55
+ screens > 1 ? `thumbnail shows ${screens} screens of ${height} px; measures read the first view` : null;
56
+
57
+ // Why the earlier measures at a width were dropped: the option files changed, or only the height did.
58
+ export const droppedLine = (r, w) =>
59
+ r.droppedReason === "height"
60
+ ? `The earlier measures at ${w} px were read at ${r.droppedHeight} px, not ${r.height} px; they were dropped.`
61
+ : `Option files changed since the last run; the earlier measures at ${w} px were dropped.`;
62
+
63
+ // The option canvas has its own width; rendered narrower, the view is a crop of it.
64
+ export const cropNote = (width) => `The option is wider than ${width} px; this view is a crop and its bleeds are not meaningful.`;
65
+ // The canvas is the body or html box, not the scroll width: a block that bleeds on purpose does not widen it.
66
+ const canvasWidth = (page) =>
67
+ page.evaluate(() => Math.max(document.body ? document.body.getBoundingClientRect().width : 0, document.documentElement.getBoundingClientRect().width));
68
+
69
+ const escape = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
70
+
71
+ function sheetHtml(width, cells) {
72
+ const items = cells
73
+ .map((c) => `<figure><img src="data:image/png;base64,${c.png.toString("base64")}" alt=""><figcaption><b>${escape(c.file)}</b>${c.lines.map((l) => `<span>${escape(l)}</span>`).join("")}</figcaption></figure>`)
74
+ .join("");
75
+ return `<!doctype html><html><head><meta charset="utf-8"><style>
76
+ html, body { margin: 0; background: #fff; color: #111; }
77
+ body { font: 14px/1.4 monospace; padding: 24px; }
78
+ h1 { font-size: 16px; margin: 0 0 16px; }
79
+ main { display: grid; grid-template-columns: repeat(${PER_ROW}, 1fr); gap: 24px; }
80
+ figure { margin: 0; }
81
+ img { display: block; width: 100%; border: 1px solid #ccc; }
82
+ figcaption { margin-top: 8px; display: flex; flex-direction: column; gap: 2px; }
83
+ </style></head><body><h1>Options at ${width} px, in file order (no ranking)</h1><main>${items}</main></body></html>`;
84
+ }
85
+
86
+ // The option files of the folder; a baseline kept in the folder is not an option (as compare-designs --options).
87
+ async function optionFiles(folder, baseline, cwd) {
88
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) throw new OptionsInputError(`Options folder not found: ${folder}`);
89
+ const entries = await fs.readdir(folder, { withFileTypes: true });
90
+ const files = entries
91
+ .filter((e) => e.isFile() && /\.html$/i.test(e.name))
92
+ .map((e) => e.name)
93
+ .sort()
94
+ .filter((name) => !baseline || !sameTarget(path.join(folder, name), baseline, cwd));
95
+ if (files.length < MIN_OPTIONS || files.length > MAX_OPTIONS) {
96
+ throw new OptionsInputError(`Found ${files.length} option files in ${folder}; show-options needs ${MIN_OPTIONS} to ${MAX_OPTIONS}.`);
97
+ }
98
+ return files;
99
+ }
100
+
101
+ // The earlier options.json of the folder, or null when there is none or it cannot be read.
102
+ async function readEarlier(jsonPath) {
103
+ try {
104
+ const prev = JSON.parse(await fs.readFile(jsonPath, "utf8"));
105
+ return Array.isArray(prev?.options) && prev.options.every((o) => typeof o?.file === "string") ? prev : null;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ // The first `screens` viewport heights of the page, cut at the page end.
112
+ async function screensClip(page, width, height, screens) {
113
+ const pageHeight = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, innerHeight));
114
+ return { x: 0, y: 0, width, height: Math.min(pageHeight, screens * height) };
115
+ }
116
+
117
+ // Renders and measures the option files of a folder and writes one contact sheet per width.
118
+ // Measures of widths rendered in an earlier run are kept when the option files are the same ones, and dropped otherwise.
119
+ // The CLI renders and measures; choosing is the agent's or the person's job.
120
+ export async function renderOptions({ folder: given, widths = [1440], height = VIEWPORT_HEIGHT, screens = 1, cwd = process.cwd(), browser: givenBrowser, rules: givenRules, baseline }) {
121
+ checkHeight(height);
122
+ if (!Number.isInteger(screens) || screens < 1) throw new OptionsInputError("--screens needs a whole number of 1 or more.");
123
+ if (screens * height > FULL_PAGE_CAP_PX) throw new OptionsInputError(`--screens ${screens} at ${height} px is taller than ${FULL_PAGE_CAP_PX} px.`);
124
+ const folder = path.resolve(cwd, given);
125
+ const files = await optionFiles(folder, baseline, cwd);
126
+ const all = givenRules ?? (await loadKit({ dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR], projectDir: path.join(cwd, ".lazuli", "rules") })).rules;
127
+ const rules = all.filter((r) => typeof r.measure === "string" && r.measure.startsWith("layout."));
128
+ // The breaks and declared moves of LAZULI.md apply to each option file through the goals that cover it (an options goal's glob).
129
+ const md = await readLazuliMd(cwd);
130
+ const knownIds = new Set(all.map((r) => r.id));
131
+ const declared = (findings, file) => {
132
+ if (!md) return findings;
133
+ const goals = matchGoals(md, file, cwd);
134
+ return applyDeclarations(applyBreaks(findings, md.breaks, goals, all, knownIds, file, cwd).findings, md, goals, all, file, cwd).findings;
135
+ };
136
+
137
+ const jsonPath = path.join(folder, "options.json");
138
+ const prev = await readEarlier(jsonPath);
139
+ const prevWidths = prev ? [...new Set(Object.values(prev.options).flatMap((o) => Object.keys(o.measures ?? {})).map(Number))] : [];
140
+ // An options.json written before heights were recorded was rendered at the default height.
141
+ const filesMatch = prev !== null && prev.options.length === files.length && prev.options.every((o, i) => o.file === files[i]);
142
+ const prevHeight = prev?.height ?? VIEWPORT_HEIGHT;
143
+ const sameFiles = filesMatch && prevHeight === height;
144
+ const earlier = prevWidths.filter((w) => !widths.includes(w));
145
+ const kept = sameFiles ? earlier : [];
146
+ const dropped = prev && !sameFiles ? earlier : [];
147
+ const droppedWhy = dropped.length === 0 ? {} : filesMatch ? { droppedReason: "height", droppedHeight: prevHeight } : { droppedReason: "files" };
148
+ // The screens each width was rendered with: a kept width keeps its own (a 1.0.1 file holds one value for all).
149
+ const screensAt = {};
150
+ for (const w of kept) screensAt[String(w)] = prev.screensAt?.[String(w)] ?? prev.screens ?? 1;
151
+ for (const w of widths) screensAt[String(w)] = screens;
152
+
153
+ const thumbs = path.join(folder, "thumbs");
154
+ await fs.mkdir(thumbs, { recursive: true });
155
+ const options = files.map((file, i) => {
156
+ const old = sameFiles ? prev.options[i] : null;
157
+ const option = { file, measures: {}, findings: [], notes: {} };
158
+ for (const w of kept) {
159
+ if (old.measures?.[String(w)]) option.measures[String(w)] = old.measures[String(w)];
160
+ if (old.notes?.[String(w)]) option.notes[String(w)] = old.notes[String(w)];
161
+ option.findings.push(...(old.findings ?? []).filter((f) => f.width === w));
162
+ }
163
+ return option;
164
+ });
165
+ const baselineSigs = new Map();
166
+ const pngs = new Map();
167
+ const sheets = {};
168
+ // A kept sheet whose file is gone is dropped from sheets and named, so the width can be run again.
169
+ const missingSheets = [];
170
+ for (const w of kept) {
171
+ const file = prev.sheets?.[String(w)];
172
+ if (!file) continue;
173
+ if (existsSync(file)) sheets[String(w)] = file;
174
+ else missingSheets.push(w);
175
+ }
176
+ const browser = givenBrowser ?? (await openBrowser());
177
+ try {
178
+ for (const option of options) {
179
+ const name = path.basename(option.file, path.extname(option.file));
180
+ for (const width of widths) {
181
+ const file = path.join(folder, option.file);
182
+ const page = await openTarget(browser, file, width, { cwd, height });
183
+ try {
184
+ const layout = await measureLayout(page, { options: true });
185
+ if ((await canvasWidth(page)) > width) option.notes[String(width)] = cropNote(width);
186
+ const png = screens === 1 ? await page.screenshot() : await page.screenshot({ fullPage: true, clip: await screensClip(page, width, height, screens) });
187
+ await fs.writeFile(path.join(thumbs, `${name}-${width}.png`), png);
188
+ pngs.set(`${option.file}|${width}`, png);
189
+ option.measures[String(width)] = layout;
190
+ if (baseline) {
191
+ // The baseline is read once per width, not once per option.
192
+ if (!baselineSigs.has(width)) baselineSigs.set(width, await signatureAt(browser, baseline, width, cwd, height));
193
+ const d = distance(await signatureAt(browser, file, width, cwd, height), baselineSigs.get(width));
194
+ (option.distances ??= {})[String(width)] = `distance ${d.value} from ${baselineName(baseline)} (H1)`;
195
+ }
196
+ option.findings.push(...declared(evaluate(rules, [{ width, layout }], MEASURERS), file));
197
+ } finally {
198
+ await page.context().close();
199
+ }
200
+ }
201
+ }
202
+ for (const width of widths) {
203
+ const cells = options.map((o) => ({
204
+ file: o.file,
205
+ png: pngs.get(`${o.file}|${width}`),
206
+ lines: optionLabel(o.measures[String(width)], o.findings.filter((f) => f.width === width), o.notes[String(width)], screensNote(screens, height), o.distances?.[String(width)]),
207
+ }));
208
+ const context = await browser.newContext({ viewport: { width: SHEET_PX, height: 900 } });
209
+ try {
210
+ const page = await context.newPage();
211
+ await page.setContent(sheetHtml(width, cells), { waitUntil: "load" });
212
+ const file = path.join(folder, `sheet-${width}.png`);
213
+ await page.screenshot({ path: file, fullPage: true });
214
+ sheets[String(width)] = file;
215
+ } finally {
216
+ await context.close();
217
+ }
218
+ }
219
+ } finally {
220
+ if (!givenBrowser) await browser.close();
221
+ }
222
+
223
+ const allWidths = [...new Set([...(sameFiles ? prevWidths : []), ...widths])];
224
+ const result = { folder, widths: allWidths, height, screens, screensAt, ...(baseline ? { baselineHeight: height } : {}), kept, dropped, ...droppedWhy, missingSheets, options, sheets, jsonPath };
225
+ await fs.writeFile(jsonPath, JSON.stringify(result, null, 2));
226
+ return result;
227
+ }
@@ -0,0 +1,32 @@
1
+ import { copyFile, access, readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const TEMPLATE = fileURLToPath(new URL("../../templates/LAZULI.md", import.meta.url));
6
+
7
+ export const MODES = ["director", "delegate"];
8
+
9
+ // mode (director or delegate) replaces the first non-empty line after "## Mode" in the copied template.
10
+ export async function startProject({ cwd = process.cwd(), mode } = {}) {
11
+ if (mode !== undefined && !MODES.includes(mode)) {
12
+ throw new Error("mode must be director or delegate.");
13
+ }
14
+ const path = join(cwd, "LAZULI.md");
15
+ try {
16
+ await access(path);
17
+ return { created: false, path };
18
+ } catch {
19
+ // not there yet
20
+ }
21
+ await copyFile(TEMPLATE, path, 1); // COPYFILE_EXCL: never overwrite, even in a race
22
+ if (mode !== undefined) {
23
+ const lines = (await readFile(path, "utf8")).split("\n");
24
+ const heading = lines.findIndex((l) => l.trim() === "## Mode");
25
+ const at = heading === -1 ? -1 : lines.findIndex((l, i) => i > heading && l.trim() !== "");
26
+ if (at !== -1) {
27
+ lines[at] = mode;
28
+ await writeFile(path, lines.join("\n"));
29
+ }
30
+ }
31
+ return { created: true, path };
32
+ }
@@ -0,0 +1,391 @@
1
+ import fs from "node:fs/promises";
2
+ import { cdpSession } from "../browser.mjs";
3
+
4
+ // Sampling limits, not rule cutoffs. The report notes when one of them limits the result.
5
+ // How many visible interactive elements are measured for target size.
6
+ const MAX_TARGETS = 3000;
7
+ // Unnamed controls, images and generic links kept in the report, each list on its own.
8
+ const MAX_LISTED = 50;
9
+ // Unnamed images looked at before the decorative ones are filtered out and the list is cut to MAX_LISTED;
10
+ // also the large images read for decorative marks.
11
+ const MAX_IMAGE_CANDIDATES = 1000;
12
+ // DevTools calls in flight at once.
13
+ const CDP_BATCH = 50;
14
+ const GLOBAL_KEY = "__lazuliA11y";
15
+ // Keyboard pass: Tab presses tried before the report says the rest was not looked at.
16
+ const MAX_TAB_STOPS = 20;
17
+ // Margin around the focused element's box in the picture compared with and without focus, in CSS px.
18
+ const FOCUS_CLIP_GROW = 8;
19
+ // Pairs of pictures (without and with focus) taken per element before it is left not judged.
20
+ const FOCUS_PAIRS = 3;
21
+ // Wall-clock limit of the keyboard passes of one check, shared by all widths, so a page that keeps producing
22
+ // new focus targets cannot run the check out of time.
23
+ const FOCUS_TOTAL_BUDGET_MS = 45_000;
24
+ // Waits after each key: two frames, then running transitions, each capped.
25
+ const FRAME_WAIT_CAP_MS = 1_000;
26
+ const ANIMATION_WAIT_CAP_MS = 500;
27
+ // Elements looked at by the reflow and text spacing passes, and text blocks compared pairwise for overlap.
28
+ const MAX_SCANNED = 20_000;
29
+ const MAX_TEXT_BLOCKS = 600;
30
+
31
+ // Roles that need a name to be usable (WCAG 4.1.2). Names come from Chrome's accessibility tree,
32
+ // so aria-label, title, aria-labelledby, labels and visually hidden text all count.
33
+ const NAMED_ROLES = new Set([
34
+ "button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox", "listbox",
35
+ "menuitem", "tab", "switch", "slider", "spinbutton",
36
+ ]);
37
+
38
+ let script;
39
+
40
+ // Lowercase, collapsed whitespace, no punctuation or symbols at either end ("Click here >>" is "click here").
41
+ export const normalizePhrase = (s) => s.toLowerCase().replace(/\s+/g, " ").replace(/^[\s\p{P}\p{S}]+|[\s\p{P}\p{S}]+$/gu, "");
42
+
43
+ const thresholdOf = (ctx, id) => (ctx?.rules ?? []).find((r) => r.measure === id)?.threshold;
44
+
45
+ // Describes the DOM nodes the accessibility tree lists, through the protocol.
46
+ async function describeNodes(client, backendIds) {
47
+ const out = new Array(backendIds.length).fill(null);
48
+ for (let i = 0; i < backendIds.length; i += CDP_BATCH) {
49
+ await Promise.all(
50
+ backendIds.slice(i, i + CDP_BATCH).map(async (backendNodeId, k) => {
51
+ try {
52
+ const { object } = await client.send("DOM.resolveNode", { backendNodeId });
53
+ const { result } = await client.send("Runtime.callFunctionOn", {
54
+ objectId: object.objectId,
55
+ functionDeclaration: `function () { return globalThis.${GLOBAL_KEY}.infoOf(this); }`,
56
+ returnByValue: true,
57
+ });
58
+ out[i + k] = result.value ?? null;
59
+ } catch {
60
+ out[i + k] = null; // a node that went away between the two calls
61
+ }
62
+ }),
63
+ );
64
+ }
65
+ return out;
66
+ }
67
+
68
+ async function axReport(page, phrases) {
69
+ const client = await cdpSession(page);
70
+ try {
71
+ await client.send("DOM.enable");
72
+ await client.send("DOM.getDocument", { depth: 0 });
73
+ await client.send("Accessibility.enable");
74
+ const { nodes } = await client.send("Accessibility.getFullAXTree");
75
+ const nameOf = (n) => String(n.name?.value ?? "").trim();
76
+ const live = nodes.filter((n) => !n.ignored && n.backendDOMNodeId != null);
77
+ const unnamed = live.filter((n) => NAMED_ROLES.has(n.role?.value) && nameOf(n) === "");
78
+ const imageNodes = live.filter((n) => n.role?.value === "image" && nameOf(n) === "");
79
+ const generic = phrases.length
80
+ ? live.filter((n) => n.role?.value === "link" && phrases.includes(normalizePhrase(nameOf(n))))
81
+ : [];
82
+ const [u, im, g] = await Promise.all(
83
+ [unnamed.slice(0, MAX_LISTED), imageNodes.slice(0, MAX_IMAGE_CANDIDATES), generic.slice(0, MAX_LISTED)].map((list) =>
84
+ describeNodes(client, list.map((n) => n.backendDOMNodeId)),
85
+ ),
86
+ );
87
+ // The cap on images applies after the decorative ones and the non-images are filtered out.
88
+ const missing = imageNodes
89
+ .slice(0, MAX_IMAGE_CANDIDATES)
90
+ .map((n, i) => im[i])
91
+ .filter((info) => info && info.isImage && !info.decorative);
92
+ return {
93
+ unnamed: unnamed.slice(0, MAX_LISTED).map((n, i) => ({ role: n.role.value, selector: u[i]?.selector ?? "(unknown)" })),
94
+ images: missing.slice(0, MAX_LISTED).map((info) => ({ selector: info.selector, src: info.src.slice(0, 200) })),
95
+ genericLinks: generic.slice(0, MAX_LISTED).map((n, i) => ({ selector: g[i]?.selector ?? "(unknown)", text: nameOf(n) })),
96
+ counts: { unnamed: unnamed.length, images: missing.length, generic: generic.length, imageNodes: imageNodes.length },
97
+ };
98
+ } finally {
99
+ await client.detach().catch(() => {});
100
+ }
101
+ }
102
+
103
+ const call = (expr) => `globalThis.${GLOBAL_KEY}.${expr}`;
104
+
105
+ // Puts the in-page probes on a page of its own (no page-wide measurements).
106
+ async function installProbes(page) {
107
+ const opts = { globalKey: GLOBAL_KEY, minPx: null, maxTargets: 0, clipGrow: FOCUS_CLIP_GROW, helpersOnly: true };
108
+ await page.evaluate(`(${script})(${JSON.stringify(opts)})`);
109
+ }
110
+
111
+ // Two animation frames, then any running transition or animation (capped).
112
+ const settle = (page) =>
113
+ page.evaluate(
114
+ async ({ frameCap, animCap }) => {
115
+ const frames = new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
116
+ await Promise.race([frames, new Promise((r) => setTimeout(r, frameCap))]);
117
+ const running = document
118
+ .getAnimations()
119
+ .filter((a) => a.playState === "running" && Number.isFinite(a.effect?.getComputedTiming?.().endTime));
120
+ await Promise.race([Promise.allSettled(running.map((a) => a.finished)), new Promise((r) => setTimeout(r, animCap))]);
121
+ },
122
+ { frameCap: FRAME_WAIT_CAP_MS, animCap: ANIMATION_WAIT_CAP_MS },
123
+ );
124
+
125
+ // WCAG 2.4.7 and 2.4.11: Tab through the page; for each new element compare a picture of its box with and
126
+ // without focus, and test whether anything else covers all of it. Stops on a repeat, a trap, nothing
127
+ // focusable, MAX_TAB_STOPS presses or the shared time budget. Tab presses spent inside a frame count as
128
+ // presses but not as stops (the page only sees the frame element).
129
+ async function focusReport(page, notes, budget) {
130
+ const started = Date.now();
131
+ try {
132
+ return await focusPass(page, notes, budget, started);
133
+ } finally {
134
+ budget.spentMs += Date.now() - started;
135
+ }
136
+ }
137
+
138
+ // Pictures compared with and without focus: CSS animations and transitions frozen, and content that
139
+ // paints on its own (canvas, video, frames) hidden in both, so only the focus change can differ.
140
+ const shot = (page, clip) =>
141
+ page.screenshot({ clip, type: "png", animations: "disabled", style: "canvas, video, iframe, embed, object { visibility: hidden !important; }" });
142
+
143
+ async function focusPass(page, notes, budget, started) {
144
+ await installProbes(page);
145
+ // Style changes land at once, so the indicator styles compared in-page are the final ones.
146
+ await page.addStyleTag({ content: "*, *::before, *::after { transition: none !important; }" });
147
+ // Timers the page already runs (a clock, a ticker, a carousel autoplay) stop, so the pictures change only
148
+ // with focus. Chrome numbers timers in one sequence; timers the page starts later (on focus) still run.
149
+ await page.evaluate(() => {
150
+ const last = setTimeout(() => {}, 0);
151
+ for (let id = 1; id <= last; id += 1) {
152
+ clearTimeout(id);
153
+ clearInterval(id);
154
+ }
155
+ });
156
+ const out = { checked: 0, judged: 0, invisible: [], obscured: [] };
157
+ let unstable = 0;
158
+ const spent = () => budget.spentMs + (Date.now() - started);
159
+
160
+ const visit = async (s) => {
161
+ out.checked += 1;
162
+ const who = { selector: s.selector, label: s.label };
163
+ if (s.obscured) out.obscured.push(who);
164
+ if (!s.clip) return;
165
+ await page.evaluate(call("blurFocus()"));
166
+ await settle(page);
167
+ // Grown to the box that carries the indicator when it is not the element itself (a card ring, a stretched link).
168
+ const clip = await page.evaluate(call(`focusClip(${JSON.stringify({ clip: s.clip })})`));
169
+ const pair = async (first) => {
170
+ if (!first) {
171
+ await page.evaluate(call("blurFocus()"));
172
+ await settle(page);
173
+ }
174
+ const without = await shot(page, clip);
175
+ await page.evaluate(call("refocus()"));
176
+ await settle(page);
177
+ return { without, withFocus: await shot(page, clip) };
178
+ };
179
+ // Equal pictures mean no indicator. A difference counts only when the next pair repeats it exactly;
180
+ // a first picture caught while the page was still repainting is replaced by the next pair. Pairs that
181
+ // keep changing (something moving on its own) leave the element not judged.
182
+ let prev = null;
183
+ for (let k = 0; k < FOCUS_PAIRS; k += 1) {
184
+ const p = await pair(k === 0);
185
+ if (p.withFocus.equals(p.without)) {
186
+ out.judged += 1;
187
+ out.invisible.push(who);
188
+ return;
189
+ }
190
+ if (prev && prev.without.equals(p.without) && prev.withFocus.equals(p.withFocus)) {
191
+ out.judged += 1;
192
+ return;
193
+ }
194
+ prev = p;
195
+ }
196
+ unstable += 1;
197
+ };
198
+
199
+ // An element focused on load (autofocus) is a stop before any key is pressed.
200
+ const first = await page.evaluate(call("focusProbe()"));
201
+ if (first.kind === "new") await visit(first);
202
+
203
+ let limited = true;
204
+ let outOfTime = false;
205
+ let idle = 0;
206
+ for (let press = 0; press < MAX_TAB_STOPS; press += 1) {
207
+ if (spent() > FOCUS_TOTAL_BUDGET_MS) {
208
+ notes.push(`The keyboard focus check stopped at its ${FOCUS_TOTAL_BUDGET_MS / 1000} s limit (shared by all widths), with ${out.checked} elements checked at this width.`);
209
+ limited = false;
210
+ outOfTime = true;
211
+ break;
212
+ }
213
+ await page.keyboard.press("Tab");
214
+ await settle(page);
215
+ const s = await page.evaluate(call("focusProbe()"));
216
+ if (s.kind === "none") {
217
+ // Focus left the document after the last stop, or the page has nothing the Tab key reaches.
218
+ idle += 1;
219
+ if (out.checked > 0 || idle >= 2) {
220
+ limited = false;
221
+ break;
222
+ }
223
+ continue;
224
+ }
225
+ if (s.kind === "frame") continue;
226
+ if (s.kind === "same") {
227
+ notes.push(`Keyboard focus stayed on ${s.selector} when Tab was pressed (a possible keyboard trap), so the focus check stopped after ${out.checked} ${out.checked === 1 ? "element" : "elements"}.`);
228
+ limited = false;
229
+ break;
230
+ }
231
+ if (s.kind === "seen") {
232
+ limited = false;
233
+ break;
234
+ }
235
+ await visit(s);
236
+ }
237
+ if (limited) {
238
+ // The cap only matters when one more press would still reach something new.
239
+ await page.keyboard.press("Tab");
240
+ await settle(page);
241
+ const more = await page.evaluate(call("focusProbe()"));
242
+ if (more.kind === "new" || more.kind === "frame") notes.push(`The keyboard focus check looked at the first ${MAX_TAB_STOPS} Tab presses only.`);
243
+ }
244
+ if (unstable > 0) {
245
+ notes.push(`${unstable} focused ${unstable === 1 ? "element was" : "elements were"} not compared because the picture around ${unstable === 1 ? "it" : "them"} kept changing without focus.`);
246
+ }
247
+ if (out.judged === 0) {
248
+ notes.push(out.checked === 0 && !outOfTime
249
+ ? "No element took keyboard focus when Tab was pressed, so focus visibility was not judged."
250
+ : `No focused element was compared with and without focus (${out.checked} reached with the Tab key), so focus visibility was not judged.`);
251
+ }
252
+ return out;
253
+ }
254
+
255
+ // WCAG 1.4.10: the document at `width` px, and the outermost boxes that reach past it.
256
+ // Animations still moving boxes would make the result depend on timing: the page opens with reduced
257
+ // motion, finite animations jump to their end state, endless ones (a spinning badge) are held at their
258
+ // first frame, and only boxes past the width in two measurements a few frames apart count.
259
+ async function reflowReport(ctx, width, notes) {
260
+ const page = await ctx.openPage({ width, still: true });
261
+ await installProbes(page);
262
+ const held = await page.evaluate(() => {
263
+ let endless = 0;
264
+ for (const a of document.getAnimations()) {
265
+ try {
266
+ if (Number.isFinite(a.effect?.getComputedTiming?.().endTime)) a.finish();
267
+ else {
268
+ a.pause();
269
+ a.currentTime = 0;
270
+ endless += 1;
271
+ }
272
+ } catch { /* an animation that cannot be moved keeps running */ }
273
+ }
274
+ return endless;
275
+ });
276
+ if (held > 0) notes.push(`Reflow measured ${held} endless ${held === 1 ? "animation" : "animations"} at ${held === 1 ? "its" : "their"} first frame.`);
277
+ const probe = () => page.evaluate(call(`reflowProbe(${JSON.stringify({ width, maxScanned: MAX_SCANNED })})`));
278
+ await settle(page);
279
+ const first = await probe();
280
+ await settle(page);
281
+ const r = await probe();
282
+ const offenders = r.offenders.filter((sel) => first.offenders.includes(sel));
283
+ if (r.total > r.scanned) notes.push(`Reflow looked at the first ${r.scanned} of ${r.total} elements.`);
284
+ if (offenders.length > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${offenders.length} elements wider than ${width} px.`);
285
+ return { width, scrollWidth: Math.min(first.scrollWidth, r.scrollWidth), offenders: offenders.slice(0, MAX_LISTED) };
286
+ }
287
+
288
+ // WCAG 1.4.12: the four spacing values forced on a fresh page, compared with the same page before.
289
+ async function textSpacingReport(ctx, t, notes) {
290
+ const page = await ctx.openPage();
291
+ await installProbes(page);
292
+ const css =
293
+ `*, *::before, *::after { line-height: ${t.lineHeight} !important; letter-spacing: ${t.letterSpacing}em !important; word-spacing: ${t.wordSpacing}em !important; }` +
294
+ ` p { margin-bottom: ${t.paragraphSpacing}em !important; }`;
295
+ const r = await page.evaluate(call(`spacingProbe(${JSON.stringify({ css, maxScanned: MAX_SCANNED, maxBlocks: MAX_TEXT_BLOCKS })})`));
296
+ if (r.total > r.scanned) notes.push(`Text spacing looked at the first ${r.scanned} of ${r.total} elements.`);
297
+ if (r.totalBlocks > r.blocks) notes.push(`Text spacing compared the first ${r.blocks} of ${r.totalBlocks} text blocks for overlap.`);
298
+ if (r.clipped.length > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${r.clipped.length} clipped elements.`);
299
+ if (r.overlapped.length > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${r.overlapped.length} overlapping text blocks.`);
300
+ return { clipped: r.clipped.slice(0, MAX_LISTED), overlapped: r.overlapped.slice(0, MAX_LISTED) };
301
+ }
302
+
303
+ const positive = (n) => Number.isFinite(n) && n > 0;
304
+
305
+ // Runs an optional pass; a failure becomes a note and a null result, so the other results survive.
306
+ async function optional(label, notes, fn) {
307
+ try {
308
+ return await fn();
309
+ } catch (err) {
310
+ notes.push(`${label} failed: ${err?.message ?? String(err)}`);
311
+ return null;
312
+ }
313
+ }
314
+
315
+ // Names, images, language, title, headings, generic links and target size of a page, plus the keyboard
316
+ // focus, reflow and text spacing passes when their rules are present (they open pages of their own).
317
+ export async function measureA11y(page, ctx) {
318
+ script ??= await fs.readFile(new URL("./in-page/a11y.js", import.meta.url), "utf8");
319
+ const notes = [];
320
+ const minPx = thresholdOf(ctx, "a11y.target-size")?.minPx;
321
+ const rawPhrases = thresholdOf(ctx, "a11y.generic-links")?.phrases;
322
+ const phrases = Array.isArray(rawPhrases) ? rawPhrases.map((p) => normalizePhrase(String(p))).filter(Boolean) : [];
323
+
324
+ const minSidePx = thresholdOf(ctx, "a11y.decorative-images")?.minSidePx;
325
+
326
+ const treatRule = thresholdOf(ctx, "a11y.image-treatment");
327
+ const treatment = treatRule && Array.isArray(treatRule.filters) ? { filters: treatRule.filters, blends: treatRule.blends === true } : null;
328
+ if (treatment && !Number.isFinite(minSidePx)) {
329
+ notes.push("Treated images were not read: the large image size comes from rule AP6, which was not part of this run.");
330
+ }
331
+
332
+ const opts = {
333
+ treatment,
334
+ globalKey: GLOBAL_KEY,
335
+ minPx: Number.isFinite(minPx) ? minPx : null,
336
+ maxTargets: MAX_TARGETS,
337
+ clipGrow: FOCUS_CLIP_GROW,
338
+ minSidePx: Number.isFinite(minSidePx) ? minSidePx : null,
339
+ maxImages: MAX_IMAGE_CANDIDATES,
340
+ };
341
+ try {
342
+ const parts = await page.evaluate(`(${script})(${JSON.stringify(opts)})`);
343
+ if (parts.totalTargets > MAX_TARGETS) {
344
+ notes.push(`Target size was checked for the first ${MAX_TARGETS} of ${parts.totalTargets} interactive elements.`);
345
+ }
346
+ if (parts.totalLarge > MAX_IMAGE_CANDIDATES) {
347
+ notes.push(`Read ${MAX_IMAGE_CANDIDATES} of ${parts.totalLarge} large images for decorative marks.`);
348
+ }
349
+ const ax = await axReport(page, phrases);
350
+ const { unnamed: nu, images: ni, generic: ng, imageNodes } = ax.counts;
351
+ if (nu > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${nu} controls without a name.`);
352
+ if (ni > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${ni} images without a text alternative.`);
353
+ if (imageNodes > MAX_IMAGE_CANDIDATES) notes.push(`Checked ${MAX_IMAGE_CANDIDATES} of ${imageNodes} images without a name.`);
354
+ if (ng > MAX_LISTED) notes.push(`Listed ${MAX_LISTED} of ${ng} generic links.`);
355
+ const wants = (id) => typeof ctx?.openPage === "function" && (ctx.rules ?? []).some((r) => r.measure === id);
356
+ let focus = null;
357
+ if (wants("a11y.focus-visible") || wants("a11y.focus-obscured")) {
358
+ focus = await optional("The keyboard focus check", notes, async () => {
359
+ const budget = typeof ctx.once === "function" ? await ctx.once("a11y.focus-budget", async () => ({ spentMs: 0 })) : { spentMs: 0 };
360
+ return focusReport(await ctx.openPage({ still: true }), notes, budget);
361
+ });
362
+ }
363
+ let reflow = null;
364
+ const width = thresholdOf(ctx, "a11y.reflow")?.width;
365
+ if (wants("a11y.reflow") && positive(width) && typeof ctx.once === "function") {
366
+ reflow = await optional("The reflow check", notes, () => ctx.once("a11y.reflow", () => reflowReport(ctx, width, notes)));
367
+ }
368
+ let textSpacing = null;
369
+ const t = thresholdOf(ctx, "a11y.text-spacing");
370
+ if (wants("a11y.text-spacing") && t && [t.lineHeight, t.paragraphSpacing, t.letterSpacing, t.wordSpacing].every(positive)) {
371
+ textSpacing = await optional("The text spacing check", notes, () => textSpacingReport(ctx, t, notes));
372
+ }
373
+ return {
374
+ title: parts.title,
375
+ lang: parts.lang,
376
+ unnamed: ax.unnamed,
377
+ images: ax.images,
378
+ headings: parts.headings,
379
+ genericLinks: ax.genericLinks,
380
+ targets: parts.targets,
381
+ largeImages: parts.largeImages,
382
+ totalLarge: parts.totalLarge,
383
+ focus,
384
+ reflow,
385
+ textSpacing,
386
+ notes,
387
+ };
388
+ } finally {
389
+ await page.evaluate((key) => { delete globalThis[key]; }, GLOBAL_KEY).catch(() => {});
390
+ }
391
+ }