@mizchi/vlmkit-core 0.6.0 → 0.8.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.
@@ -1,387 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Accessibility / WCAG contrast check.
4
- *
5
- * Use case: agent writes new HTML/CSS, doesn't notice that the muted
6
- * `color: #9ca3af` on `background: #ffffff` only hits 2.9:1 contrast
7
- * — below WCAG AA's 4.5:1 for body text. Tool scans every visible
8
- * text-bearing element, computes its actual text-vs-background
9
- * contrast ratio via WCAG formula, and reports failures.
10
- *
11
- * Implementation:
12
- * 1. Playwright renders the HTML.
13
- * 2. In-browser script walks visible text nodes, reads
14
- * `getComputedStyle(el).color` for foreground and walks up the
15
- * ancestor chain for the first non-transparent background.
16
- * Returns text + colors + font size + bbox.
17
- * 3. Compute WCAG luminance + contrast ratio. Flag elements below
18
- * 4.5:1 (or 3.0:1 for "large text" ≥ 18px or ≥ 14px-bold).
19
- *
20
- * Unlike axe-core / pa11y which require a DOM-aware semantic scan,
21
- * this is purely visual — works on any page that renders text.
22
- *
23
- * Usage:
24
- * vrt a11y-contrast <html>
25
- */
26
- import { readFile, writeFile, mkdir } from "node:fs/promises";
27
- import { join, resolve } from "node:path";
28
- import { fileURLToPath } from "node:url";
29
- import { chromium } from "playwright";
30
- import { DIM, RESET, GREEN, RED, YELLOW, BOLD, CYAN } from "./terminal-colors.ts";
31
- import { handleCliError } from "./cli-error.ts";
32
-
33
- export interface A11yContrastOptions {
34
- htmlPath: string;
35
- outputDir: string;
36
- reportPath?: string;
37
- viewport?: { width: number; height: number };
38
- /** Min text length to bother analyzing. Default 1. */
39
- minTextLength?: number;
40
- }
41
-
42
- export type WcagLevel = "AAA" | "AA" | "AA-large" | "fail";
43
-
44
- export interface ContrastFinding {
45
- path: string;
46
- tag: string;
47
- text: string;
48
- fontSize: number;
49
- fontWeight: number;
50
- bbox: { x: number; y: number; width: number; height: number };
51
- foreground: { r: number; g: number; b: number; hex: string };
52
- background: { r: number; g: number; b: number; hex: string };
53
- /** Computed WCAG contrast ratio (1 = identical, 21 = max black/white). */
54
- ratio: number;
55
- /** Required threshold based on font size/weight. 4.5 for normal text, 3.0 for large. */
56
- requiredAA: number;
57
- level: WcagLevel;
58
- }
59
-
60
- export interface A11yContrastReport {
61
- html: string;
62
- viewport: { width: number; height: number };
63
- screenshot: string;
64
- totalText: number;
65
- failures: ContrastFinding[];
66
- reportPath: string;
67
- }
68
-
69
- export const A11Y_CONTRAST_SAMPLE_SCRIPT = `
70
- (function a11ySample(minLen) {
71
- function parseColor(s) {
72
- if (!s) return null;
73
- const m = s.match(/rgba?\\(([^)]+)\\)/);
74
- if (!m) return null;
75
- const parts = m[1].split(",").map((x) => parseFloat(x.trim()));
76
- const r = parts[0], g = parts[1], b = parts[2], a = parts.length >= 4 ? parts[3] : 1;
77
- return { r: r|0, g: g|0, b: b|0, a };
78
- }
79
- function effectiveBg(el) {
80
- let cur = el;
81
- while (cur && cur !== document.documentElement) {
82
- const cs = getComputedStyle(cur);
83
- const c = parseColor(cs.backgroundColor);
84
- if (c && c.a >= 0.5) return c;
85
- cur = cur.parentElement;
86
- }
87
- // Fallback to html background or white.
88
- const htmlBg = parseColor(getComputedStyle(document.documentElement).backgroundColor);
89
- if (htmlBg && htmlBg.a >= 0.5) return htmlBg;
90
- return { r: 255, g: 255, b: 255, a: 1 };
91
- }
92
- function shortPath(el) {
93
- const parts = [];
94
- let cur = el;
95
- while (cur && cur !== document.body && parts.length < 5) {
96
- let p = cur.tagName.toLowerCase();
97
- if (cur.id) p += "#" + cur.id;
98
- else if (cur.className && typeof cur.className === "string") {
99
- const cls = cur.className.trim().split(/\\s+/).slice(0, 2).join(".");
100
- if (cls) p += "." + cls;
101
- }
102
- parts.unshift(p);
103
- cur = cur.parentElement;
104
- }
105
- return parts.join(">");
106
- }
107
- const out = [];
108
- const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
109
- let node;
110
- while ((node = walker.nextNode())) {
111
- const text = (node.nodeValue || "").trim();
112
- if (text.length < minLen) continue;
113
- const el = node.parentElement;
114
- if (!el) continue;
115
- if (el.tagName === "SCRIPT" || el.tagName === "STYLE" || el.tagName === "NOSCRIPT") continue;
116
- const cs = getComputedStyle(el);
117
- if (cs.visibility === "hidden" || cs.display === "none" || parseFloat(cs.opacity) < 0.5) continue;
118
- const r = el.getBoundingClientRect();
119
- if (r.width < 1 || r.height < 1) continue;
120
- const fg = parseColor(cs.color);
121
- if (!fg) continue;
122
- const bg = effectiveBg(el);
123
- const fontSize = parseFloat(cs.fontSize) || 16;
124
- const fontWeight = parseInt(cs.fontWeight, 10) || 400;
125
- out.push({
126
- path: shortPath(el),
127
- tag: el.tagName.toLowerCase(),
128
- text: text.slice(0, 60),
129
- fontSize, fontWeight,
130
- bbox: { x: r.x, y: r.y, width: r.width, height: r.height },
131
- foreground: { r: fg.r, g: fg.g, b: fg.b },
132
- background: { r: bg.r, g: bg.g, b: bg.b },
133
- });
134
- if (out.length > 500) break;
135
- }
136
- return out;
137
- })
138
- `;
139
-
140
- export interface A11yContrastRawSample {
141
- path: string;
142
- tag: string;
143
- text: string;
144
- fontSize: number;
145
- fontWeight: number;
146
- bbox: { x: number; y: number; width: number; height: number };
147
- foreground: { r: number; g: number; b: number };
148
- background: { r: number; g: number; b: number };
149
- }
150
-
151
- function relLuma(r: number, g: number, b: number): number {
152
- // WCAG relative luminance formula.
153
- const s = (c: number) => {
154
- const v = c / 255;
155
- return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
156
- };
157
- return 0.2126 * s(r) + 0.7152 * s(g) + 0.0722 * s(b);
158
- }
159
-
160
- function contrastRatio(a: { r: number; g: number; b: number }, b: { r: number; g: number; b: number }): number {
161
- const la = relLuma(a.r, a.g, a.b);
162
- const lb = relLuma(b.r, b.g, b.b);
163
- const lighter = Math.max(la, lb);
164
- const darker = Math.min(la, lb);
165
- return (lighter + 0.05) / (darker + 0.05);
166
- }
167
-
168
- function toHex(c: { r: number; g: number; b: number }): string {
169
- const h = (n: number) => n.toString(16).padStart(2, "0");
170
- return `#${h(c.r)}${h(c.g)}${h(c.b)}`;
171
- }
172
-
173
- /**
174
- * Build the list of contrast failures from raw samples (post-process
175
- * step extracted from `runA11yContrast`). Pure — no I/O — so it can
176
- * be invoked over Playwright pages owned by other modules (e.g. the
177
- * `vrt diff-pr` CI gate calls this without spinning up a second
178
- * browser instance per route).
179
- */
180
- export function analyzeA11yContrastSamples(samples: A11yContrastRawSample[]): ContrastFinding[] {
181
- const byPath = new Map<string, A11yContrastRawSample>();
182
- for (const s of samples) if (!byPath.has(s.path)) byPath.set(s.path, s);
183
- const findings: ContrastFinding[] = [];
184
- for (const s of byPath.values()) {
185
- const ratio = contrastRatio(s.foreground, s.background);
186
- const { requiredAA, level } = classify(ratio, s.fontSize, s.fontWeight);
187
- if (level !== "fail") continue;
188
- findings.push({
189
- path: s.path,
190
- tag: s.tag,
191
- text: s.text,
192
- fontSize: s.fontSize,
193
- fontWeight: s.fontWeight,
194
- bbox: s.bbox,
195
- foreground: { ...s.foreground, hex: toHex(s.foreground) },
196
- background: { ...s.background, hex: toHex(s.background) },
197
- ratio: Number(ratio.toFixed(2)),
198
- requiredAA,
199
- level,
200
- });
201
- }
202
- findings.sort((a, b) => a.ratio - b.ratio);
203
- return findings;
204
- }
205
-
206
- function classify(ratio: number, fontSize: number, fontWeight: number): { requiredAA: number; level: WcagLevel } {
207
- // WCAG 2.1 "large text" threshold: ≥ 18px regular, or ≥ 14px bold (≥ 700).
208
- const isLarge = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700);
209
- const requiredAA = isLarge ? 3.0 : 4.5;
210
- let level: WcagLevel = "fail";
211
- if (ratio >= 7) level = "AAA";
212
- else if (ratio >= 4.5) level = "AA";
213
- else if (ratio >= 3 && isLarge) level = "AA-large";
214
- return { requiredAA, level };
215
- }
216
-
217
- function parseArgs(argv: string[]) {
218
- let outputDir = "";
219
- let report = "";
220
- const positional: string[] = [];
221
- for (let i = 0; i < argv.length; i++) {
222
- const a = argv[i];
223
- if (a === "--output-dir") outputDir = argv[++i];
224
- else if (a === "--report") report = argv[++i];
225
- else positional.push(a);
226
- }
227
- return { positional, outputDir, report };
228
- }
229
-
230
- export async function runA11yContrast(
231
- options: A11yContrastOptions,
232
- ): Promise<A11yContrastReport> {
233
- const outputDir = resolve(options.outputDir);
234
- await mkdir(outputDir, { recursive: true });
235
- const htmlPath = resolve(options.htmlPath);
236
- const html = await readFile(htmlPath, "utf-8");
237
- const viewport = options.viewport ?? { width: 1280, height: 900 };
238
- const minLen = options.minTextLength ?? 1;
239
-
240
- const browser = await chromium.launch();
241
- let samples: A11yContrastRawSample[];
242
- let screenshotPath: string;
243
- try {
244
- const page = await browser.newPage({ viewport });
245
- await page.setContent(html, { waitUntil: "networkidle" });
246
- await page.addStyleTag({
247
- content: `*, *::before, *::after { transition: none !important; animation: none !important; }`,
248
- });
249
- samples = await page.evaluate(`(${A11Y_CONTRAST_SAMPLE_SCRIPT})(${minLen})`) as A11yContrastRawSample[];
250
- screenshotPath = join(outputDir, "page.png");
251
- await page.screenshot({ path: screenshotPath, fullPage: false });
252
- await page.close();
253
- } finally {
254
- await browser.close();
255
- }
256
-
257
- // Dedupe by path — many text nodes from the same element produce
258
- // identical findings.
259
- const byPath = new Map<string, A11yContrastRawSample>();
260
- for (const s of samples) {
261
- if (!byPath.has(s.path)) byPath.set(s.path, s);
262
- }
263
-
264
- const findings: ContrastFinding[] = [];
265
- for (const s of byPath.values()) {
266
- const ratio = contrastRatio(s.foreground, s.background);
267
- const { requiredAA, level } = classify(ratio, s.fontSize, s.fontWeight);
268
- if (level !== "fail") continue;
269
- findings.push({
270
- path: s.path,
271
- tag: s.tag,
272
- text: s.text,
273
- fontSize: s.fontSize,
274
- fontWeight: s.fontWeight,
275
- bbox: s.bbox,
276
- foreground: { ...s.foreground, hex: toHex(s.foreground) },
277
- background: { ...s.background, hex: toHex(s.background) },
278
- ratio: Number(ratio.toFixed(2)),
279
- requiredAA,
280
- level,
281
- });
282
- }
283
- findings.sort((a, b) => a.ratio - b.ratio); // worst first
284
-
285
- const reportPath = options.reportPath ?? join(outputDir, "report.md");
286
- const md = renderReport({
287
- html: htmlPath,
288
- viewport,
289
- screenshot: screenshotPath,
290
- totalText: byPath.size,
291
- failures: findings,
292
- });
293
- await writeFile(reportPath, md);
294
-
295
- console.log(` ${BOLD}${CYAN}vrt a11y-contrast${RESET}`);
296
- console.log(` ${DIM}html: ${htmlPath}${RESET}`);
297
- console.log(` ${DIM}inspected ${byPath.size} text-bearing element(s)${RESET}`);
298
- const icon = findings.length === 0 ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
299
- console.log(` ${icon} ${findings.length} contrast failure(s)`);
300
- for (const f of findings.slice(0, 5)) {
301
- console.log(` ${DIM}${f.path} — ${f.ratio.toFixed(2)}:1 (need ${f.requiredAA}) — \`${f.foreground.hex}\` on \`${f.background.hex}\` — "${f.text}"${RESET}`);
302
- }
303
- console.log(` ${DIM}report: ${reportPath}${RESET}`);
304
-
305
- return {
306
- html: htmlPath,
307
- viewport,
308
- screenshot: screenshotPath,
309
- totalText: byPath.size,
310
- failures: findings,
311
- reportPath,
312
- };
313
- }
314
-
315
- function renderReport(r: Omit<A11yContrastReport, "reportPath">): string {
316
- const lines: string[] = [];
317
- lines.push("# A11y contrast report");
318
- lines.push("");
319
- lines.push(`HTML: \`${r.html}\``);
320
- lines.push("");
321
- lines.push(`Inspected **${r.totalText}** unique text-bearing elements. ` +
322
- `Screenshot: \`${r.screenshot}\`.`);
323
- lines.push("");
324
- if (r.failures.length === 0) {
325
- lines.push("## All text passes WCAG AA contrast");
326
- lines.push("");
327
- lines.push("Every visible text element has a contrast ratio ≥ 4.5:1 (or ≥ 3:1 for " +
328
- "large text, defined as ≥ 18px regular or ≥ 14px bold).");
329
- } else {
330
- lines.push(`## ${r.failures.length} contrast failure(s)`);
331
- lines.push("");
332
- lines.push("WCAG 2.1 AA requires ≥ 4.5:1 contrast for normal text and ≥ 3:1 for " +
333
- "large text (≥ 18px regular, or ≥ 14px bold). Ratios below these thresholds " +
334
- "make text hard to read for users with low vision.");
335
- lines.push("");
336
- lines.push("| Element | Text (truncated) | Foreground | Background | Ratio | Need |");
337
- lines.push("|---|---|---|---|---|---|");
338
- for (const f of r.failures.slice(0, 20)) {
339
- const fgSwatch = `\`${f.foreground.hex}\``;
340
- const bgSwatch = `\`${f.background.hex}\``;
341
- lines.push(`| \`${f.path}\` (${f.fontSize.toFixed(0)}px${f.fontWeight >= 600 ? " b" : ""}) | \`${f.text}\` | ${fgSwatch} | ${bgSwatch} | **${f.ratio}:1** | ${f.requiredAA}:1 |`);
342
- }
343
- if (r.failures.length > 20) {
344
- lines.push(`| _…${r.failures.length - 20} more_ | | | | | |`);
345
- }
346
- }
347
- lines.push("");
348
- lines.push("## Suggested next step");
349
- lines.push("");
350
- if (r.failures.length === 0) {
351
- lines.push("Page is WCAG AA contrast-clean. Consider running with `--strict` to also " +
352
- "check AAA (7:1 normal, 4.5:1 large) when supporting low-vision users.");
353
- } else {
354
- lines.push("For each failing row:");
355
- lines.push("1. Increase contrast by darkening the foreground or lightening the background " +
356
- "until the ratio crosses 4.5:1 (or 3:1 for large text).");
357
- lines.push("2. Use a contrast-ratio calculator to find specific hex values — every step " +
358
- "toward black/white on a light/dark bg adds ratio.");
359
- lines.push("3. Common fix: muted-gray-on-white text (e.g. `#9ca3af` on `#ffffff` = 2.85:1) " +
360
- "→ try `#6b7280` (4.69:1) or darker.");
361
- lines.push("4. Re-run `vrt a11y-contrast`. Failures should clear.");
362
- }
363
- lines.push("");
364
- return lines.join("\n");
365
- }
366
-
367
- async function main(argv = process.argv.slice(2)) {
368
- if (argv[0] === "--help" || argv[0] === "-h") argv = [];
369
- const { positional, outputDir, report } = parseArgs(argv);
370
- if (positional.length === 0) {
371
- console.log("Usage: vrt a11y-contrast <html> [--output-dir dir]");
372
- console.log("Options:");
373
- console.log(" --output-dir <dir> Default: ./test-results/a11y-contrast");
374
- console.log(" --report <path> Markdown report path");
375
- process.exit(1);
376
- }
377
- await runA11yContrast({
378
- htmlPath: positional[0]!,
379
- outputDir: outputDir || join(process.cwd(), "test-results", "a11y-contrast"),
380
- reportPath: report || undefined,
381
- });
382
- }
383
-
384
- const isCliEntry = process.env.__VRT_DISPATCHER_LEAF__ === "a11y-contrast" || (process.argv[1] ? resolve(process.argv[1]) === fileURLToPath(import.meta.url) : false);
385
- if (isCliEntry) {
386
- main().catch(handleCliError);
387
- }