@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,621 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { cdpSession, toUrl } from "../browser.mjs";
3
+ import { flowStopUrl, hasStopWord, isLocalTarget } from "../project/tasks.mjs";
4
+ import { restOff, restOn } from "./at-rest.mjs";
5
+ import { bounded } from "./states.mjs";
6
+
7
+ // The motion recorder: one raw open of the target (no settle, no reveal, no animation wait) with the
8
+ // motion probe installed before any page script, a load window, a few safe scripted steps and, in a
9
+ // frames pass, frame capture. It never touches the page a measurer is given: it opens its own through
10
+ // ctx.openPage and closes it. On a page that is not local it only hovers, focuses and scrolls; a click
11
+ // runs only on a local page, only on a vetted disclosure control, through clickVetted (the one place that
12
+ // clicks). After load every main-frame navigation is aborted and counted, dialogs are dismissed and new
13
+ // windows closed, on every host.
14
+
15
+ // Definitions, not cutoffs, fixed before any page was read.
16
+ // The longest load window, longer than the 5 s of WCAG 2.2.2.
17
+ export const LOAD_WINDOW_MS = 7000;
18
+ // A load window ends early when no animation has run (and, in a frames pass, no frame differing from the
19
+ // previous one has come) for this long.
20
+ export const QUIET_MS = 1500;
21
+ // The longest window after a scripted step, and the quiet that ends it early.
22
+ export const STEP_WINDOW_MS = 1000;
23
+ export const STEP_QUIET_MS = 300;
24
+ // The first-view actions a pass hovers, focuses and (local, disclosure controls only) clicks.
25
+ export const MAX_STEP_TARGETS = 3;
26
+ // Frames are captured at this share of the viewport size.
27
+ export const FRAME_SCALE = 0.5;
28
+ // Frame analysis (in-page/frames.js). A channel difference of PIXEL_NOISE levels or less is no change.
29
+ export const PIXEL_NOISE = 2;
30
+ // Moving content is read on square cells of CELL_PX frame px.
31
+ export const CELL_PX = 16;
32
+ // A cell moves when it changes in at least MIN_MOVING_SECONDS distinct whole seconds over more than the
33
+ // moving rule's maxMovingMs, so one late image is not motion.
34
+ export const MIN_MOVING_SECONDS = 3;
35
+ // Neighbor runs of a gradient at most BAND_LEVELS levels apart per channel are bands; a larger step is a
36
+ // content edge.
37
+ export const BAND_LEVELS = 3;
38
+ // Measurement constant, not a cutoff: frames from the start of a scripted scroll step to SCROLL_SETTLE_MS
39
+ // after its end are not read for flashes (moving content shows opposing changes that are not a flash).
40
+ export const SCROLL_SETTLE_MS = 500;
41
+ // Measurement constant, not a cutoff: the flash reading looks for content moved by up to MAX_SHIFT_PX frame
42
+ // px between two captured frames (96 CSS px at FRAME_SCALE), so a ticker or a sliding carousel is read as
43
+ // movement, not as flashing. The reach per second scales with the capture rate (2880 CSS px a second at 30
44
+ // frames a second, 960 at 10); faster movement is not read as movement.
45
+ export const MAX_SHIFT_PX = 48;
46
+ // Filmstrip tiles: the last frame at or before each of these offsets from the phase start.
47
+ export const FILM_OFFSETS_MS = [0, 100, 200, 400, 800, 1600];
48
+ // Layout shift session window: shifts less than SHIFT_GAP_MS apart, at most SHIFT_WINDOW_MS in total, as the
49
+ // web.dev "Cumulative Layout Shift (CLS)" page defines it (https://web.dev/articles/cls).
50
+ export const SHIFT_GAP_MS = 1000;
51
+ export const SHIFT_WINDOW_MS = 5000;
52
+ // Properties that move an element (MOVE_PROPS) and properties that lay the page out again (LAYOUT_PROPS).
53
+ export const MOVE_PROPS = [
54
+ "transform", "translate", "scale", "rotate", "top", "left", "right", "bottom",
55
+ "inset", "inset-block", "inset-inline", "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
56
+ "offset-distance",
57
+ ];
58
+ export const LAYOUT_PROPS = [
59
+ "width", "height", "min-width", "min-height", "max-width", "max-height",
60
+ "inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size",
61
+ "top", "left", "right", "bottom", "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
62
+ "margin-top", "margin-right", "margin-bottom", "margin-left",
63
+ "margin-block-start", "margin-block-end", "margin-inline-start", "margin-inline-end",
64
+ "padding-top", "padding-right", "padding-bottom", "padding-left",
65
+ "padding-block-start", "padding-block-end", "padding-inline-start", "padding-inline-end",
66
+ "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
67
+ "border-block-start-width", "border-block-end-width", "border-inline-start-width", "border-inline-end-width",
68
+ "font-size", "line-height", "letter-spacing", "flex-basis", "grid-template-columns", "grid-template-rows",
69
+ ];
70
+ // Sampling limits, noted when they cut.
71
+ export const MAX_ANIMATIONS = 200;
72
+ export const MAX_FRAMES = 900;
73
+ export const MAX_GRADIENTS = 8;
74
+ // Measurement tolerance, not a cutoff (about three frames at 60 Hz): a timed reading within it of a rule's
75
+ // cutoff is not judged; the evaluator gives no finding and a note names the reading, this tolerance and
76
+ // the cutoff.
77
+ export const TIMING_TOLERANCE_MS = 50;
78
+ // Cap, not a cutoff: one pass, open to close.
79
+ export const PASS_CAP_MS = 30000;
80
+ // Cap, not a cutoff: frame decoding, analysis and filmstrip composition of a frames pass together.
81
+ export const ANALYSIS_CAP_MS = 30000;
82
+ // Cap, not a cutoff: the whole motion measure, every pass and the analysis together,
83
+ // so three pass caps and the analysis cap never add up past it; what it stops is noted as not checked.
84
+ export const MOTION_CAP_MS = 90000;
85
+ // Whole words of an accessible name that make an action a control that may pause moving content (WCAG 2.2.2).
86
+ export const PAUSE_WORDS = ["pause", "pausar", "stop", "parar", "pare", "hide", "ocultar", "esconder"];
87
+ // The capture method, chosen once by a probe (a 10 Hz black and white toggle): the screencast saw
88
+ // every toggle, so back-to-back screenshots are not used.
89
+ export const CAPTURE_METHOD = "screencast";
90
+
91
+ // Implementation intervals and caps, not rule cutoffs: how often a window is polled, and how long a
92
+ // DevTools call or a cleanup step may take.
93
+ const POLL_MS = 50;
94
+ const CDP_CAP_MS = 5000;
95
+ const CLEANUP_CAP_MS = 5000;
96
+ // Two boxes within this many px are the same box (the vetted action against the live element).
97
+ const BOX_PX = 1;
98
+ // The snapshot grid of a frames pass, in CSS px: half a frame cell (CELL_PX / FRAME_SCALE / 2), so the
99
+ // center of any box of whole cells falls on a grid point. Derived from the definitions above.
100
+ const SNAPSHOT_PX = CELL_PX / FRAME_SCALE / 2;
101
+
102
+ const probeSource = readFileSync(new URL("./in-page/motion-probe.js", import.meta.url), "utf8");
103
+ const composition = readFileSync(new URL("./in-page/composition.js", import.meta.url), "utf8");
104
+
105
+ // The init script: the probe wrapped as an immediately called function with its limits.
106
+ export function motionProbeScript() {
107
+ return `(${probeSource})(${JSON.stringify({ maxAnimations: MAX_ANIMATIONS, moveProps: MOVE_PROPS })})`;
108
+ }
109
+
110
+ const read = (page, opts) => page.evaluate(`(${composition})(${JSON.stringify(opts)})`);
111
+ const readActions = (page) => read(page, { read: "actions", keepPinned: true, disclosure: true });
112
+ const readMotion = (page, from, snapshot = null) => read(page, { read: "motion", keepPinned: true, from, maxGradients: MAX_GRADIENTS, snapshot });
113
+
114
+ const STEP_KINDS = new Set(["link", "button", "other"]);
115
+
116
+ // The steps of a pass: for each of the first MAX_STEP_TARGETS first-view links, buttons and other
117
+ // controls that do not submit a form, a hover and a focus step and, only on a local page, a click step
118
+ // for a disclosure control (not a link, outside any form, with no stop word in its name); then one
119
+ // scroll step. Pure.
120
+ export function planSteps(actions, { local }) {
121
+ const targets = (actions ?? []).filter((a) => a.firstView === true && STEP_KINDS.has(a.kind) && a.submits !== true).slice(0, MAX_STEP_TARGETS);
122
+ const steps = [];
123
+ const next = () => `s${steps.length + 1}`;
124
+ for (const a of targets) {
125
+ const base = { selector: a.selector, name: a.name ?? "", box: a.box };
126
+ steps.push({ id: next(), kind: "hover", ...base });
127
+ steps.push({ id: next(), kind: "focus", ...base });
128
+ if (local === true && a.kind !== "link" && a.form === null && a.disclosure === true && !hasStopWord(a.name ?? "")) {
129
+ steps.push({ id: next(), kind: "click", ...base });
130
+ }
131
+ }
132
+ steps.push({ id: next(), kind: "scroll", selector: "html", name: "" });
133
+ return steps;
134
+ }
135
+
136
+ // The navigation abort of a pass, installed in prepare (before the page opens) at context level and armed
137
+ // at load. Until it is armed the page loads as it would (its own redirects included); then every
138
+ // main-frame navigation of the page is aborted and counted, and a window the page opens is never loaded
139
+ // (closed, counted once). Requests that are not navigations, and iframe navigations, go on through
140
+ // route.fallback() to any route registered before it.
141
+ // Real sites are read only: on a page that is not local (the target, or where the page is now), every
142
+ // request whose method is not GET, HEAD or OPTIONS is aborted and counted (sent), from any frame and of
143
+ // any type (navigation, iframe navigation, fetch, XHR, beacon, form), from the first request on; so is
144
+ // every request whose address has a stop word (flowStopUrl: a logout, delete, unsubscribe or
145
+ // checkout link fired by a hover, an image ping or an iframe; counted as stops), except the load the
146
+ // person asked for (the target's main-frame navigations before arming). Every WebSocket of such a
147
+ // page is closed before it connects (live, counted apart); on a local page sockets connect as they would.
148
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
149
+ function navigationAbort(startUrl) {
150
+ const state = { page: null, armed: false, blocked: 0, windows: 0, sent: 0, stops: 0, live: 0 };
151
+ const local = () => {
152
+ if (!isLocalTarget(startUrl)) return false;
153
+ const now = state.page ? state.page.url() : "about:blank";
154
+ return now === "about:blank" || isLocalTarget(now);
155
+ };
156
+ const install = async (context) => {
157
+ context.on("page", (p) => {
158
+ if (state.page === null) {
159
+ state.page = p;
160
+ p.on("dialog", (d) => d.dismiss().catch(() => {}));
161
+ p.once("load", () => {
162
+ state.armed = true;
163
+ });
164
+ return;
165
+ }
166
+ state.windows += 1;
167
+ p.close().catch(() => {});
168
+ });
169
+ // context.route never sees a WebSocket. Never connectToServer on a page that is not local.
170
+ await context.routeWebSocket(() => true, (ws) => {
171
+ if (local()) {
172
+ ws.connectToServer();
173
+ return;
174
+ }
175
+ state.live += 1;
176
+ ws.close();
177
+ });
178
+ await context.route("**/*", (route) => {
179
+ const req = route.request();
180
+ let frame = null;
181
+ try {
182
+ frame = req.frame();
183
+ } catch {
184
+ // A navigation whose frame does not exist yet (a window the page opens): fail closed.
185
+ frame = null;
186
+ }
187
+ if (!local()) {
188
+ if (!SAFE_METHODS.has(req.method())) {
189
+ state.sent += 1;
190
+ return route.abort("aborted");
191
+ }
192
+ // The load the person asked for (the target and its redirects, before the guard is armed) is never
193
+ // stopped for its address; the recorder then runs no step on a checkout or payment page.
194
+ const asked = !state.armed && req.isNavigationRequest() && !!frame && frame.parentFrame() === null && frame.page() === state.page;
195
+ if (!asked && flowStopUrl(req.url())) {
196
+ state.stops += 1;
197
+ return route.abort("aborted");
198
+ }
199
+ }
200
+ if (!req.isNavigationRequest()) return route.fallback();
201
+ if (frame && frame.parentFrame() !== null) return route.fallback();
202
+ // "aborted" leaves the page on its document; a plain abort commits the browser's error page.
203
+ if (!frame || frame.page() !== state.page) return route.abort("aborted");
204
+ if (!state.armed) return route.fallback();
205
+ state.blocked += 1;
206
+ return route.abort("aborted");
207
+ });
208
+ };
209
+ return { state, install, arm: () => (state.armed = true) };
210
+ }
211
+
212
+ // The live element of a vetted action: the one element matching its selector whose box is the box read.
213
+ function findVetted([selector, box, near]) {
214
+ const close = (a, b) => Math.abs(a - b) <= near;
215
+ let list = [];
216
+ try {
217
+ list = [...document.querySelectorAll(selector)];
218
+ } catch {
219
+ return null;
220
+ }
221
+ const hits = list.filter((el) => {
222
+ const r = el.getBoundingClientRect();
223
+ return close(r.left + scrollX, box.x) && close(r.top + scrollY, box.y) && close(r.width, box.w) && close(r.height, box.h);
224
+ });
225
+ return hits.length === 1 ? hits[0] : null;
226
+ }
227
+
228
+ // The vetted element as a handle (findVetted, run once), or null and a note naming the skipped step.
229
+ async function vettedHandle(page, step, notes) {
230
+ const handle = await page.evaluateHandle(findVetted, [step.selector, step.box, BOX_PX]);
231
+ const el = handle.asElement();
232
+ if (el) return el;
233
+ await handle.dispose();
234
+ notes.push(`The ${step.kind} on "${step.name}" (${step.selector}) was skipped: it was not found where it was read.`);
235
+ return null;
236
+ }
237
+
238
+ // Run on the vetted element itself: its center in viewport coordinates, or why it cannot be acted on.
239
+ // With click, also checks that it is still a disclosure control outside any form and link, and that the
240
+ // element at its center is it or inside it.
241
+ function pointOf(el, click) {
242
+ const r = el.getBoundingClientRect();
243
+ const x = r.left + r.width / 2;
244
+ const y = r.top + r.height / 2;
245
+ if (!(x >= 0 && y >= 0 && x < innerWidth && y < innerHeight)) return { why: "its center is outside the screen" };
246
+ if (click) {
247
+ const popup = el.getAttribute("aria-haspopup");
248
+ const disclosure =
249
+ el.tagName === "SUMMARY" || el.hasAttribute("aria-expanded") || el.hasAttribute("aria-controls") || (popup !== null && popup !== "false") || el.getAttribute("role") === "tab";
250
+ if (!disclosure) return { why: "it is not a disclosure control" };
251
+ if (el.form || el.closest("form")) return { why: "it is inside a form" };
252
+ if (el.closest("a[href]")) return { why: "it is inside a link" };
253
+ const hit = document.elementFromPoint(x, y);
254
+ if (!hit || !(hit === el || el.contains(hit))) return { why: "another element is on top of it" };
255
+ }
256
+ return { x, y };
257
+ }
258
+
259
+ const sameBox = (a, b) => !!a && !!b && ["x", "y", "w", "h"].every((k) => Math.abs(a[k] - b[k]) <= BOX_PX);
260
+
261
+ // The one place the recorder clicks: a local page, the vetted action read again with the same selector,
262
+ // name and box (a disclosure control, not a link, outside any form, no stop word), and the element at its
263
+ // center is it or inside it. Returns the step's start time, or null and a note when the click is skipped.
264
+ async function clickVetted(page, step, mark, notes, live) {
265
+ const skip = (why) => {
266
+ notes.push(`The click on "${step.name}" (${step.selector}) was skipped: ${why}.`);
267
+ return null;
268
+ };
269
+ if (!isLocalTarget(page.url())) return skip("the page is no longer local");
270
+ if (hasStopWord(step.name)) return skip("its name has a stop word");
271
+ const { actions } = await readActions(page);
272
+ const same = actions.filter((a) => a.selector === step.selector && a.name === step.name && sameBox(a.box, step.box));
273
+ if (same.length !== 1) return skip("it was not found again with the same name and box");
274
+ const a = same[0];
275
+ if (a.kind === "link" || a.form !== null || a.submits !== false || a.disclosure !== true) return skip("it is not a disclosure control outside a form");
276
+ const el = await vettedHandle(page, step, notes);
277
+ if (!el) return null;
278
+ try {
279
+ const point = await el.evaluate(pointOf, true);
280
+ if (point.why) return skip(point.why);
281
+ // Residual: check and click are separate round trips, so on a page that animates another element can
282
+ // slide under the point in between (local pages and disclosure controls only).
283
+ const startMs = await mark(el);
284
+ // A pass past its cap never clicks, even with this click already in flight.
285
+ if (live.cancelled) throw new Error("the recording was stopped");
286
+ await page.mouse.click(point.x, point.y);
287
+ return startMs;
288
+ } finally {
289
+ await el.dispose().catch(() => {});
290
+ }
291
+ }
292
+
293
+ // After a wheel: the page time scrollY stopped changing (two animation frames in a row with the same value
294
+ // after it moved), or the step's start when the page cannot scroll; at most STEP_WINDOW_MS after the start.
295
+ function scrollEnd([y0, start, maxMs]) {
296
+ return new Promise((resolve) => {
297
+ if (document.documentElement.scrollHeight <= innerHeight) {
298
+ resolve(start);
299
+ return;
300
+ }
301
+ let last = y0;
302
+ let lastChange = start;
303
+ let moved = false;
304
+ const tick = () => {
305
+ const now = performance.now();
306
+ if (scrollY !== last) {
307
+ last = scrollY;
308
+ lastChange = now;
309
+ moved = true;
310
+ } else if (moved) {
311
+ resolve(lastChange);
312
+ return;
313
+ }
314
+ if (now - start >= maxMs) {
315
+ resolve(lastChange);
316
+ return;
317
+ }
318
+ requestAnimationFrame(tick);
319
+ };
320
+ requestAnimationFrame(tick);
321
+ });
322
+ }
323
+
324
+ // The handle a hover vetted, kept for the focus step on the same action: a hover that moves the element
325
+ // (a lift) leaves it off its read box, and focus needs no pointer. Clicks always vet
326
+ // again by the box.
327
+ const heldKey = (step) => JSON.stringify([step.selector, step.name, step.box]);
328
+
329
+ // Hover: the pointer over the vetted element's center. Focus: element.focus() on the same element (no key
330
+ // event), through the handle its hover vetted when there is one. Scroll: one wheel of the page's viewport height from
331
+ // the viewport center; step.scrollEndMs is when scrollY stopped changing. Returns the start time, or null.
332
+ async function runStep(page, step, mark, notes, live, held) {
333
+ if (step.kind === "click") return clickVetted(page, step, mark, notes, live);
334
+ if (step.kind === "scroll") {
335
+ const { width, height } = page.viewportSize();
336
+ const y0 = await page.evaluate(() => scrollY);
337
+ const startMs = await mark();
338
+ await page.mouse.move(width / 2, height / 2);
339
+ await page.mouse.wheel(0, height);
340
+ step.scrollEndMs = await page.evaluate(scrollEnd, [y0, startMs, STEP_WINDOW_MS]);
341
+ return startMs;
342
+ }
343
+ if (step.kind === "hover") {
344
+ const el = await vettedHandle(page, step, notes);
345
+ if (!el) return null;
346
+ const point = await el.evaluate(pointOf, false);
347
+ if (point.why) {
348
+ await el.dispose().catch(() => {});
349
+ notes.push(`The hover on "${step.name}" (${step.selector}) was skipped: ${point.why}.`);
350
+ return null;
351
+ }
352
+ held.set(heldKey(step), el);
353
+ const startMs = await mark(el);
354
+ await page.mouse.move(point.x, point.y);
355
+ return startMs;
356
+ }
357
+ const kept = held.get(heldKey(step));
358
+ held.delete(heldKey(step));
359
+ const el = kept && (await kept.evaluate((e) => e.isConnected).catch(() => false)) ? kept : await vettedHandle(page, step, notes);
360
+ if (kept && el !== kept) await kept.dispose().catch(() => {});
361
+ if (!el) return null;
362
+ step.handle = el;
363
+ const startMs = await mark(el);
364
+ await el.evaluate((e) => e.focus({ preventScroll: true }));
365
+ return startMs;
366
+ }
367
+
368
+ // After a step: the pointer parks off the page, a focused element is blurred, and two animation frames
369
+ // pass so a reverse transition is recorded under this step.
370
+ async function releaseStep(page, step) {
371
+ if (step.kind === "hover" || step.kind === "scroll" || step.kind === "click") await page.mouse.move(-1, -1);
372
+ if (step.handle) {
373
+ await step.handle.evaluate((e) => e.blur()).catch(() => {});
374
+ await step.handle.dispose().catch(() => {});
375
+ delete step.handle;
376
+ }
377
+ await page.evaluate(() => new Promise((resolve) => {
378
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
379
+ setTimeout(resolve, 100);
380
+ }));
381
+ }
382
+
383
+ const poll = (page) => page.evaluate(() => [performance.now(), window.__lazuliMotion.running()]);
384
+
385
+ // Waits from start (page ms) until maxMs has passed, or until nothing has run (no running animation and,
386
+ // with a capture, no differing frame) for quietMs. Returns the page time it ended at.
387
+ async function windowFrom(page, start, { maxMs, quietMs, capture }) {
388
+ let lastActive = start;
389
+ for (;;) {
390
+ const [t, running] = await poll(page);
391
+ if (running > 0) lastActive = t;
392
+ const change = capture ? capture.lastChange() : null;
393
+ const quietSince = Math.max(lastActive, change ?? -Infinity);
394
+ if (t - start >= maxMs) return t;
395
+ if (quietMs !== null && t - quietSince >= quietMs) return t;
396
+ await page.waitForTimeout(POLL_MS);
397
+ }
398
+ }
399
+
400
+ // Frame capture through the DevTools screencast (PNG at FRAME_SCALE, every frame acked). t is the frame's
401
+ // time on the page's timeline (its wall time minus the page's timeOrigin); at most MAX_FRAMES are kept.
402
+ // lastChange() is the time of the last frame whose PNG bytes differ from the previous frame's. stop() gives
403
+ // { method, frames, cut, seen }: seen counts every frame that came, kept or not.
404
+ export async function startFrames(page) {
405
+ const client = await cdpSession(page);
406
+ const timeOrigin = await page.evaluate(() => performance.timeOrigin);
407
+ const { width, height } = page.viewportSize();
408
+ const frames = [];
409
+ let cut = false;
410
+ let seen = 0;
411
+ let open = true;
412
+ let previous = null;
413
+ let lastChange = null;
414
+ client.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
415
+ client.send("Page.screencastFrameAck", { sessionId }).catch(() => {});
416
+ if (!open) return;
417
+ seen += 1;
418
+ const png = Buffer.from(data, "base64");
419
+ // metadata.timestamp is the frame's wall time in seconds since the epoch.
420
+ const wall = typeof metadata?.timestamp === "number" ? metadata.timestamp * 1000 : Date.now();
421
+ const t = Math.round(wall - timeOrigin);
422
+ if (previous === null || !png.equals(previous)) lastChange = t;
423
+ previous = png;
424
+ if (frames.length >= MAX_FRAMES) {
425
+ cut = true;
426
+ return;
427
+ }
428
+ frames.push({ t, png });
429
+ });
430
+ await bounded(
431
+ client.send("Page.startScreencast", { format: "png", maxWidth: Math.round(width * FRAME_SCALE), maxHeight: Math.round(height * FRAME_SCALE), everyNthFrame: 1 }),
432
+ CDP_CAP_MS,
433
+ "Page.startScreencast",
434
+ );
435
+ let stopped = null;
436
+ return {
437
+ lastChange: () => lastChange,
438
+ stop() {
439
+ stopped ??= (async () => {
440
+ await bounded(client.send("Page.stopScreencast"), CDP_CAP_MS, "Page.stopScreencast").catch(() => {});
441
+ open = false;
442
+ await client.detach().catch(() => {});
443
+ return { method: CAPTURE_METHOD, frames, cut, seen };
444
+ })();
445
+ return stopped;
446
+ },
447
+ };
448
+ }
449
+
450
+ const plural = (n, one, many) => (n === 1 ? one : many);
451
+
452
+ async function record(ctx, o) {
453
+ const { guard, live } = o;
454
+ const notes = [];
455
+ const page = await ctx.openPage({ bare: true, still: o.reduced, prepare: o.prepare });
456
+ guard.arm();
457
+ const info = await page.evaluate(() => {
458
+ const nav = performance.getEntriesByType("navigation")[0];
459
+ return { loadMs: nav && nav.loadEventStart > 0 ? nav.loadEventStart : performance.now(), probe: typeof window.__lazuliMotion === "object" && window.__lazuliMotion !== null };
460
+ });
461
+ if (!info.probe) throw new Error("the motion probe did not run on the page");
462
+ const loadMs = info.loadMs;
463
+ if (o.frames) live.capture = await startFrames(page);
464
+
465
+ const ended = await windowFrom(page, loadMs, { maxMs: LOAD_WINDOW_MS, quietMs: o.fullWindow ? null : QUIET_MS, capture: live.capture });
466
+ const windowMs = Math.round(ended - loadMs);
467
+ const targets = [];
468
+ const first = await readMotion(page, 0);
469
+ targets.push(...first.targets);
470
+ notes.push(...first.notes.filter((n) => !n.includes("gradients on the screen")));
471
+
472
+ // Local is read from where the page ended after load (a local start may redirect to a hosted page).
473
+ const url = page.url();
474
+ const local = isLocalTarget(url);
475
+ const { actions } = await readActions(page);
476
+ let planned = [];
477
+ if (o.steps) {
478
+ if (!local && flowStopUrl(url)) {
479
+ notes.push("The page ended on a checkout or payment address of a site that is not local; no step was run.");
480
+ } else {
481
+ planned = planSteps(actions, { local });
482
+ if (!local) notes.push("The page is not local: it was hovered, focused and scrolled; nothing was clicked.");
483
+ }
484
+ }
485
+ const steps = [];
486
+ let lastEnd = ended;
487
+ const held = new Map();
488
+ try {
489
+ for (const step of planned) {
490
+ // A pass past its cap runs no further step (no click after the pass has rejected).
491
+ if (live.cancelled) throw new Error("the recording was stopped");
492
+ // el: the vetted element a hover, focus or click acts on, so each record says whether it runs on it.
493
+ const mark = (el = null) => page.evaluate(([label, on]) => window.__lazuliMotion.mark(label, on), [`${step.kind} ${step.id}`, el]);
494
+ const startMs = await runStep(page, step, mark, notes, live, held);
495
+ if (startMs === null) continue;
496
+ await windowFrom(page, startMs, { maxMs: STEP_WINDOW_MS, quietMs: STEP_QUIET_MS, capture: live.capture });
497
+ await releaseStep(page, step);
498
+ const endMs = await page.evaluate(() => performance.now());
499
+ lastEnd = endMs;
500
+ steps.push({
501
+ id: step.id, kind: step.kind, selector: step.selector, name: step.name, startMs: Math.round(startMs), endMs: Math.round(endMs),
502
+ ...(step.kind === "scroll" ? { scrollEndMs: Math.round(step.scrollEndMs) } : {}),
503
+ });
504
+ targets.push(...(await readMotion(page, targets.length)).targets);
505
+ }
506
+ } finally {
507
+ for (const h of held.values()) await h.dispose().catch(() => {});
508
+ }
509
+ // Shift sources or late animations recorded after the last read.
510
+ targets.push(...(await readMotion(page, targets.length)).targets);
511
+
512
+ let frames = null;
513
+ if (live.capture) {
514
+ frames = await live.capture.stop();
515
+ live.capture = null;
516
+ }
517
+ // A frames pass reads the page as the load window left it: back at the top, with the
518
+ // capture stopped. The snapshot first (endless motion still running), then the gradients at rest.
519
+ let snapshot = null;
520
+ let gradientShots = null;
521
+ if (o.snapshot || o.gradients) {
522
+ await page.evaluate(() => new Promise((resolve) => {
523
+ window.scrollTo({ top: 0, left: 0, behavior: "instant" });
524
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
525
+ setTimeout(resolve, 100);
526
+ }));
527
+ }
528
+ if (o.snapshot) {
529
+ const read = await readMotion(page, 0, SNAPSHOT_PX);
530
+ snapshot = { targets: read.targets, points: read.points, media: read.media };
531
+ }
532
+ if (o.gradients) gradientShots = await shootGradients(page);
533
+ const data = await page.evaluate(() => {
534
+ const m = window.__lazuliMotion;
535
+ return { animations: m.animations, longFrames: m.longFrames, longFrameApi: m.longFrameApi, shifts: m.shifts, timeOrigin: m.timeOrigin, cut: m.cut };
536
+ });
537
+ if (data.cut > 0) notes.push(`The first ${MAX_ANIMATIONS} animations were recorded; ${data.cut} later ${plural(data.cut, "one was", "ones were")} not read.`);
538
+ if (guard.state.sent > 0) notes.push(`${guard.state.sent} ${plural(guard.state.sent, "request that would send data was", "requests that would send data were")} blocked.`);
539
+ if (guard.state.stops > 0) notes.push(`${guard.state.stops} ${plural(guard.state.stops, "request to an address like cart, checkout or logout was", "requests to addresses like cart, checkout or logout were")} blocked.`);
540
+ if (guard.state.live > 0) notes.push(`${guard.state.live} ${plural(guard.state.live, "live connection was", "live connections were")} blocked.`);
541
+ if (guard.state.windows > 0) notes.push(`${guard.state.windows} ${plural(guard.state.windows, "window", "windows")} the page opened ${plural(guard.state.windows, "was", "were")} closed unloaded.`);
542
+ notes.push(`Recording ended ${Math.round(lastEnd - loadMs)} ms after load; motion that starts later was not read.`);
543
+ return {
544
+ url: page.url(),
545
+ local,
546
+ timeOrigin: data.timeOrigin,
547
+ loadMs: Math.round(loadMs),
548
+ windowMs,
549
+ endedEarly: windowMs < LOAD_WINDOW_MS,
550
+ steps,
551
+ actions,
552
+ animations: data.animations,
553
+ targets,
554
+ longFrames: data.longFrames,
555
+ longFrameApi: data.longFrameApi,
556
+ shifts: data.shifts,
557
+ frames,
558
+ snapshot,
559
+ gradientShots,
560
+ navigationsBlocked: guard.state.blocked,
561
+ notes,
562
+ };
563
+ }
564
+
565
+ // The visible gradients at rest (restOn, restOff in finally), each one lossless PNG clip at device scale 1,
566
+ // the box rounded inward to whole px: { selector, box, png }[].
567
+ async function shootGradients(page) {
568
+ await page.evaluate(restOn());
569
+ try {
570
+ const { gradients } = await readMotion(page, Number.MAX_SAFE_INTEGER);
571
+ const shots = [];
572
+ for (const g of gradients) {
573
+ const x = Math.ceil(g.box.x);
574
+ const y = Math.ceil(g.box.y);
575
+ const width = Math.floor(g.box.x + g.box.w) - x;
576
+ const height = Math.floor(g.box.y + g.box.h) - y;
577
+ if (width <= 0 || height <= 0) continue;
578
+ const box = { x, y, width, height };
579
+ shots.push({ selector: g.selector, box, png: await page.screenshot({ clip: box, type: "png" }) });
580
+ }
581
+ return shots;
582
+ } finally {
583
+ await page.evaluate(restOff()).catch(() => {});
584
+ }
585
+ }
586
+
587
+ // One recording of the target, under capMs. The context is captured in prepare, so a cap that fires while
588
+ // the page is still opening closes it too; capture and context are closed in finally, every time.
589
+ // gradients: after the window, with the capture stopped, one lossless clip of each visible gradient at rest
590
+ // (Pass.gradientShots). snapshot: the target boxes, the element at each point of a grid and the media
591
+ // controls, read back at the top once the capture stopped (Pass.snapshot).
592
+ export async function recordPass(ctx, { reduced = false, steps = true, frames = false, fullWindow = false, gradients = false, snapshot = false, capMs = PASS_CAP_MS } = {}) {
593
+ // The target decides local before the page exists; a target that cannot be read is not local.
594
+ let startUrl = null;
595
+ try {
596
+ startUrl = toUrl(ctx.target, ctx.cwd);
597
+ } catch {
598
+ startUrl = null;
599
+ }
600
+ const guard = navigationAbort(startUrl);
601
+ const live = { context: null, capture: null, cancelled: false };
602
+ const prepare = async (context) => {
603
+ live.context = context;
604
+ if (live.cancelled) throw new Error("the recording was stopped");
605
+ await context.addInitScript(motionProbeScript());
606
+ await guard.install(context);
607
+ };
608
+ const work = record(ctx, { reduced, steps, frames, fullWindow, gradients, snapshot, prepare, guard, live });
609
+ // After a cap the work runs on against a closed context; its rejection is expected.
610
+ work.catch(() => {});
611
+ try {
612
+ return await bounded(work, capMs, "the recording");
613
+ } finally {
614
+ live.cancelled = true;
615
+ if (live.capture) await bounded(live.capture.stop(), CLEANUP_CAP_MS, "stopping the capture").catch(() => {});
616
+ if (live.context) await bounded(live.context.close(), CLEANUP_CAP_MS, "closing the recording").catch(() => {});
617
+ // A cap that fired before the page opened: the open gives up in prepare and closes its own context.
618
+ await bounded(work, CLEANUP_CAP_MS, "the recording").catch(() => {});
619
+ if (live.context) await live.context.close().catch(() => {});
620
+ }
621
+ }