@mizchi/vlmkit-core 0.7.0 → 0.8.1

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 (65) hide show
  1. package/dist/a11y-semantic.d.mts +34 -0
  2. package/dist/a11y-semantic.mjs +261 -0
  3. package/dist/authored-style-capture.d.mts +42 -0
  4. package/dist/authored-style-capture.mjs +117 -0
  5. package/dist/authored-style-diff.d.mts +15 -0
  6. package/dist/authored-style-diff.mjs +16 -0
  7. package/dist/cli-args.d.mts +11 -0
  8. package/dist/cli-args.mjs +21 -0
  9. package/dist/cli-error.d.mts +4 -0
  10. package/dist/cli-error.mjs +59 -0
  11. package/dist/computed-style-capture.d.mts +41 -0
  12. package/dist/computed-style-capture.mjs +589 -0
  13. package/dist/computed-style-diff.d.mts +83 -0
  14. package/dist/computed-style-diff.mjs +123 -0
  15. package/dist/diff-regions.d.mts +8 -0
  16. package/dist/diff-regions.mjs +52 -0
  17. package/dist/dom-equivalence.d.mts +51 -0
  18. package/dist/dom-equivalence.mjs +91 -0
  19. package/dist/dom-position-styles.d.mts +166 -0
  20. package/dist/dom-position-styles.mjs +296 -0
  21. package/dist/element-compare.d.mts +71 -0
  22. package/dist/element-compare.mjs +269 -0
  23. package/dist/heatmap-regions.d.mts +57 -0
  24. package/dist/heatmap-regions.mjs +158 -0
  25. package/dist/heatmap.d.mts +86 -0
  26. package/dist/heatmap.mjs +510 -0
  27. package/dist/image-resize.d.mts +34 -0
  28. package/dist/image-resize.mjs +92 -0
  29. package/dist/index.d.mts +15 -0
  30. package/dist/index.mjs +14 -0
  31. package/dist/mask.d.mts +18 -0
  32. package/dist/mask.mjs +27 -0
  33. package/dist/png-utils.d.mts +30 -0
  34. package/dist/png-utils.mjs +80 -0
  35. package/dist/region-shift.d.mts +20 -0
  36. package/dist/region-shift.mjs +128 -0
  37. package/dist/run-ledger.d.mts +14 -0
  38. package/dist/run-ledger.mjs +31 -0
  39. package/dist/terminal-colors.d.mts +12 -0
  40. package/dist/terminal-colors.mjs +14 -0
  41. package/dist/text-rows.d.mts +121 -0
  42. package/dist/text-rows.mjs +246 -0
  43. package/{src/types.ts → dist/types.d.mts} +88 -206
  44. package/dist/types.mjs +1 -0
  45. package/package.json +17 -5
  46. package/src/a11y-semantic.ts +0 -384
  47. package/src/authored-style-capture.ts +0 -185
  48. package/src/authored-style-diff.ts +0 -32
  49. package/src/cli-args.ts +0 -29
  50. package/src/cli-error.ts +0 -85
  51. package/src/computed-style-capture.ts +0 -717
  52. package/src/computed-style-diff.ts +0 -192
  53. package/src/diff-regions.ts +0 -70
  54. package/src/dom-equivalence.ts +0 -158
  55. package/src/dom-position-styles.ts +0 -457
  56. package/src/element-compare.ts +0 -354
  57. package/src/heatmap-regions.ts +0 -245
  58. package/src/heatmap.ts +0 -670
  59. package/src/image-resize.ts +0 -112
  60. package/src/index.ts +0 -105
  61. package/src/mask.ts +0 -41
  62. package/src/png-utils.ts +0 -86
  63. package/src/region-shift.ts +0 -173
  64. package/src/terminal-colors.ts +0 -13
  65. package/src/text-rows.ts +0 -412
