@mizchi/vlmkit-core 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,384 @@
1
+ import type {
2
+ A11yNode,
3
+ A11yChange,
4
+ A11yDiff,
5
+ A11ySnapshot,
6
+ } from "./types.ts";
7
+
8
+ export const LANDMARK_ROLES = new Set([
9
+ "banner",
10
+ "complementary",
11
+ "contentinfo",
12
+ "form",
13
+ "main",
14
+ "navigation",
15
+ "region",
16
+ "search",
17
+ ]);
18
+
19
+ export const INTERACTIVE_ROLES = new Set([
20
+ "button",
21
+ "checkbox",
22
+ "combobox",
23
+ "link",
24
+ "listbox",
25
+ "menu",
26
+ "menubar",
27
+ "menuitem",
28
+ "option",
29
+ "radio",
30
+ "scrollbar",
31
+ "searchbox",
32
+ "slider",
33
+ "spinbutton",
34
+ "switch",
35
+ "tab",
36
+ "tabpanel",
37
+ "textbox",
38
+ "treeitem",
39
+ ]);
40
+
41
+ /**
42
+ * Compare two a11y tree snapshots and return the semantic diff.
43
+ */
44
+ export function diffA11yTrees(
45
+ baseline: A11ySnapshot,
46
+ current: A11ySnapshot
47
+ ): A11yDiff {
48
+ const changes: A11yChange[] = [];
49
+ diffNodes(baseline.tree, current.tree, "", changes);
50
+
51
+ const landmarkChanges = changes.filter((c) => c.type === "landmark-changed");
52
+ const hasRegression = changes.some((c) => c.severity === "error");
53
+
54
+ return {
55
+ testId: current.testId,
56
+ changes,
57
+ hasRegression,
58
+ landmarkChanges,
59
+ stats: {
60
+ added: changes.filter((c) => c.type === "node-added").length,
61
+ removed: changes.filter((c) => c.type === "node-removed").length,
62
+ modified: changes.filter(
63
+ (c) =>
64
+ c.type !== "node-added" &&
65
+ c.type !== "node-removed"
66
+ ).length,
67
+ },
68
+ };
69
+ }
70
+
71
+ function diffNodes(
72
+ before: A11yNode | undefined,
73
+ after: A11yNode | undefined,
74
+ path: string,
75
+ changes: A11yChange[]
76
+ ): void {
77
+ const nodePath = path
78
+ ? `${path} > ${nodeLabel(after ?? before!)}`
79
+ : nodeLabel(after ?? before!);
80
+
81
+ // Node added
82
+ if (!before && after) {
83
+ changes.push({
84
+ type: isLandmark(after) ? "landmark-changed" : "node-added",
85
+ path: nodePath,
86
+ after: nodeSnapshot(after),
87
+ severity: "info",
88
+ description: `Added ${after.role}${after.name ? ` "${after.name}"` : ""}`,
89
+ });
90
+ // Don't record children as added (included in parent addition)
91
+ return;
92
+ }
93
+
94
+ // Node removed
95
+ if (before && !after) {
96
+ const severity = isLandmark(before)
97
+ ? "error" // landmark removal is critical
98
+ : isInteractive(before)
99
+ ? "error" // interactive element removal is regression
100
+ : "warning";
101
+
102
+ changes.push({
103
+ type: isLandmark(before) ? "landmark-changed" : "node-removed",
104
+ path: nodePath,
105
+ before: nodeSnapshot(before),
106
+ severity,
107
+ description: `Removed ${before.role}${before.name ? ` "${before.name}"` : ""}`,
108
+ });
109
+ return;
110
+ }
111
+
112
+ if (!before || !after) return;
113
+
114
+ // role change
115
+ if (before.role !== after.role) {
116
+ changes.push({
117
+ type: "role-changed",
118
+ path: nodePath,
119
+ before: { role: before.role },
120
+ after: { role: after.role },
121
+ severity: isInteractive(before) || isInteractive(after) ? "error" : "warning",
122
+ description: `Role changed from "${before.role}" to "${after.role}"`,
123
+ });
124
+ }
125
+
126
+ // name change
127
+ if (before.name !== after.name) {
128
+ const severity =
129
+ isInteractive(before) && !after.name
130
+ ? "error" // label loss is regression
131
+ : "info";
132
+
133
+ changes.push({
134
+ type: "name-changed",
135
+ path: nodePath,
136
+ before: { name: before.name },
137
+ after: { name: after.name },
138
+ severity,
139
+ description: after.name
140
+ ? `Name changed from "${before.name}" to "${after.name}"`
141
+ : `Name removed (was "${before.name}")`,
142
+ });
143
+ }
144
+
145
+ // state change (checked, disabled, expanded, pressed, selected)
146
+ const stateKeys = ["checked", "disabled", "expanded", "pressed", "selected"] as const;
147
+ for (const key of stateKeys) {
148
+ if (before[key] !== after[key]) {
149
+ changes.push({
150
+ type: "state-changed",
151
+ path: nodePath,
152
+ before: { [key]: before[key] },
153
+ after: { [key]: after[key] },
154
+ severity: "info",
155
+ description: `${key} changed from ${before[key]} to ${after[key]}`,
156
+ });
157
+ }
158
+ }
159
+
160
+ // Child node diff (order-based matching + role+name key matching)
161
+ const beforeChildren = before.children ?? [];
162
+ const afterChildren = after.children ?? [];
163
+ diffChildren(beforeChildren, afterChildren, nodePath, changes);
164
+ }
165
+
166
+ /**
167
+ * Diff child node lists.
168
+ * 1) Exact match by role+name
169
+ * 2) Position-based matching for remaining -> detect role/name changes
170
+ * 3) Remainder is additions/removals
171
+ */
172
+ function diffChildren(
173
+ beforeChildren: A11yNode[],
174
+ afterChildren: A11yNode[],
175
+ parentPath: string,
176
+ changes: A11yChange[]
177
+ ): void {
178
+ const matched = new Set<number>(); // matched indices in beforeChildren
179
+ const afterMatched = new Set<number>();
180
+
181
+ // Pass 1: exact role+name match
182
+ const beforeByKey = new Map<string, { node: A11yNode; index: number }[]>();
183
+ for (let i = 0; i < beforeChildren.length; i++) {
184
+ const key = childKey(beforeChildren[i]);
185
+ const list = beforeByKey.get(key) ?? [];
186
+ list.push({ node: beforeChildren[i], index: i });
187
+ beforeByKey.set(key, list);
188
+ }
189
+
190
+ for (let ai = 0; ai < afterChildren.length; ai++) {
191
+ const key = childKey(afterChildren[ai]);
192
+ const candidates = beforeByKey.get(key);
193
+ if (candidates && candidates.length > 0) {
194
+ const match = candidates.shift()!;
195
+ matched.add(match.index);
196
+ afterMatched.add(ai);
197
+ diffNodes(match.node, afterChildren[ai], parentPath, changes);
198
+ }
199
+ }
200
+
201
+ // Pass 2: position-based matching (detect role or name changes)
202
+ const unmatchedBefore: { node: A11yNode; index: number }[] = [];
203
+ for (let i = 0; i < beforeChildren.length; i++) {
204
+ if (!matched.has(i)) unmatchedBefore.push({ node: beforeChildren[i], index: i });
205
+ }
206
+ const unmatchedAfter: { node: A11yNode; index: number }[] = [];
207
+ for (let i = 0; i < afterChildren.length; i++) {
208
+ if (!afterMatched.has(i)) unmatchedAfter.push({ node: afterChildren[i], index: i });
209
+ }
210
+
211
+ // role-only or name-only match for pairing
212
+ const stillUnmatchedBefore: typeof unmatchedBefore = [];
213
+ const stillUnmatchedAfter = new Set(unmatchedAfter.map((_, i) => i));
214
+
215
+ for (const b of unmatchedBefore) {
216
+ let found = false;
217
+ for (let j = 0; j < unmatchedAfter.length; j++) {
218
+ if (!stillUnmatchedAfter.has(j)) continue;
219
+ const a = unmatchedAfter[j];
220
+ // role or name match -> pair (diff as change)
221
+ if (
222
+ b.node.role === a.node.role ||
223
+ (b.node.name && b.node.name === a.node.name)
224
+ ) {
225
+ stillUnmatchedAfter.delete(j);
226
+ diffNodes(b.node, a.node, parentPath, changes);
227
+ found = true;
228
+ break;
229
+ }
230
+ }
231
+ if (!found) {
232
+ stillUnmatchedBefore.push(b);
233
+ }
234
+ }
235
+
236
+ // Pass 3: remainder is additions/removals
237
+ for (const b of stillUnmatchedBefore) {
238
+ diffNodes(b.node, undefined, parentPath, changes);
239
+ }
240
+ for (const j of stillUnmatchedAfter) {
241
+ diffNodes(undefined, unmatchedAfter[j].node, parentPath, changes);
242
+ }
243
+
244
+ // Detect structural changes (significant child count change)
245
+ const countDiff = Math.abs(afterChildren.length - beforeChildren.length);
246
+ if (countDiff > 3 && countDiff / Math.max(beforeChildren.length, 1) > 0.3) {
247
+ changes.push({
248
+ type: "structure-changed",
249
+ path: parentPath,
250
+ before: { name: `${beforeChildren.length} children` },
251
+ after: { name: `${afterChildren.length} children` },
252
+ severity: "warning",
253
+ description: `Structure changed significantly: ${beforeChildren.length} → ${afterChildren.length} children`,
254
+ });
255
+ }
256
+ }
257
+
258
+ function childKey(node: A11yNode): string {
259
+ return `${node.role}:${node.name ?? ""}`;
260
+ }
261
+
262
+ function nodeLabel(node: A11yNode): string {
263
+ const name = node.name ? `[${node.name}]` : "";
264
+ return `${node.role}${name}`;
265
+ }
266
+
267
+ function nodeSnapshot(node: A11yNode): Partial<A11yNode> {
268
+ return {
269
+ role: node.role,
270
+ name: node.name,
271
+ ...(node.level !== undefined && { level: node.level }),
272
+ ...(node.checked !== undefined && { checked: node.checked }),
273
+ ...(node.disabled !== undefined && { disabled: node.disabled }),
274
+ ...(node.expanded !== undefined && { expanded: node.expanded }),
275
+ };
276
+ }
277
+
278
+ function isLandmark(node: A11yNode): boolean {
279
+ return LANDMARK_ROLES.has(node.role);
280
+ }
281
+
282
+ function isInteractive(node: A11yNode): boolean {
283
+ return INTERACTIVE_ROLES.has(node.role);
284
+ }
285
+
286
+ // ---- A11y Quality Checks ----
287
+
288
+ /**
289
+ * A11y tree quality checks (standalone, no diff).
290
+ *
291
+ * Walks the tree and returns issues such as missing labels on
292
+ * interactive elements and missing alt text on images.
293
+ *
294
+ * @since 0.5.0 — replaces `checkA11yTree`.
295
+ */
296
+ export function verifyA11yTree(tree: A11yNode): A11yIssue[] {
297
+ const issues: A11yIssue[] = [];
298
+ walkTree(tree, "", issues);
299
+ return issues;
300
+ }
301
+
302
+ /**
303
+ * @deprecated since 0.5.0 — use `verifyA11yTree` instead. Removed in 1.0.0.
304
+ */
305
+ export const checkA11yTree = verifyA11yTree;
306
+
307
+ export interface A11yIssue {
308
+ path: string;
309
+ rule: string;
310
+ severity: "error" | "warning";
311
+ message: string;
312
+ }
313
+
314
+ function walkTree(node: A11yNode, path: string, issues: A11yIssue[]): void {
315
+ const nodePath = path ? `${path} > ${nodeLabel(node)}` : nodeLabel(node);
316
+
317
+ // Interactive elements without labels
318
+ if (isInteractive(node) && !node.name) {
319
+ issues.push({
320
+ path: nodePath,
321
+ rule: "label-missing",
322
+ severity: "error",
323
+ message: `Interactive element "${node.role}" has no accessible name`,
324
+ });
325
+ }
326
+
327
+ // Images without alt (role=img with no name)
328
+ if (node.role === "img" && !node.name) {
329
+ issues.push({
330
+ path: nodePath,
331
+ rule: "img-alt-missing",
332
+ severity: "error",
333
+ message: "Image has no accessible name (missing alt text)",
334
+ });
335
+ }
336
+
337
+ // Heading level skip detection needs parent context,
338
+ // so only individual node checks here
339
+
340
+ for (const child of node.children ?? []) {
341
+ walkTree(child, nodePath, issues);
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Convert Playwright page.accessibility.snapshot() output to A11ySnapshot.
347
+ */
348
+ export function parsePlaywrightA11ySnapshot(
349
+ testId: string,
350
+ testTitle: string,
351
+ raw: Record<string, unknown>
352
+ ): A11ySnapshot {
353
+ return {
354
+ testId,
355
+ testTitle,
356
+ tree: normalizeA11yNode(raw),
357
+ };
358
+ }
359
+
360
+ function normalizeA11yNode(raw: Record<string, unknown>): A11yNode {
361
+ return {
362
+ role: (raw.role as string) ?? "none",
363
+ name: (raw.name as string) ?? "",
364
+ ...(raw.level !== undefined && { level: raw.level as number }),
365
+ ...(raw.value !== undefined && { value: raw.value as string }),
366
+ ...(raw.description !== undefined && {
367
+ description: raw.description as string,
368
+ }),
369
+ ...(raw.checked !== undefined && {
370
+ checked: raw.checked as boolean | "mixed",
371
+ }),
372
+ ...(raw.disabled !== undefined && { disabled: raw.disabled as boolean }),
373
+ ...(raw.expanded !== undefined && { expanded: raw.expanded as boolean }),
374
+ ...(raw.pressed !== undefined && {
375
+ pressed: raw.pressed as boolean | "mixed",
376
+ }),
377
+ ...(raw.selected !== undefined && { selected: raw.selected as boolean }),
378
+ ...(raw.children ? {
379
+ children: (raw.children as Record<string, unknown>[]).map(
380
+ normalizeA11yNode
381
+ ),
382
+ } : {}),
383
+ };
384
+ }