@sloppy-ai/verify 0.0.0-stage → 1.4.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,534 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DOM-backed accessibility verification.
4
+ *
5
+ * The browser collector is deliberately separate from the pure audit function so
6
+ * the checks can be tested with a synthetic role/name/rect snapshot without a
7
+ * browser. This module never claims a pass when the browser is unavailable.
8
+ */
9
+
10
+ import { tryLaunch } from './browser.mjs';
11
+
12
+ const INTERACTIVE_ROLES = new Set([
13
+ 'button', 'link', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio',
14
+ 'switch', 'checkbox', 'radio', 'option', 'slider', 'spinbutton', 'combobox'
15
+ ]);
16
+
17
+ const FORM_TAGS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
18
+
19
+ function overlapsAnotherTarget(item, snapshot) {
20
+ const { x = 0, y = 0, width = 0, height = 0 } = item.rect;
21
+ const cx = x + width / 2;
22
+ const cy = y + height / 2;
23
+ const box = { left: cx - 12, right: cx + 12, top: cy - 12, bottom: cy + 12 };
24
+ return snapshot.some((other) => {
25
+ if (!other || other === item || other.hidden || other.disabled || !other.rect) return false;
26
+ const rect = other.rect;
27
+ if (!Number.isFinite(rect.x) || !Number.isFinite(rect.y)) return false;
28
+ if (!['BUTTON', 'A', 'SUMMARY', 'INPUT', 'SELECT', 'TEXTAREA'].includes(other.tag) && !other.role) return false;
29
+ return rect.x < box.right && rect.x + rect.width > box.left && rect.y < box.bottom && rect.y + rect.height > box.top;
30
+ });
31
+ }
32
+
33
+ export function analyzeFocusOrder(stops) {
34
+ const jumps = [];
35
+ for (let index = 1; index < stops.length; index += 1) {
36
+ const previous = stops[index - 1];
37
+ const current = stops[index];
38
+ if (!previous || !current || current.selector === stops[0]?.selector) continue;
39
+ if (previous.positiveTabindex || current.positiveTabindex) continue;
40
+ const verticalDelta = previous.docTop - current.docTop;
41
+ const horizontalDelta = (previous.docLeft ?? 0) - (current.docLeft ?? 0);
42
+ const verticalJump = verticalDelta > 24;
43
+ const horizontalJump = Math.abs(previous.docTop - current.docTop) <= 8 && horizontalDelta > 50;
44
+ if (verticalJump || horizontalJump) {
45
+ jumps.push({ from: previous.selector, to: current.selector, delta: verticalJump ? verticalDelta : horizontalDelta });
46
+ }
47
+ }
48
+ return jumps;
49
+ }
50
+
51
+ export function auditA11ySnapshot(snapshot, options = {}) {
52
+ const findings = [];
53
+ const push = (rule, message, item, extra = {}) => {
54
+ findings.push({
55
+ rule,
56
+ message,
57
+ severity: extra.severity || 'medium',
58
+ confidence: extra.confidence || 'high',
59
+ objective: extra.objective !== false,
60
+ evidence: {
61
+ kind: extra.kind || 'dom',
62
+ description: message,
63
+ selector: item?.selector,
64
+ viewport: options.viewport,
65
+ criterion: extra.criterion
66
+ }
67
+ });
68
+ };
69
+
70
+ for (const item of snapshot) {
71
+ if (!item || item.hidden || item.disabled) continue;
72
+ const role = String(item.role || '').toLowerCase();
73
+ const isInteractive = INTERACTIVE_ROLES.has(role) || ['BUTTON', 'A', 'SUMMARY'].includes(item.tag);
74
+ const isForm = FORM_TAGS.has(item.tag) && String(item.type || '').toLowerCase() !== 'hidden';
75
+ const hasName = Boolean(String(item.name || '').trim());
76
+
77
+ if ((isInteractive || isForm) && !hasName) {
78
+ const isFormControl = isForm && !['button', 'submit', 'reset'].includes(String(item.type || '').toLowerCase());
79
+ if (isFormControl) {
80
+ push('a11y.inputUnlabeled', `Form control <${item.tag.toLowerCase()}> has no label, aria-label, or labelledby reference.`, item, {
81
+ severity: 'high',
82
+ criterion: 'WCAG 3.3.2 Labels or Instructions / 4.1.2 Name, Role, Value'
83
+ });
84
+ } else {
85
+ push('a11y.nameMissing', `Interactive <${item.tag.toLowerCase()}> has no accessible name.`, item, {
86
+ severity: 'high',
87
+ criterion: 'WCAG 4.1.2 Name, Role, Value'
88
+ });
89
+ }
90
+ }
91
+
92
+ if (item.focusVisible === false && Number(item.tabIndex) >= 0) {
93
+ push('a11y.focusInvisible', `Focused <${item.tag.toLowerCase()}> has no visible outline or focus shadow.`, item, {
94
+ severity: 'medium',
95
+ confidence: 'medium',
96
+ criterion: 'WCAG 2.4.7 Focus Visible'
97
+ });
98
+ }
99
+
100
+ if (isInteractive && item.rect && !item.inlineLink) {
101
+ const { width = 0, height = 0, x, y } = item.rect;
102
+ const undersized = width > 0 && height > 0 && (width < 24 || height < 24);
103
+ const spacingExempt = undersized && Number.isFinite(x) && Number.isFinite(y) && !overlapsAnotherTarget(item, snapshot);
104
+ if (undersized && !spacingExempt) {
105
+ push('a11y.targetTooSmall', `Interactive target is ${Math.round(width)}x${Math.round(height)}px; WCAG 2.2 AA requires at least 24x24 CSS px.`, item, {
106
+ severity: 'medium',
107
+ confidence: 'medium',
108
+ criterion: 'WCAG 2.5.8 Target Size (Minimum)'
109
+ });
110
+ }
111
+ }
112
+
113
+ if (Number(item.explicitTabIndex) > 0) {
114
+ push('a11y.positiveTabindex', `Explicit tabindex="${item.explicitTabIndex}" overrides the natural focus order.`, item, {
115
+ severity: 'medium',
116
+ objective: false,
117
+ criterion: 'WCAG 2.4.3 Focus Order'
118
+ });
119
+ }
120
+
121
+ if (item.ariaExpanded !== undefined && item.ariaExpanded !== null && !item.ariaControls) {
122
+ push('a11y.stateUnwired', `Element exposes aria-expanded="${item.ariaExpanded}" without aria-controls naming the region it expands.`, item, {
123
+ severity: 'medium',
124
+ confidence: 'medium',
125
+ objective: false,
126
+ criterion: 'WCAG 4.1.2 Name, Role, Value'
127
+ });
128
+ }
129
+ }
130
+
131
+ for (const duplicate of options.duplicateIds || []) {
132
+ push('a11y.duplicateId', `Duplicate id "${duplicate}" makes labels and aria references ambiguous.`, { selector: `#${duplicate}` }, {
133
+ severity: 'low',
134
+ confidence: 'high',
135
+ objective: false
136
+ });
137
+ }
138
+
139
+ for (const broken of options.brokenReferences || []) {
140
+ push('a11y.brokenReference', `${broken.attribute} references missing id "${broken.id}".`, { selector: broken.selector }, {
141
+ severity: 'high',
142
+ criterion: 'WCAG 4.1.2 Name, Role, Value'
143
+ });
144
+ }
145
+
146
+ for (const jump of options.focusOrderJumps || []) {
147
+ push('a11y.focusOrderJump', `Tab order moves from "${jump.from}" to "${jump.to}" (${Math.round(Math.abs(jump.delta))}px backwards); confirm the focus sequence follows the visual reading order.`, { selector: jump.to }, {
148
+ severity: 'low',
149
+ confidence: 'low',
150
+ objective: false,
151
+ kind: 'interaction',
152
+ criterion: 'WCAG 2.4.3 Focus Order'
153
+ });
154
+ }
155
+
156
+ if (options.reflowOverflow) {
157
+ push('a11y.reflowOverflow', `At 320 CSS px the page scrolls horizontally (${options.reflowOverflow.scrollWidth}px content in ${options.reflowOverflow.clientWidth}px viewport).`, { selector: 'document' }, {
158
+ severity: 'high',
159
+ criterion: 'WCAG 1.4.10 Reflow'
160
+ });
161
+ }
162
+
163
+ for (const clipped of options.textResizeClipped || []) {
164
+ push('a11y.textResizeClipped', `At 200% text size, text is clipped inside a fixed-height element (${clipped.scrollHeight}px content in ${clipped.clientHeight}px box).`, { selector: clipped.selector }, {
165
+ severity: 'medium',
166
+ confidence: 'medium',
167
+ kind: 'computed-style',
168
+ criterion: 'WCAG 1.4.4 Resize Text'
169
+ });
170
+ }
171
+
172
+ const firstPaint = options.firstPaint;
173
+ if (firstPaint && firstPaint.withJsChars >= 200 && firstPaint.withoutJsChars < firstPaint.withJsChars * 0.5) {
174
+ push('motion.jsDependentFirstPaint', `Without JavaScript the page shows ${firstPaint.withoutJsChars} of ${firstPaint.withJsChars} characters; first paint must render the content, not wait for a script.`, { selector: 'document' }, {
175
+ severity: 'high',
176
+ confidence: 'medium',
177
+ objective: false,
178
+ kind: 'dom'
179
+ });
180
+ }
181
+
182
+ if (options.reducedMotionIgnored) {
183
+ push('a11y.reducedMotionIgnored', 'Infinite animation keeps running under prefers-reduced-motion: reduce.', { selector: 'document' }, {
184
+ severity: 'low',
185
+ confidence: 'low',
186
+ objective: false,
187
+ kind: 'computed-style'
188
+ });
189
+ }
190
+
191
+ for (const item of options.autoplayWithoutControl || []) {
192
+ push('motion.autoplayWithoutControl', `Automatically running motion has no visible pause control (${item.animationName || 'infinite animation'} on ${item.selector}).`, { selector: item.selector }, {
193
+ severity: 'high',
194
+ confidence: 'medium',
195
+ kind: 'computed-style',
196
+ criterion: 'WCAG 2.2.2 Pause, Stop, Hide'
197
+ });
198
+ }
199
+
200
+ for (const item of options.slowFeedback || []) {
201
+ push('motion.slowFeedback', `Interactive feedback takes ${Math.round(item.ms)}ms to transition (${item.selector}); keep hover, press, and focus responses inside roughly 300ms.`, { selector: item.selector }, {
202
+ severity: 'low',
203
+ confidence: 'medium',
204
+ objective: false,
205
+ kind: 'computed-style'
206
+ });
207
+ }
208
+
209
+ return findings;
210
+ }
211
+
212
+ export async function runAccessibilityAudit(target, options = {}) {
213
+ if (!/^https?:\/\//i.test(String(target))) {
214
+ return {
215
+ target,
216
+ ok: false,
217
+ mode: 'static',
218
+ isStaticFallback: true,
219
+ findings: [],
220
+ summary: 'Accessibility audit requires a served http(s) URL; no DOM snapshot was collected.',
221
+ unavailable: 'Accessibility evidence requires a browser and a served URL.'
222
+ };
223
+ }
224
+
225
+ const ownsBrowser = !options.browser;
226
+ const launchResult = options.browser ? { browser: options.browser, reason: null } : await tryLaunch();
227
+ if (!launchResult.browser) {
228
+ return {
229
+ target,
230
+ ok: false,
231
+ mode: 'browser',
232
+ isStaticFallback: false,
233
+ findings: [],
234
+ summary: `Accessibility audit unavailable: ${launchResult.reason}`,
235
+ unavailable: launchResult.reason
236
+ };
237
+ }
238
+
239
+ const browser = launchResult.browser;
240
+ const page = await browser.newPage({ viewport: { width: options.width || 1440, height: options.height || 900 } });
241
+ try {
242
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
243
+ await page.waitForTimeout(options.settleMs ?? 250);
244
+
245
+ const snapshot = await page.evaluate(() => {
246
+ const nameOf = (el) => {
247
+ const aria = el.getAttribute('aria-label')?.trim();
248
+ if (aria) return aria;
249
+ const labelledby = el.getAttribute('aria-labelledby');
250
+ if (labelledby) {
251
+ const text = labelledby.split(/\s+/).map((id) => document.getElementById(id)?.textContent || '').join(' ').trim();
252
+ if (text) return text;
253
+ }
254
+ if (el.tagName === 'IMG') return (el.getAttribute('alt') || '').trim();
255
+ if (el.labels && el.labels.length) {
256
+ const text = [...el.labels].map((label) => (label.innerText || label.textContent || '').trim()).filter(Boolean).join(' ').trim();
257
+ if (text) return text;
258
+ }
259
+ if (el.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) return el.value || '';
260
+ return (el.innerText || el.textContent || '').trim() || (el.getAttribute('title') || '').trim();
261
+ };
262
+ const roleOf = (el) => {
263
+ const explicit = el.getAttribute('role');
264
+ if (explicit) return explicit;
265
+ if (el.tagName === 'BUTTON' || el.tagName === 'SUMMARY') return 'button';
266
+ if (el.tagName === 'A' && el.hasAttribute('href')) return 'link';
267
+ if (el.tagName === 'INPUT') {
268
+ return ({ checkbox: 'checkbox', radio: 'radio', range: 'slider', number: 'spinbutton' })[(el.type || '').toLowerCase()] || 'textbox';
269
+ }
270
+ if (el.tagName === 'SELECT') return 'combobox';
271
+ if (el.tagName === 'TEXTAREA') return 'textbox';
272
+ return '';
273
+ };
274
+ const selectorOf = (el) => {
275
+ if (el.id) return `#${el.id}`;
276
+ const cls = [...el.classList].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
277
+ return `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`;
278
+ };
279
+ const items = [];
280
+ const previousFocus = document.activeElement;
281
+ const all = [...document.querySelectorAll('body *')];
282
+ for (const el of all) {
283
+ const style = getComputedStyle(el);
284
+ if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) continue;
285
+ const rect = el.getBoundingClientRect();
286
+ if (!rect.width || !rect.height) continue;
287
+ const tag = el.tagName;
288
+ const role = roleOf(el);
289
+ const interactive = ['BUTTON', 'A', 'SUMMARY', 'INPUT', 'SELECT', 'TEXTAREA'].includes(tag) || Boolean(el.getAttribute('role'));
290
+ if (!interactive && !el.hasAttribute('aria-expanded')) continue;
291
+ const type = (el.getAttribute('type') || (tag === 'INPUT' ? 'text' : '') || '').toLowerCase();
292
+ if (tag === 'INPUT' && type === 'hidden') continue;
293
+ const labels = el.labels ? [...el.labels] : [];
294
+ const hasLabel = labels.length > 0 || Boolean(el.getAttribute('aria-label') || el.getAttribute('aria-labelledby') || el.getAttribute('title'));
295
+ const focusable = el.tabIndex >= 0 && !el.disabled;
296
+ let focusVisible;
297
+ if (focusable) {
298
+ try { el.focus({ preventScroll: true }); } catch {}
299
+ const focusedStyle = getComputedStyle(el);
300
+ focusVisible = (focusedStyle.outlineStyle !== 'none' && focusedStyle.outlineWidth !== '0px') || focusedStyle.boxShadow !== 'none';
301
+ }
302
+ items.push({
303
+ tag,
304
+ role,
305
+ name: nameOf(el),
306
+ id: el.id || undefined,
307
+ selector: selectorOf(el),
308
+ type,
309
+ hidden: false,
310
+ disabled: Boolean(el.disabled),
311
+ rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
312
+ tabIndex: el.tabIndex,
313
+ explicitTabIndex: el.getAttribute('tabindex'),
314
+ inlineLink: tag === 'A' && style.display === 'inline',
315
+ hasLabel,
316
+ focusVisible,
317
+ ariaExpanded: el.getAttribute('aria-expanded'),
318
+ ariaControls: el.getAttribute('aria-controls') || undefined
319
+ });
320
+ }
321
+
322
+ if (previousFocus && previousFocus !== document.body && typeof previousFocus.focus === 'function') {
323
+ try { previousFocus.focus({ preventScroll: true }); } catch {}
324
+ }
325
+
326
+ const ids = new Map();
327
+ for (const el of document.querySelectorAll('[id]')) ids.set(el.id, (ids.get(el.id) || 0) + 1);
328
+ const duplicateIds = [...ids.entries()].filter(([, count]) => count > 1).map(([id]) => id);
329
+
330
+ const brokenReferences = [];
331
+ for (const el of document.querySelectorAll('[aria-labelledby], [aria-describedby], [aria-controls], [aria-owns]')) {
332
+ for (const attribute of ['aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-owns']) {
333
+ const value = el.getAttribute(attribute);
334
+ if (!value) continue;
335
+ for (const id of value.split(/\s+/).filter(Boolean)) {
336
+ if (!document.getElementById(id)) brokenReferences.push({ attribute, id, selector: selectorOf(el) });
337
+ }
338
+ }
339
+ }
340
+
341
+ return { items, duplicateIds, brokenReferences };
342
+ });
343
+
344
+ let focusOrderJumps = [];
345
+ if (options.checkFocusOrder !== false) {
346
+ await page.evaluate(() => window.scrollTo(0, 0));
347
+ const stops = [];
348
+ for (let index = 0; index < 30; index += 1) {
349
+ await page.keyboard.press('Tab');
350
+ const stop = await page.evaluate(() => {
351
+ const el = document.activeElement;
352
+ if (!el || el === document.body || el === document.documentElement) return null;
353
+ const rect = el.getBoundingClientRect();
354
+ const label = el.getAttribute('aria-label') || (el.innerText || el.textContent || el.tagName).trim().slice(0, 40);
355
+ return {
356
+ selector: el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${label ? `[${label}]` : ''}`,
357
+ docTop: rect.top + window.scrollY,
358
+ docLeft: rect.left,
359
+ positiveTabindex: Number(el.getAttribute('tabindex')) > 0
360
+ };
361
+ });
362
+ if (stop) stops.push(stop);
363
+ if (stops.length > 2 && stop?.selector === stops[0]?.selector) break;
364
+ }
365
+ focusOrderJumps = analyzeFocusOrder(stops);
366
+ }
367
+
368
+ const viewport = page.viewportSize();
369
+ let autoplayWithoutControl = [];
370
+ let slowFeedback = [];
371
+ if (options.checkMotionBudget !== false) {
372
+ try {
373
+ const motion = await page.evaluate(() => {
374
+ const label = (el) => {
375
+ const cls = [...(el.classList || [])].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
376
+ return el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`;
377
+ };
378
+ const pauseControl = [...document.querySelectorAll('button, [role="button"], a')]
379
+ .some((el) => /pause|stop playback|stop animation/i.test(`${el.getAttribute('aria-label') || ''} ${el.getAttribute('title') || ''} ${el.textContent || ''}`));
380
+ const viewportArea = Math.max(1, window.innerWidth * window.innerHeight);
381
+ const autoplay = [];
382
+ for (const animation of document.getAnimations?.() || []) {
383
+ const timing = animation.effect?.getTiming?.();
384
+ if (!timing || timing.iterations !== Infinity || animation.playState !== 'running') continue;
385
+ if (pauseControl) continue;
386
+ const el = animation.effect?.target;
387
+ if (!el || el.nodeType !== 1) continue;
388
+ const rect = el.getBoundingClientRect();
389
+ const area = Math.max(0, rect.width) * Math.max(0, rect.height);
390
+ const name = `${animation.animationName || ''} ${el.className || ''} ${el.id || ''}`.toLowerCase();
391
+ const named = /marquee|ticker|carousel|autoplay|logo-scroll/.test(name);
392
+ if (!named && area < viewportArea * 0.25) continue;
393
+ autoplay.push({ selector: label(el), animationName: animation.animationName || 'infinite animation' });
394
+ if (autoplay.length >= 5) break;
395
+ }
396
+ const slow = [];
397
+ for (const el of document.querySelectorAll('a, button, input, select, textarea, summary, [role="button"]')) {
398
+ const style = getComputedStyle(el);
399
+ if (style.transitionProperty === 'none') continue;
400
+ const durations = style.transitionDuration.split(',').map((value) => {
401
+ const trimmed = value.trim();
402
+ const number = Number.parseFloat(trimmed);
403
+ if (!Number.isFinite(number)) return 0;
404
+ return /ms$/.test(trimmed) ? number : number * 1000;
405
+ });
406
+ const ms = Math.max(0, ...durations);
407
+ if (ms < 600) continue;
408
+ slow.push({ selector: label(el), ms });
409
+ if (slow.length >= 5) break;
410
+ }
411
+ return { autoplay, slow };
412
+ });
413
+ autoplayWithoutControl = motion.autoplay;
414
+ slowFeedback = motion.slow;
415
+ } catch {}
416
+ }
417
+
418
+ let firstPaint = null;
419
+ if (options.checkFirstPaint !== false) {
420
+ const visibleChars = () => {
421
+ const hidden = (el) => {
422
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
423
+ const style = getComputedStyle(node);
424
+ if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return true;
425
+ }
426
+ return false;
427
+ };
428
+ let total = 0;
429
+ for (const el of document.querySelectorAll('main, header, section, article, h1, h2, h3, p, li, blockquote, figcaption')) {
430
+ if (!hidden(el)) total += (el.innerText || '').trim().length;
431
+ }
432
+ return total;
433
+ };
434
+ const withJsChars = await page.evaluate(visibleChars);
435
+ let context;
436
+ let withoutJsChars = null;
437
+ try {
438
+ context = await browser.newContext({ javaScriptEnabled: false, viewport: viewport || { width: options.width || 1440, height: options.height || 900 } });
439
+ const staticPage = await context.newPage();
440
+ await staticPage.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
441
+ await staticPage.waitForTimeout(150);
442
+ withoutJsChars = await staticPage.evaluate(visibleChars);
443
+ } catch {
444
+ withoutJsChars = null;
445
+ } finally {
446
+ await context?.close().catch(() => {});
447
+ }
448
+ if (withoutJsChars !== null) firstPaint = { withJsChars, withoutJsChars };
449
+ }
450
+
451
+ let reflowOverflow = null;
452
+ let textResizeClipped = [];
453
+ try {
454
+ await page.setViewportSize({ width: 320, height: 800 });
455
+ await page.waitForTimeout(120);
456
+ const reflow = await page.evaluate(() => ({
457
+ scrollWidth: document.documentElement.scrollWidth,
458
+ clientWidth: document.documentElement.clientWidth
459
+ }));
460
+ if (reflow.scrollWidth > reflow.clientWidth + 1) reflowOverflow = reflow;
461
+
462
+ await page.evaluate(() => { document.documentElement.style.fontSize = '32px'; });
463
+ await page.waitForTimeout(120);
464
+ textResizeClipped = await page.evaluate(() => {
465
+ const clipped = [];
466
+ for (const el of document.querySelectorAll('body *')) {
467
+ const style = getComputedStyle(el);
468
+ if (style.overflow !== 'hidden' && style.overflowY !== 'hidden') continue;
469
+ const text = (el.innerText || el.textContent || '').trim();
470
+ if (!text || el.children.length > 0) continue;
471
+ if (el.scrollHeight > el.clientHeight + 2) {
472
+ const cls = [...el.classList].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
473
+ clipped.push({ selector: el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight });
474
+ }
475
+ if (clipped.length >= 5) break;
476
+ }
477
+ return clipped;
478
+ });
479
+ await page.evaluate(() => { document.documentElement.style.fontSize = ''; });
480
+ } finally {
481
+ if (viewport) await page.setViewportSize(viewport);
482
+ }
483
+
484
+ let reducedMotionIgnored = false;
485
+ if (options.checkReducedMotion !== false) {
486
+ await page.emulateMedia({ reducedMotion: 'reduce' });
487
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
488
+ await page.waitForTimeout(150);
489
+ reducedMotionIgnored = await page.evaluate(() => (document.getAnimations?.() || []).some((animation) => {
490
+ const timing = animation.effect?.getTiming?.();
491
+ return animation.playState === 'running' && timing && timing.iterations === Infinity;
492
+ }));
493
+ }
494
+
495
+ const findings = auditA11ySnapshot(snapshot.items, {
496
+ duplicateIds: snapshot.duplicateIds,
497
+ brokenReferences: snapshot.brokenReferences,
498
+ focusOrderJumps,
499
+ reflowOverflow,
500
+ textResizeClipped,
501
+ reducedMotionIgnored,
502
+ firstPaint,
503
+ autoplayWithoutControl,
504
+ slowFeedback,
505
+ viewport: { width: options.width || 1440, height: options.height || 900 }
506
+ });
507
+
508
+ return {
509
+ target,
510
+ ok: findings.length === 0,
511
+ mode: 'browser',
512
+ isStaticFallback: false,
513
+ findings,
514
+ summary: findings.length
515
+ ? `Found ${findings.length} accessibility issue(s) in the rendered DOM.`
516
+ : 'Rendered DOM passes the name, label, focus, target-size, reference, reflow, text-resize, reduced-motion, and motion-budget checks.',
517
+ checked: ['accessible name', 'form labels', 'focus visibility', 'focus order', 'target size 24x24', 'aria references', 'reflow at 320px', '200% text resize', 'reduced motion', 'first paint without JavaScript', 'autoplay pause control', 'interaction transition duration']
518
+ };
519
+ } catch (error) {
520
+ const reason = String(error?.message || error).split('\n')[0];
521
+ return {
522
+ target,
523
+ ok: false,
524
+ mode: 'browser',
525
+ isStaticFallback: false,
526
+ findings: [],
527
+ summary: `Accessibility audit failed: ${reason}`,
528
+ unavailable: reason
529
+ };
530
+ } finally {
531
+ await page.close();
532
+ if (ownsBrowser) await browser.close();
533
+ }
534
+ }
package/browser.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Headless browser loader with graceful static fallback detection.
2
+ // playwright-core is optional: when unavailable, Sloppy gracefully falls back
3
+ // to static source-scan multi-width and contrast simulation.
4
+
5
+ export async function tryLaunch() {
6
+ let chromium;
7
+ try {
8
+ ;({ chromium } = await import('playwright-core'));
9
+ } catch (err) {
10
+ return { browser: null, reason: 'playwright-core not installed' };
11
+ }
12
+
13
+ const path = process.env.CHROME_PATH;
14
+ try {
15
+ const browser = await chromium.launch(path ? { executablePath: path } : { channel: 'chrome', headless: true });
16
+ return { browser, reason: null };
17
+ } catch (err) {
18
+ return { browser: null, reason: `Chrome launch failed: ${err?.message || err}` };
19
+ }
20
+ }
21
+
22
+ export async function launch() {
23
+ const result = await tryLaunch();
24
+ if (!result.browser) {
25
+ console.error(`[BROWSER LAUNCH FAILED] ${result.reason}`);
26
+ console.error('Install Google Chrome or install playwright-core: `npm i -D playwright-core`');
27
+ process.exit(2);
28
+ }
29
+ return result.browser;
30
+ }