@@ -0,0 +1,34 @@
1
+ import { A11yDiff, A11yNode, A11ySnapshot } from "./types.mjs";
2
+
3
+ //#region src/a11y-semantic.d.ts
4
+ declare const LANDMARK_ROLES: Set<string>;
5
+ declare const INTERACTIVE_ROLES: Set<string>;
6
+ /**
7
+ * Compare two a11y tree snapshots and return the semantic diff.
8
+ */
9
+ declare function diffA11yTrees(baseline: A11ySnapshot, current: A11ySnapshot): A11yDiff;
10
+ /**
11
+ * A11y tree quality checks (standalone, no diff).
12
+ *
13
+ * Walks the tree and returns issues such as missing labels on
14
+ * interactive elements and missing alt text on images.
15
+ *
16
+ * @since 0.5.0 — replaces `checkA11yTree`.
17
+ */
18
+ declare function verifyA11yTree(tree: A11yNode): A11yIssue[];
19
+ /**
20
+ * @deprecated since 0.5.0 — use `verifyA11yTree` instead. Removed in 1.0.0.
21
+ */
22
+ declare const checkA11yTree: typeof verifyA11yTree;
23
+ interface A11yIssue {
24
+ path: string;
25
+ rule: string;
26
+ severity: "error" | "warning";
27
+ message: string;
28
+ }
29
+ /**
30
+ * Convert Playwright page.accessibility.snapshot() output to A11ySnapshot.
31
+ */
32
+ declare function parsePlaywrightA11ySnapshot(testId: string, testTitle: string, raw: Record<string, unknown>): A11ySnapshot;
33
+ //#endregion
34
+ export { A11yIssue, INTERACTIVE_ROLES, LANDMARK_ROLES, checkA11yTree, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree };
@@ -0,0 +1,261 @@
1
+ //#region src/a11y-semantic.ts
2
+ const LANDMARK_ROLES = new Set([
3
+ "banner",
4
+ "complementary",
5
+ "contentinfo",
6
+ "form",
7
+ "main",
8
+ "navigation",
9
+ "region",
10
+ "search"
11
+ ]);
12
+ const INTERACTIVE_ROLES = new Set([
13
+ "button",
14
+ "checkbox",
15
+ "combobox",
16
+ "link",
17
+ "listbox",
18
+ "menu",
19
+ "menubar",
20
+ "menuitem",
21
+ "option",
22
+ "radio",
23
+ "scrollbar",
24
+ "searchbox",
25
+ "slider",
26
+ "spinbutton",
27
+ "switch",
28
+ "tab",
29
+ "tabpanel",
30
+ "textbox",
31
+ "treeitem"
32
+ ]);
33
+ /**
34
+ * Compare two a11y tree snapshots and return the semantic diff.
35
+ */
36
+ function diffA11yTrees(baseline, current) {
37
+ const changes = [];
38
+ diffNodes(baseline.tree, current.tree, "", changes);
39
+ const landmarkChanges = changes.filter((c) => c.type === "landmark-changed");
40
+ const hasRegression = changes.some((c) => c.severity === "error");
41
+ return {
42
+ testId: current.testId,
43
+ changes,
44
+ hasRegression,
45
+ landmarkChanges,
46
+ stats: {
47
+ added: changes.filter((c) => c.type === "node-added").length,
48
+ removed: changes.filter((c) => c.type === "node-removed").length,
49
+ modified: changes.filter((c) => c.type !== "node-added" && c.type !== "node-removed").length
50
+ }
51
+ };
52
+ }
53
+ function diffNodes(before, after, path, changes) {
54
+ const nodePath = path ? `${path} > ${nodeLabel(after ?? before)}` : nodeLabel(after ?? before);
55
+ if (!before && after) {
56
+ changes.push({
57
+ type: isLandmark(after) ? "landmark-changed" : "node-added",
58
+ path: nodePath,
59
+ after: nodeSnapshot(after),
60
+ severity: "info",
61
+ description: `Added ${after.role}${after.name ? ` "${after.name}"` : ""}`
62
+ });
63
+ return;
64
+ }
65
+ if (before && !after) {
66
+ const severity = isLandmark(before) ? "error" : isInteractive(before) ? "error" : "warning";
67
+ changes.push({
68
+ type: isLandmark(before) ? "landmark-changed" : "node-removed",
69
+ path: nodePath,
70
+ before: nodeSnapshot(before),
71
+ severity,
72
+ description: `Removed ${before.role}${before.name ? ` "${before.name}"` : ""}`
73
+ });
74
+ return;
75
+ }
76
+ if (!before || !after) return;
77
+ if (before.role !== after.role) changes.push({
78
+ type: "role-changed",
79
+ path: nodePath,
80
+ before: { role: before.role },
81
+ after: { role: after.role },
82
+ severity: isInteractive(before) || isInteractive(after) ? "error" : "warning",
83
+ description: `Role changed from "${before.role}" to "${after.role}"`
84
+ });
85
+ if (before.name !== after.name) {
86
+ const severity = isInteractive(before) && !after.name ? "error" : "info";
87
+ changes.push({
88
+ type: "name-changed",
89
+ path: nodePath,
90
+ before: { name: before.name },
91
+ after: { name: after.name },
92
+ severity,
93
+ description: after.name ? `Name changed from "${before.name}" to "${after.name}"` : `Name removed (was "${before.name}")`
94
+ });
95
+ }
96
+ for (const key of [
97
+ "checked",
98
+ "disabled",
99
+ "expanded",
100
+ "pressed",
101
+ "selected"
102
+ ]) if (before[key] !== after[key]) changes.push({
103
+ type: "state-changed",
104
+ path: nodePath,
105
+ before: { [key]: before[key] },
106
+ after: { [key]: after[key] },
107
+ severity: "info",
108
+ description: `${key} changed from ${before[key]} to ${after[key]}`
109
+ });
110
+ diffChildren(before.children ?? [], after.children ?? [], nodePath, changes);
111
+ }
112
+ /**
113
+ * Diff child node lists.
114
+ * 1) Exact match by role+name
115
+ * 2) Position-based matching for remaining -> detect role/name changes
116
+ * 3) Remainder is additions/removals
117
+ */
118
+ function diffChildren(beforeChildren, afterChildren, parentPath, changes) {
119
+ const matched = /* @__PURE__ */ new Set();
120
+ const afterMatched = /* @__PURE__ */ new Set();
121
+ const beforeByKey = /* @__PURE__ */ new Map();
122
+ for (let i = 0; i < beforeChildren.length; i++) {
123
+ const key = childKey(beforeChildren[i]);
124
+ const list = beforeByKey.get(key) ?? [];
125
+ list.push({
126
+ node: beforeChildren[i],
127
+ index: i
128
+ });
129
+ beforeByKey.set(key, list);
130
+ }
131
+ for (let ai = 0; ai < afterChildren.length; ai++) {
132
+ const key = childKey(afterChildren[ai]);
133
+ const candidates = beforeByKey.get(key);
134
+ if (candidates && candidates.length > 0) {
135
+ const match = candidates.shift();
136
+ matched.add(match.index);
137
+ afterMatched.add(ai);
138
+ diffNodes(match.node, afterChildren[ai], parentPath, changes);
139
+ }
140
+ }
141
+ const unmatchedBefore = [];
142
+ for (let i = 0; i < beforeChildren.length; i++) if (!matched.has(i)) unmatchedBefore.push({
143
+ node: beforeChildren[i],
144
+ index: i
145
+ });
146
+ const unmatchedAfter = [];
147
+ for (let i = 0; i < afterChildren.length; i++) if (!afterMatched.has(i)) unmatchedAfter.push({
148
+ node: afterChildren[i],
149
+ index: i
150
+ });
151
+ const stillUnmatchedBefore = [];
152
+ const stillUnmatchedAfter = new Set(unmatchedAfter.map((_, i) => i));
153
+ for (const b of unmatchedBefore) {
154
+ let found = false;
155
+ for (let j = 0; j < unmatchedAfter.length; j++) {
156
+ if (!stillUnmatchedAfter.has(j)) continue;
157
+ const a = unmatchedAfter[j];
158
+ if (b.node.role === a.node.role || b.node.name && b.node.name === a.node.name) {
159
+ stillUnmatchedAfter.delete(j);
160
+ diffNodes(b.node, a.node, parentPath, changes);
161
+ found = true;
162
+ break;
163
+ }
164
+ }
165
+ if (!found) stillUnmatchedBefore.push(b);
166
+ }
167
+ for (const b of stillUnmatchedBefore) diffNodes(b.node, void 0, parentPath, changes);
168
+ for (const j of stillUnmatchedAfter) diffNodes(void 0, unmatchedAfter[j].node, parentPath, changes);
169
+ const countDiff = Math.abs(afterChildren.length - beforeChildren.length);
170
+ if (countDiff > 3 && countDiff / Math.max(beforeChildren.length, 1) > .3) changes.push({
171
+ type: "structure-changed",
172
+ path: parentPath,
173
+ before: { name: `${beforeChildren.length} children` },
174
+ after: { name: `${afterChildren.length} children` },
175
+ severity: "warning",
176
+ description: `Structure changed significantly: ${beforeChildren.length} → ${afterChildren.length} children`
177
+ });
178
+ }
179
+ function childKey(node) {
180
+ return `${node.role}:${node.name ?? ""}`;
181
+ }
182
+ function nodeLabel(node) {
183
+ const name = node.name ? `[${node.name}]` : "";
184
+ return `${node.role}${name}`;
185
+ }
186
+ function nodeSnapshot(node) {
187
+ return {
188
+ role: node.role,
189
+ name: node.name,
190
+ ...node.level !== void 0 && { level: node.level },
191
+ ...node.checked !== void 0 && { checked: node.checked },
192
+ ...node.disabled !== void 0 && { disabled: node.disabled },
193
+ ...node.expanded !== void 0 && { expanded: node.expanded }
194
+ };
195
+ }
196
+ function isLandmark(node) {
197
+ return LANDMARK_ROLES.has(node.role);
198
+ }
199
+ function isInteractive(node) {
200
+ return INTERACTIVE_ROLES.has(node.role);
201
+ }
202
+ /**
203
+ * A11y tree quality checks (standalone, no diff).
204
+ *
205
+ * Walks the tree and returns issues such as missing labels on
206
+ * interactive elements and missing alt text on images.
207
+ *
208
+ * @since 0.5.0 — replaces `checkA11yTree`.
209
+ */
210
+ function verifyA11yTree(tree) {
211
+ const issues = [];
212
+ walkTree(tree, "", issues);
213
+ return issues;
214
+ }
215
+ /**
216
+ * @deprecated since 0.5.0 — use `verifyA11yTree` instead. Removed in 1.0.0.
217
+ */
218
+ const checkA11yTree = verifyA11yTree;
219
+ function walkTree(node, path, issues) {
220
+ const nodePath = path ? `${path} > ${nodeLabel(node)}` : nodeLabel(node);
221
+ if (isInteractive(node) && !node.name) issues.push({
222
+ path: nodePath,
223
+ rule: "label-missing",
224
+ severity: "error",
225
+ message: `Interactive element "${node.role}" has no accessible name`
226
+ });
227
+ if (node.role === "img" && !node.name) issues.push({
228
+ path: nodePath,
229
+ rule: "img-alt-missing",
230
+ severity: "error",
231
+ message: "Image has no accessible name (missing alt text)"
232
+ });
233
+ for (const child of node.children ?? []) walkTree(child, nodePath, issues);
234
+ }
235
+ /**
236
+ * Convert Playwright page.accessibility.snapshot() output to A11ySnapshot.
237
+ */
238
+ function parsePlaywrightA11ySnapshot(testId, testTitle, raw) {
239
+ return {
240
+ testId,
241
+ testTitle,
242
+ tree: normalizeA11yNode(raw)
243
+ };
244
+ }
245
+ function normalizeA11yNode(raw) {
246
+ return {
247
+ role: raw.role ?? "none",
248
+ name: raw.name ?? "",
249
+ ...raw.level !== void 0 && { level: raw.level },
250
+ ...raw.value !== void 0 && { value: raw.value },
251
+ ...raw.description !== void 0 && { description: raw.description },
252
+ ...raw.checked !== void 0 && { checked: raw.checked },
253
+ ...raw.disabled !== void 0 && { disabled: raw.disabled },
254
+ ...raw.expanded !== void 0 && { expanded: raw.expanded },
255
+ ...raw.pressed !== void 0 && { pressed: raw.pressed },
256
+ ...raw.selected !== void 0 && { selected: raw.selected },
257
+ ...raw.children ? { children: raw.children.map(normalizeA11yNode) } : {}
258
+ };
259
+ }
260
+ //#endregion
261
+ export { INTERACTIVE_ROLES, LANDMARK_ROLES, checkA11yTree, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree };
@@ -0,0 +1,42 @@
1
+ //#region src/authored-style-capture.d.ts
2
+ /**
3
+ * Authored CSS capture for properties whose computed form lies about the
4
+ * authored shape.
5
+ *
6
+ * Motivating case (2026-05-23 dogfood, app-shell `.shell`):
7
+ * `getComputedStyle().getPropertyValue("grid-template-columns")` resolves
8
+ * `minmax(0, 1fr) 4px minmax(0, 1fr)` to a three px-tuple — but writing
9
+ * those numbers back as CSS would corrupt the responsive layout. The fix is
10
+ * not to track grid-template-* in computed-style at all; instead, walk
11
+ * `document.styleSheets.cssRules` to emit the AUTHORED strings and diff
12
+ * THEM. Same approach scales to `flex` shorthand, `transform`, and any
13
+ * other property whose computed form diverges from authored.
14
+ *
15
+ * Surface mirrors `computed-style-capture` so consumers can reuse
16
+ * `diffComputedStyles` (it's just `Record<selector, Record<prop, value>>`
17
+ * → `Record<selector, Record<prop, value>>` either way).
18
+ */
19
+ type AuthoredStyleSnapshot = Record<string, Record<string, string>>;
20
+ /**
21
+ * Properties tracked by default. These are the ones whose computed
22
+ * representation differs structurally from the authored source — anything
23
+ * already faithful in `getComputedStyle` does not need this channel.
24
+ */
25
+ declare const AUTHORED_PROPERTIES: string[];
26
+ /**
27
+ * Browser-context capture. Walks all same-origin stylesheets and nested
28
+ * `@media` / `@supports` rules, collecting authored `value` strings for
29
+ * each (scoped-selector, property) pair listed in `props`. Last
30
+ * declaration wins per pair (mirrors authoring order; sufficient for
31
+ * static diff use cases).
32
+ *
33
+ * Selectors are comma-split so `.a, .b { grid-template-columns: ... }`
34
+ * fans out into both `.a` and `.b` entries.
35
+ */
36
+ declare function captureAuthoredStyleSnapshotInDom(props: string[]): AuthoredStyleSnapshot;
37
+ declare function buildAuthoredStyleCaptureExpression(props?: string[]): string;
38
+ declare function buildAuthoredStyleCaptureJsonExpression(props?: string[]): string;
39
+ declare function parseAuthoredStyleSnapshot(value: unknown): AuthoredStyleSnapshot;
40
+ declare function hasMeaningfulAuthoredStyleSnapshot(snapshot: AuthoredStyleSnapshot): boolean;
41
+ //#endregion
42
+ export { AUTHORED_PROPERTIES, AuthoredStyleSnapshot, buildAuthoredStyleCaptureExpression, buildAuthoredStyleCaptureJsonExpression, captureAuthoredStyleSnapshotInDom, hasMeaningfulAuthoredStyleSnapshot, parseAuthoredStyleSnapshot };
@@ -0,0 +1,117 @@
1
+ //#region src/authored-style-capture.ts
2
+ /**
3
+ * Properties tracked by default. These are the ones whose computed
4
+ * representation differs structurally from the authored source — anything
5
+ * already faithful in `getComputedStyle` does not need this channel.
6
+ */
7
+ const AUTHORED_PROPERTIES = [
8
+ "grid-template",
9
+ "grid-template-columns",
10
+ "grid-template-rows",
11
+ "grid-template-areas",
12
+ "grid-auto-columns",
13
+ "grid-auto-rows",
14
+ "grid-auto-flow",
15
+ "grid-column",
16
+ "grid-row",
17
+ "grid",
18
+ "flex",
19
+ "transform",
20
+ "clip-path",
21
+ "mask",
22
+ "mask-image"
23
+ ];
24
+ const MEDIA_SEPARATOR = " :: ";
25
+ /**
26
+ * Format a "scoped" selector key. When `mediaCondition` is empty, returns
27
+ * the bare selector text. When non-empty, the key reads
28
+ * `@media (min-width: 768px) :: .shell` so the diff treats the same
29
+ * selector inside a different `@media` block as a distinct row.
30
+ */
31
+ function buildScopedSelectorKey(selector, mediaCondition) {
32
+ const trimmedMedia = mediaCondition.trim();
33
+ if (!trimmedMedia) return selector;
34
+ return `@media ${trimmedMedia}${MEDIA_SEPARATOR}${selector}`;
35
+ }
36
+ /**
37
+ * Browser-context capture. Walks all same-origin stylesheets and nested
38
+ * `@media` / `@supports` rules, collecting authored `value` strings for
39
+ * each (scoped-selector, property) pair listed in `props`. Last
40
+ * declaration wins per pair (mirrors authoring order; sufficient for
41
+ * static diff use cases).
42
+ *
43
+ * Selectors are comma-split so `.a, .b { grid-template-columns: ... }`
44
+ * fans out into both `.a` and `.b` entries.
45
+ */
46
+ function captureAuthoredStyleSnapshotInDom(props) {
47
+ const trackedProps = new Set(props);
48
+ const results = {};
49
+ function visit(rule, mediaCondition) {
50
+ if (!rule || typeof rule !== "object") return;
51
+ const ruleObj = rule;
52
+ const conditionFromMedia = typeof ruleObj.media?.mediaText === "string" ? ruleObj.media.mediaText : "";
53
+ const conditionFromAt = typeof ruleObj.conditionText === "string" ? ruleObj.conditionText : "";
54
+ const additionalCondition = conditionFromMedia || conditionFromAt;
55
+ const nestedMedia = additionalCondition ? mediaCondition ? `${mediaCondition} and ${additionalCondition}` : additionalCondition : mediaCondition;
56
+ if (ruleObj.cssRules && typeof ruleObj.cssRules.length === "number") {
57
+ const nested = ruleObj.cssRules;
58
+ for (let i = 0; i < nested.length; i++) visit(nested[i], nestedMedia);
59
+ if (!ruleObj.selectorText) return;
60
+ }
61
+ if (typeof ruleObj.selectorText !== "string") return;
62
+ const style = ruleObj.style;
63
+ if (!style || typeof style.getPropertyValue !== "function") return;
64
+ for (const rawSelector of ruleObj.selectorText.split(",")) {
65
+ const selector = rawSelector.trim();
66
+ if (!selector) continue;
67
+ const key = buildScopedSelectorKey(selector, mediaCondition);
68
+ for (const prop of trackedProps) {
69
+ const value = style.getPropertyValue(prop);
70
+ if (!value) continue;
71
+ const bucket = results[key] ?? (results[key] = {});
72
+ bucket[prop] = value.trim();
73
+ }
74
+ }
75
+ }
76
+ const styleSheets = document.styleSheets;
77
+ if (!styleSheets) return results;
78
+ for (const sheet of Array.from(styleSheets)) try {
79
+ const rules = sheet.cssRules;
80
+ for (const rule of Array.from(rules)) visit(rule, "");
81
+ } catch {}
82
+ return results;
83
+ }
84
+ const ESBUILD_NAME_POLYFILL = "var __name = typeof __name !== 'undefined' ? __name : function(fn) { return fn; };";
85
+ function buildAuthoredStyleCaptureExpression(props = AUTHORED_PROPERTIES) {
86
+ return `(function(){ ${ESBUILD_NAME_POLYFILL} return (${captureAuthoredStyleSnapshotInDom.toString()})(${JSON.stringify(props)}); })()`;
87
+ }
88
+ function buildAuthoredStyleCaptureJsonExpression(props = AUTHORED_PROPERTIES) {
89
+ return `JSON.stringify(${buildAuthoredStyleCaptureExpression(props)})`;
90
+ }
91
+ function parseAuthoredStyleSnapshot(value) {
92
+ const candidate = typeof value === "string" ? safeJsonParse(value) : value;
93
+ if (!isRecord(candidate)) return {};
94
+ const snapshot = {};
95
+ for (const [selector, props] of Object.entries(candidate)) {
96
+ if (!isRecord(props)) continue;
97
+ const normalized = {};
98
+ for (const [prop, propValue] of Object.entries(props)) normalized[prop] = typeof propValue === "string" ? propValue : String(propValue ?? "");
99
+ snapshot[selector] = normalized;
100
+ }
101
+ return snapshot;
102
+ }
103
+ function hasMeaningfulAuthoredStyleSnapshot(snapshot) {
104
+ return Object.values(snapshot).some((props) => Object.values(props).some((value) => value.trim().length > 0));
105
+ }
106
+ function safeJsonParse(value) {
107
+ try {
108
+ return JSON.parse(value);
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+ function isRecord(value) {
114
+ return typeof value === "object" && value !== null && !Array.isArray(value);
115
+ }
116
+ //#endregion
117
+ export { AUTHORED_PROPERTIES, buildAuthoredStyleCaptureExpression, buildAuthoredStyleCaptureJsonExpression, captureAuthoredStyleSnapshotInDom, hasMeaningfulAuthoredStyleSnapshot, parseAuthoredStyleSnapshot };
@@ -0,0 +1,15 @@
1
+ import { AuthoredStyleSnapshot } from "./authored-style-capture.mjs";
2
+ import { CsdEntry, CsdPerViewportEntry, CsdPerViewportResult, CsdResult } from "./computed-style-diff.mjs";
3
+
4
+ //#region src/authored-style-diff.d.ts
5
+ type AuthoredStyleEntry = CsdEntry;
6
+ type AuthoredStyleDiffResult = CsdResult;
7
+ type AuthoredStylePerViewportEntry = CsdPerViewportEntry;
8
+ type AuthoredStylePerViewportResult = CsdPerViewportResult;
9
+ declare function diffAuthoredStyles(baseline: AuthoredStyleSnapshot, variant: AuthoredStyleSnapshot): AuthoredStyleDiffResult;
10
+ declare function aggregateAuthoredStyleByViewport(perViewport: ReadonlyArray<{
11
+ viewport: string;
12
+ result: AuthoredStyleDiffResult;
13
+ }>): AuthoredStylePerViewportResult;
14
+ //#endregion
15
+ export { AuthoredStyleDiffResult, AuthoredStyleEntry, AuthoredStylePerViewportEntry, AuthoredStylePerViewportResult, aggregateAuthoredStyleByViewport, diffAuthoredStyles };
@@ -0,0 +1,16 @@
1
+ import { aggregateCsdByViewport, diffComputedStyles } from "./computed-style-diff.mjs";
2
+ //#region src/authored-style-diff.ts
3
+ /**
4
+ * Authored-style diff. Same shape as `computed-style-diff` (a snapshot is
5
+ * `Record<scopedSelector, Record<property, value>>` in both cases), so the
6
+ * heavy lifting reuses `diffComputedStyles` — only the snapshot type
7
+ * label differs.
8
+ */
9
+ function diffAuthoredStyles(baseline, variant) {
10
+ return diffComputedStyles(baseline, variant);
11
+ }
12
+ function aggregateAuthoredStyleByViewport(perViewport) {
13
+ return aggregateCsdByViewport(perViewport);
14
+ }
15
+ //#endregion
16
+ export { aggregateAuthoredStyleByViewport, diffAuthoredStyles };
@@ -0,0 +1,11 @@
1
+ //#region src/cli-args.d.ts
2
+ /** Shared CLI argument parsing helpers */
3
+ declare const args: string[];
4
+ declare function getArg(name: string, fallback: string): string;
5
+ declare function getArg(name: string): string | undefined;
6
+ declare function hasFlag(name: string): boolean;
7
+ declare function getArgValues(name: string): string[];
8
+ /** Get positional args (not flags or flag values) */
9
+ declare function getPositionalArgs(): string[];
10
+ //#endregion
11
+ export { args, getArg, getArgValues, getPositionalArgs, hasFlag };
@@ -0,0 +1,21 @@
1
+ //#region src/cli-args.ts
2
+ /** Shared CLI argument parsing helpers */
3
+ const args = process.argv.slice(2);
4
+ function getArg(name, fallback) {
5
+ const idx = args.indexOf(`--${name}`);
6
+ return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
7
+ }
8
+ function hasFlag(name) {
9
+ return args.includes(`--${name}`);
10
+ }
11
+ function getArgValues(name) {
12
+ const values = [];
13
+ for (let i = 0; i < args.length; i++) if (args[i] === `--${name}` && args[i + 1]) values.push(args[i + 1]);
14
+ return values;
15
+ }
16
+ /** Get positional args (not flags or flag values) */
17
+ function getPositionalArgs() {
18
+ return args.filter((a, i) => !a.startsWith("--") && (i === 0 || !args[i - 1]?.startsWith("--")));
19
+ }
20
+ //#endregion
21
+ export { args, getArg, getArgValues, getPositionalArgs, hasFlag };
@@ -0,0 +1,4 @@
1
+ //#region src/cli-error.d.ts
2
+ declare function handleCliError(e: unknown): never;
3
+ //#endregion
4
+ export { handleCliError };
@@ -0,0 +1,59 @@
1
+ import { statSync } from "node:fs";
2
+ //#region src/cli-error.ts
3
+ /**
4
+ * Shared CLI error-prettifier. Recognizes common error shapes that
5
+ * make `vrt` look user-hostile (ENOENT stack traces, Playwright
6
+ * navigation errors with absolute source paths) and rewrites them
7
+ * to a one-line message.
8
+ *
9
+ * Use:
10
+ * main().catch(handleCliError);
11
+ */
12
+ function handleCliError(e) {
13
+ const err = e;
14
+ const msg = String(err?.message ?? e);
15
+ if (err?.code === "ENOENT") {
16
+ const path = err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?";
17
+ process.stderr.write(`error: file not found: ${path}\n`);
18
+ process.exit(1);
19
+ }
20
+ if (err?.code === "EISDIR") {
21
+ const argvDir = findDirectoryArg();
22
+ const path = err.path ?? msg.match(/EISDIR:[^']*'([^']+)'/)?.[1] ?? argvDir ?? "?";
23
+ const hint = path === "?" ? " hint: pass the path to a specific .html file." : ` hint: pass the path to a specific .html file inside it (e.g. ${path}/page.html).`;
24
+ process.stderr.write(`error: expected an HTML file, got a directory: ${path}\n${hint}\n`);
25
+ process.exit(1);
26
+ }
27
+ if (/net::ERR_NAME_NOT_RESOLVED/i.test(msg) || /net::ERR_CONNECTION_REFUSED/i.test(msg) || /Cannot navigate to invalid URL/i.test(msg)) {
28
+ const url = msg.match(/Navigating to ([^,]+)/i)?.[1] ?? msg.match(/(https?:\/\/[^\s"]+)/)?.[1] ?? "the URL";
29
+ let reason = "failed to load";
30
+ if (/ERR_NAME_NOT_RESOLVED/i.test(msg)) reason = "host could not be resolved (check the URL)";
31
+ else if (/ERR_CONNECTION_REFUSED/i.test(msg)) reason = "connection refused (is the server running?)";
32
+ else if (/invalid URL/i.test(msg)) reason = "not a valid URL";
33
+ process.stderr.write(`error: cannot load ${url}: ${reason}\n`);
34
+ process.exit(1);
35
+ }
36
+ if (/Timeout \d+ms exceeded/i.test(msg)) {
37
+ process.stderr.write(`error: page load timed out (${msg.match(/Timeout \d+ms exceeded[^.]*/i)?.[0] ?? msg})\n`);
38
+ process.exit(1);
39
+ }
40
+ console.error(e);
41
+ process.exit(1);
42
+ }
43
+ /**
44
+ * EISDIR fallback: Node's `fsPromises.readFile` doesn't attach `.path`
45
+ * to the error, and the message string doesn't include the path
46
+ * either. Scan argv for the first positional that exists as a
47
+ * directory — close enough since most vrt subcommands take exactly
48
+ * one path argument and the failure happens during the initial read.
49
+ */
50
+ function findDirectoryArg() {
51
+ for (const arg of process.argv.slice(2)) {
52
+ if (arg.startsWith("-")) continue;
53
+ try {
54
+ if (statSync(arg).isDirectory()) return arg;
55
+ } catch {}
56
+ }
57
+ }
58
+ //#endregion
59
+ export { handleCliError };
@@ -0,0 +1,41 @@
1
+ //#region src/computed-style-capture.d.ts
2
+ type ComputedStyleSnapshot = Record<string, Record<string, string>>;
3
+ type InteractionType = "hover" | "focus" | "active";
4
+ /** Pseudo-class state names that CDP `CSS.forcePseudoState` accepts. */
5
+ type ForcedPseudoState = "hover" | "focus" | "focus-visible" | "focus-within" | "active";
6
+ interface InteractionTargetPlan {
7
+ selector: string;
8
+ normalizedSelector: string;
9
+ /**
10
+ * Primary interaction kind, kept for legacy fallback ordering:
11
+ * `:active` collapses to "active", any `:focus*` to "focus", else "hover".
12
+ */
13
+ interaction: InteractionType;
14
+ /**
15
+ * The actual pseudo-class names extracted from the selector — preserves
16
+ * the full set (e.g. `:hover:active` → ["hover", "active"]) so Crater and
17
+ * the CDP-driven Playwright fallback can force identical states.
18
+ */
19
+ forcedStates: ForcedPseudoState[];
20
+ }
21
+ declare const TRACKED_PROPERTIES: string[];
22
+ declare function normalizeInteractionSelector(selector: string): string;
23
+ declare function buildInteractionTargetPlans(selectors: string[]): InteractionTargetPlan[];
24
+ declare function selectInteractionFallbackPlans(plans: InteractionTargetPlan[], emulatedSnapshotMeaningful: boolean): InteractionTargetPlan[];
25
+ declare function mergeComputedStyleSnapshots(...snapshots: ComputedStyleSnapshot[]): ComputedStyleSnapshot;
26
+ declare function captureComputedStyleSnapshotInDom(props: string[]): ComputedStyleSnapshot;
27
+ declare function captureComputedStyleSnapshotForTargetSelectorsInDom(input: {
28
+ props: string[];
29
+ selectors: string[];
30
+ }): ComputedStyleSnapshot;
31
+ declare function collectInteractionTargetPlansInDom(): InteractionTargetPlan[];
32
+ declare function waitForInteractionStylesInDom(): Promise<void>;
33
+ declare function captureEmulatedInteractionStyleSnapshotInDom(props: string[]): Promise<ComputedStyleSnapshot>;
34
+ declare function computedStyleSnapshotToMap(snapshot: ComputedStyleSnapshot): Map<string, Record<string, string>>;
35
+ declare const ESBUILD_NAME_POLYFILL = "var __name = typeof __name !== 'undefined' ? __name : function(fn) { return fn; };";
36
+ declare function buildComputedStyleCaptureExpression(props?: string[]): string;
37
+ declare function buildComputedStyleCaptureJsonExpression(props?: string[]): string;
38
+ declare function parseComputedStyleSnapshot(value: unknown): ComputedStyleSnapshot;
39
+ declare function hasMeaningfulComputedStyleSnapshot(snapshot: ComputedStyleSnapshot): boolean;
40
+ //#endregion
41
+ export { ComputedStyleSnapshot, ESBUILD_NAME_POLYFILL, ForcedPseudoState, InteractionTargetPlan, InteractionType, TRACKED_PROPERTIES, buildComputedStyleCaptureExpression, buildComputedStyleCaptureJsonExpression, buildInteractionTargetPlans, captureComputedStyleSnapshotForTargetSelectorsInDom, captureComputedStyleSnapshotInDom, captureEmulatedInteractionStyleSnapshotInDom, collectInteractionTargetPlansInDom, computedStyleSnapshotToMap, hasMeaningfulComputedStyleSnapshot, mergeComputedStyleSnapshots, normalizeInteractionSelector, parseComputedStyleSnapshot, selectInteractionFallbackPlans, waitForInteractionStylesInDom };