@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.
- package/LICENSE +21 -0
- package/README.md +38 -0
- package/package.json +35 -0
- package/src/a11y-contrast.ts +387 -0
- package/src/a11y-focus-order.ts +397 -0
- package/src/a11y-semantic.ts +384 -0
- package/src/a11y-touch.ts +340 -0
- package/src/cli-args.ts +29 -0
- package/src/cli-error.ts +85 -0
- package/src/computed-style-capture.ts +596 -0
- package/src/computed-style-diff.ts +192 -0
- package/src/diff-regions.ts +70 -0
- package/src/dom-equivalence.ts +158 -0
- package/src/dom-position-styles.ts +457 -0
- package/src/element-compare.ts +339 -0
- package/src/grid-ratio.ts +251 -0
- package/src/heatmap-regions.ts +246 -0
- package/src/heatmap.ts +516 -0
- package/src/image-resize.ts +112 -0
- package/src/index.ts +108 -0
- package/src/mask.ts +41 -0
- package/src/png-diff.ts +165 -0
- package/src/png-utils.ts +56 -0
- package/src/quality.ts +209 -0
- package/src/region-classify.ts +189 -0
- package/src/shift-origin.ts +204 -0
- package/src/terminal-colors.ts +13 -0
- package/src/text-rows.ts +410 -0
- package/src/types.ts +468 -0
- package/src/visual-semantic.ts +185 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* A11y touch-target check.
|
|
4
|
+
*
|
|
5
|
+
* WCAG 2.1 AAA (criterion 2.5.5) requires interactive elements to have
|
|
6
|
+
* a target size of at least 44 × 44 CSS px. WCAG 2.2 AA (criterion
|
|
7
|
+
* 2.5.8) relaxes this to 24 × 24 with sufficient spacing. Small
|
|
8
|
+
* touch targets are unreachable for users with motor impairments
|
|
9
|
+
* and frustrating on touchscreens.
|
|
10
|
+
*
|
|
11
|
+
* Scans visible interactive elements (button, link, input, select,
|
|
12
|
+
* textarea, [role=button], [role=link], elements with tabindex ≥ 0)
|
|
13
|
+
* and reports those whose bounding box falls below the chosen
|
|
14
|
+
* threshold.
|
|
15
|
+
*
|
|
16
|
+
* Usage:
|
|
17
|
+
* vrt a11y-touch <html-or-url>
|
|
18
|
+
* vrt a11y-touch <url> --level AAA # 44x44 (default)
|
|
19
|
+
* vrt a11y-touch <url> --level AA # 24x24
|
|
20
|
+
*/
|
|
21
|
+
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
22
|
+
import { basename, join, resolve } from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
import { chromium, type Page } from "playwright";
|
|
25
|
+
import { handleCliError } from "./cli-error.ts";
|
|
26
|
+
import { DIM, RESET, GREEN, RED, BOLD, CYAN } from "./terminal-colors.ts";
|
|
27
|
+
|
|
28
|
+
export type WcagTouchLevel = "AAA" | "AA";
|
|
29
|
+
|
|
30
|
+
export interface TouchCheckOptions {
|
|
31
|
+
/** HTML file path or http(s) URL. */
|
|
32
|
+
source: string;
|
|
33
|
+
outputDir: string;
|
|
34
|
+
reportPath?: string;
|
|
35
|
+
viewport?: { width: number; height: number };
|
|
36
|
+
/** Required size threshold. AAA → 44px, AA → 24px. Default AAA. */
|
|
37
|
+
level?: WcagTouchLevel;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface TouchTargetFinding {
|
|
41
|
+
path: string;
|
|
42
|
+
tag: string;
|
|
43
|
+
text: string;
|
|
44
|
+
bbox: { x: number; y: number; width: number; height: number };
|
|
45
|
+
/** Minimum of width and height — the limiting dimension. */
|
|
46
|
+
minSide: number;
|
|
47
|
+
required: number;
|
|
48
|
+
/** Same selectors with overlapping or near-adjacent bboxes within 24 px. */
|
|
49
|
+
cluster: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface TouchReport {
|
|
53
|
+
source: string;
|
|
54
|
+
level: WcagTouchLevel;
|
|
55
|
+
viewport: { width: number; height: number };
|
|
56
|
+
screenshot: string;
|
|
57
|
+
inspectedCount: number;
|
|
58
|
+
failures: TouchTargetFinding[];
|
|
59
|
+
reportPath: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const A11Y_TOUCH_SAMPLE_SCRIPT = `
|
|
63
|
+
(function a11yTouch() {
|
|
64
|
+
function shortPath(el) {
|
|
65
|
+
const parts = [];
|
|
66
|
+
let cur = el;
|
|
67
|
+
while (cur && cur !== document.body && parts.length < 5) {
|
|
68
|
+
let p = cur.tagName.toLowerCase();
|
|
69
|
+
if (cur.id) p += "#" + cur.id;
|
|
70
|
+
else if (cur.className && typeof cur.className === "string") {
|
|
71
|
+
const cls = cur.className.trim().split(/\\s+/).slice(0, 2).join(".");
|
|
72
|
+
if (cls) p += "." + cls;
|
|
73
|
+
}
|
|
74
|
+
parts.unshift(p);
|
|
75
|
+
cur = cur.parentElement;
|
|
76
|
+
}
|
|
77
|
+
return parts.join(">");
|
|
78
|
+
}
|
|
79
|
+
const selectors = [
|
|
80
|
+
"button",
|
|
81
|
+
"a[href]",
|
|
82
|
+
"input:not([type='hidden'])",
|
|
83
|
+
"select",
|
|
84
|
+
"textarea",
|
|
85
|
+
"summary",
|
|
86
|
+
"[role='button']",
|
|
87
|
+
"[role='link']",
|
|
88
|
+
"[tabindex]:not([tabindex='-1'])",
|
|
89
|
+
].join(",");
|
|
90
|
+
const out = [];
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
for (const el of document.querySelectorAll(selectors)) {
|
|
93
|
+
if (seen.has(el)) continue;
|
|
94
|
+
seen.add(el);
|
|
95
|
+
const cs = getComputedStyle(el);
|
|
96
|
+
if (cs.visibility === "hidden" || cs.display === "none" || parseFloat(cs.opacity) < 0.5) continue;
|
|
97
|
+
if (el.hasAttribute("disabled") || el.getAttribute("aria-hidden") === "true") continue;
|
|
98
|
+
const r = el.getBoundingClientRect();
|
|
99
|
+
if (r.width === 0 || r.height === 0) continue;
|
|
100
|
+
const text = (el.textContent || el.getAttribute("aria-label") || el.getAttribute("title") || "").trim().slice(0, 60);
|
|
101
|
+
out.push({
|
|
102
|
+
path: shortPath(el),
|
|
103
|
+
tag: el.tagName.toLowerCase(),
|
|
104
|
+
text,
|
|
105
|
+
bbox: { x: r.x, y: r.y, width: r.width, height: r.height },
|
|
106
|
+
});
|
|
107
|
+
if (out.length > 400) break;
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
})()
|
|
111
|
+
`;
|
|
112
|
+
|
|
113
|
+
export interface A11yTouchRawSample {
|
|
114
|
+
path: string;
|
|
115
|
+
tag: string;
|
|
116
|
+
text: string;
|
|
117
|
+
bbox: { x: number; y: number; width: number; height: number };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Build the list of touch-target failures from raw samples. Pure
|
|
122
|
+
* post-process so the `vrt diff-pr` CI gate can reuse it on its
|
|
123
|
+
* own Playwright page without spinning up a new browser.
|
|
124
|
+
*/
|
|
125
|
+
export function analyzeA11yTouchSamples(
|
|
126
|
+
samples: A11yTouchRawSample[],
|
|
127
|
+
level: WcagTouchLevel = "AAA",
|
|
128
|
+
): TouchTargetFinding[] {
|
|
129
|
+
const required = level === "AAA" ? 44 : 24;
|
|
130
|
+
const byPath = new Map<string, A11yTouchRawSample>();
|
|
131
|
+
for (const s of samples) if (!byPath.has(s.path)) byPath.set(s.path, s);
|
|
132
|
+
const findings: TouchTargetFinding[] = [];
|
|
133
|
+
const elements = [...byPath.values()];
|
|
134
|
+
for (let i = 0; i < elements.length; i++) {
|
|
135
|
+
const e = elements[i]!;
|
|
136
|
+
const minSide = Math.min(e.bbox.width, e.bbox.height);
|
|
137
|
+
if (minSide >= required) continue;
|
|
138
|
+
let cluster = false;
|
|
139
|
+
for (let j = 0; j < elements.length; j++) {
|
|
140
|
+
if (i === j) continue;
|
|
141
|
+
const o = elements[j]!;
|
|
142
|
+
const cx1 = e.bbox.x + e.bbox.width / 2, cy1 = e.bbox.y + e.bbox.height / 2;
|
|
143
|
+
const cx2 = o.bbox.x + o.bbox.width / 2, cy2 = o.bbox.y + o.bbox.height / 2;
|
|
144
|
+
const dx = cx2 - cx1, dy = cy2 - cy1;
|
|
145
|
+
if (Math.sqrt(dx * dx + dy * dy) < 24) { cluster = true; break; }
|
|
146
|
+
}
|
|
147
|
+
findings.push({
|
|
148
|
+
path: e.path,
|
|
149
|
+
tag: e.tag,
|
|
150
|
+
text: e.text,
|
|
151
|
+
bbox: e.bbox,
|
|
152
|
+
minSide: Math.round(minSide),
|
|
153
|
+
required,
|
|
154
|
+
cluster,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
findings.sort((a, b) => a.minSide - b.minSide);
|
|
158
|
+
return findings;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function parseArgs(argv: string[]) {
|
|
162
|
+
let outputDir = "";
|
|
163
|
+
let report = "";
|
|
164
|
+
let level: WcagTouchLevel = "AAA";
|
|
165
|
+
const positional: string[] = [];
|
|
166
|
+
for (let i = 0; i < argv.length; i++) {
|
|
167
|
+
const a = argv[i];
|
|
168
|
+
if (a === "--output-dir") outputDir = argv[++i];
|
|
169
|
+
else if (a === "--report") report = argv[++i];
|
|
170
|
+
else if (a === "--level") {
|
|
171
|
+
const v = argv[++i];
|
|
172
|
+
if (v === "AA" || v === "AAA") level = v;
|
|
173
|
+
} else positional.push(a);
|
|
174
|
+
}
|
|
175
|
+
return { positional, outputDir, report, level };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isUrl(s: string): boolean {
|
|
179
|
+
return /^https?:\/\//.test(s);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function runA11yTouch(options: TouchCheckOptions): Promise<TouchReport> {
|
|
183
|
+
const outputDir = resolve(options.outputDir);
|
|
184
|
+
await mkdir(outputDir, { recursive: true });
|
|
185
|
+
const viewport = options.viewport ?? { width: 1280, height: 900 };
|
|
186
|
+
const level = options.level ?? "AAA";
|
|
187
|
+
const required = level === "AAA" ? 44 : 24;
|
|
188
|
+
|
|
189
|
+
const browser = await chromium.launch();
|
|
190
|
+
let samples: A11yTouchRawSample[];
|
|
191
|
+
let screenshotPath: string;
|
|
192
|
+
try {
|
|
193
|
+
const page = await browser.newPage({ viewport });
|
|
194
|
+
if (isUrl(options.source)) {
|
|
195
|
+
await page.goto(options.source, { waitUntil: "networkidle", timeout: 30000 });
|
|
196
|
+
} else {
|
|
197
|
+
const html = await readFile(resolve(options.source), "utf-8");
|
|
198
|
+
await page.setContent(html, { waitUntil: "networkidle" });
|
|
199
|
+
}
|
|
200
|
+
await page.addStyleTag({
|
|
201
|
+
content: `*, *::before, *::after { transition: none !important; animation: none !important; }`,
|
|
202
|
+
});
|
|
203
|
+
samples = await page.evaluate(A11Y_TOUCH_SAMPLE_SCRIPT) as A11yTouchRawSample[];
|
|
204
|
+
screenshotPath = join(outputDir, "page.png");
|
|
205
|
+
await page.screenshot({ path: screenshotPath, fullPage: false });
|
|
206
|
+
await page.close();
|
|
207
|
+
} finally {
|
|
208
|
+
await browser.close();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Dedupe by path.
|
|
212
|
+
const byPath = new Map<string, A11yTouchRawSample>();
|
|
213
|
+
for (const s of samples) if (!byPath.has(s.path)) byPath.set(s.path, s);
|
|
214
|
+
|
|
215
|
+
// Cluster detection: if two below-threshold targets are within
|
|
216
|
+
// 24 px center-to-center, the WCAG 2.5.8 AA "with spacing" leniency
|
|
217
|
+
// is forfeited. (Strict-AAA doesn't have the leniency anyway, but
|
|
218
|
+
// we still surface clusters for context.)
|
|
219
|
+
const findings: TouchTargetFinding[] = [];
|
|
220
|
+
const elements = [...byPath.values()];
|
|
221
|
+
for (let i = 0; i < elements.length; i++) {
|
|
222
|
+
const e = elements[i]!;
|
|
223
|
+
const minSide = Math.min(e.bbox.width, e.bbox.height);
|
|
224
|
+
if (minSide >= required) continue;
|
|
225
|
+
let cluster = false;
|
|
226
|
+
for (let j = 0; j < elements.length; j++) {
|
|
227
|
+
if (i === j) continue;
|
|
228
|
+
const o = elements[j]!;
|
|
229
|
+
const cx1 = e.bbox.x + e.bbox.width / 2, cy1 = e.bbox.y + e.bbox.height / 2;
|
|
230
|
+
const cx2 = o.bbox.x + o.bbox.width / 2, cy2 = o.bbox.y + o.bbox.height / 2;
|
|
231
|
+
const dx = cx2 - cx1, dy = cy2 - cy1;
|
|
232
|
+
if (Math.sqrt(dx * dx + dy * dy) < 24) { cluster = true; break; }
|
|
233
|
+
}
|
|
234
|
+
findings.push({
|
|
235
|
+
path: e.path,
|
|
236
|
+
tag: e.tag,
|
|
237
|
+
text: e.text,
|
|
238
|
+
bbox: e.bbox,
|
|
239
|
+
minSide: Math.round(minSide),
|
|
240
|
+
required,
|
|
241
|
+
cluster,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
findings.sort((a, b) => a.minSide - b.minSide);
|
|
245
|
+
|
|
246
|
+
const reportPath = options.reportPath ?? join(outputDir, "report.md");
|
|
247
|
+
const md = renderReport({
|
|
248
|
+
source: options.source,
|
|
249
|
+
level,
|
|
250
|
+
viewport,
|
|
251
|
+
screenshot: screenshotPath,
|
|
252
|
+
inspectedCount: byPath.size,
|
|
253
|
+
failures: findings,
|
|
254
|
+
});
|
|
255
|
+
await writeFile(reportPath, md);
|
|
256
|
+
|
|
257
|
+
console.log(` ${BOLD}${CYAN}vrt a11y-touch${RESET}`);
|
|
258
|
+
console.log(` ${DIM}source: ${options.source} level: WCAG ${level} (${required}×${required} min)${RESET}`);
|
|
259
|
+
console.log(` ${DIM}inspected ${byPath.size} interactive element(s)${RESET}`);
|
|
260
|
+
const icon = findings.length === 0 ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
|
|
261
|
+
console.log(` ${icon} ${findings.length} undersized target(s)`);
|
|
262
|
+
for (const f of findings.slice(0, 5)) {
|
|
263
|
+
const cl = f.cluster ? " (clustered)" : "";
|
|
264
|
+
console.log(` ${DIM}${f.path} — ${Math.round(f.bbox.width)}×${Math.round(f.bbox.height)}${cl} — "${f.text}"${RESET}`);
|
|
265
|
+
}
|
|
266
|
+
console.log(` ${DIM}report: ${reportPath}${RESET}`);
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
source: options.source, level, viewport, screenshot: screenshotPath,
|
|
270
|
+
inspectedCount: byPath.size, failures: findings, reportPath,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function renderReport(r: Omit<TouchReport, "reportPath">): string {
|
|
275
|
+
const lines: string[] = [];
|
|
276
|
+
lines.push("# A11y touch-target report");
|
|
277
|
+
lines.push("");
|
|
278
|
+
lines.push(`Source: \`${r.source}\``);
|
|
279
|
+
lines.push(`WCAG level: **${r.level}** — requires ${r.level === "AAA" ? "44×44 px" : "24×24 px (with spacing)"} for every interactive element.`);
|
|
280
|
+
lines.push("");
|
|
281
|
+
lines.push(`Inspected **${r.inspectedCount}** interactive element(s). ` +
|
|
282
|
+
`Screenshot: \`${r.screenshot}\``);
|
|
283
|
+
lines.push("");
|
|
284
|
+
if (r.failures.length === 0) {
|
|
285
|
+
lines.push("## All interactive elements meet the size threshold.");
|
|
286
|
+
return lines.join("\n");
|
|
287
|
+
}
|
|
288
|
+
lines.push(`## ${r.failures.length} undersized target(s)`);
|
|
289
|
+
lines.push("");
|
|
290
|
+
lines.push("Targets below the threshold are hard to tap on touchscreens and " +
|
|
291
|
+
"unreachable for users with motor impairments. The `cluster` flag fires " +
|
|
292
|
+
"when another interactive element's center is within 24 px — the WCAG " +
|
|
293
|
+
"AA-with-spacing leniency does not apply.");
|
|
294
|
+
lines.push("");
|
|
295
|
+
lines.push("| Element | Text | Size | Min side | Need | Cluster |");
|
|
296
|
+
lines.push("|---|---|---|---|---|---|");
|
|
297
|
+
for (const f of r.failures.slice(0, 30)) {
|
|
298
|
+
const sz = `${Math.round(f.bbox.width)}×${Math.round(f.bbox.height)}`;
|
|
299
|
+
lines.push(`| \`${f.path}\` | \`${f.text}\` | ${sz} | **${f.minSide}** | ${f.required} | ${f.cluster ? "yes" : "no"} |`);
|
|
300
|
+
}
|
|
301
|
+
if (r.failures.length > 30) lines.push(`| _…${r.failures.length - 30} more_ | | | | | |`);
|
|
302
|
+
lines.push("");
|
|
303
|
+
lines.push("## Suggested next step");
|
|
304
|
+
lines.push("");
|
|
305
|
+
lines.push("1. For each failing row, expand the element's bbox to ≥ " +
|
|
306
|
+
`${r.failures[0]!.required}×${r.failures[0]!.required} px. Common fixes:`);
|
|
307
|
+
lines.push(" - Increase `padding`. A 12px padding on an icon-only button " +
|
|
308
|
+
"grows a 16×16 icon to 40×40 reach-bbox.");
|
|
309
|
+
lines.push(" - Set `min-width` / `min-height` explicitly: " +
|
|
310
|
+
`\`min-width: ${r.failures[0]!.required}px; min-height: ${r.failures[0]!.required}px;\`.`);
|
|
311
|
+
lines.push(" - For inline links, wrap them in a block with hit padding " +
|
|
312
|
+
"and use `display: inline-block`.");
|
|
313
|
+
lines.push("2. Re-run `vrt a11y-touch`. The failure list should empty out.");
|
|
314
|
+
lines.push("");
|
|
315
|
+
return lines.join("\n");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function main(argv = process.argv.slice(2)) {
|
|
319
|
+
if (argv[0] === "--help" || argv[0] === "-h") argv = [];
|
|
320
|
+
const { positional, outputDir, report, level } = parseArgs(argv);
|
|
321
|
+
if (positional.length === 0) {
|
|
322
|
+
console.log("Usage: vrt a11y-touch <html-or-url> [--level AAA|AA] [--output-dir dir]");
|
|
323
|
+
console.log("Options:");
|
|
324
|
+
console.log(" --level AAA|AA WCAG threshold — AAA=44px (default), AA=24px-with-spacing.");
|
|
325
|
+
console.log(" --output-dir <dir> Default: ./test-results/a11y-touch");
|
|
326
|
+
console.log(" --report <path> Markdown report path");
|
|
327
|
+
process.exit(1);
|
|
328
|
+
}
|
|
329
|
+
await runA11yTouch({
|
|
330
|
+
source: positional[0]!,
|
|
331
|
+
outputDir: outputDir || join(process.cwd(), "test-results", "a11y-touch"),
|
|
332
|
+
reportPath: report || undefined,
|
|
333
|
+
level,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const isCliEntry = process.env.__VRT_DISPATCHER_LEAF__ === "a11y-touch" || (process.argv[1] ? resolve(process.argv[1]) === fileURLToPath(import.meta.url) : false);
|
|
338
|
+
if (isCliEntry) {
|
|
339
|
+
main().catch(handleCliError);
|
|
340
|
+
}
|
package/src/cli-args.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Shared CLI argument parsing helpers */
|
|
2
|
+
|
|
3
|
+
const args = process.argv.slice(2);
|
|
4
|
+
|
|
5
|
+
export function getArg(name: string, fallback: string): string;
|
|
6
|
+
export function getArg(name: string): string | undefined;
|
|
7
|
+
export function getArg(name: string, fallback?: string): string | undefined {
|
|
8
|
+
const idx = args.indexOf(`--${name}`);
|
|
9
|
+
return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function hasFlag(name: string): boolean {
|
|
13
|
+
return args.includes(`--${name}`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getArgValues(name: string): string[] {
|
|
17
|
+
const values: string[] = [];
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
if (args[i] === `--${name}` && args[i + 1]) values.push(args[i + 1]);
|
|
20
|
+
}
|
|
21
|
+
return values;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Get positional args (not flags or flag values) */
|
|
25
|
+
export function getPositionalArgs(): string[] {
|
|
26
|
+
return args.filter((a, i) => !a.startsWith("--") && (i === 0 || !args[i - 1]?.startsWith("--")));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export { args };
|
package/src/cli-error.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared CLI error-prettifier. Recognizes common error shapes that
|
|
3
|
+
* make `vrt` look user-hostile (ENOENT stack traces, Playwright
|
|
4
|
+
* navigation errors with absolute source paths) and rewrites them
|
|
5
|
+
* to a one-line message.
|
|
6
|
+
*
|
|
7
|
+
* Use:
|
|
8
|
+
* main().catch(handleCliError);
|
|
9
|
+
*/
|
|
10
|
+
import { statSync } from "node:fs";
|
|
11
|
+
|
|
12
|
+
export function handleCliError(e: unknown): never {
|
|
13
|
+
// Node fs errors carry the offending path on `.path`; that's more
|
|
14
|
+
// reliable than parsing it out of `.message` (which sometimes
|
|
15
|
+
// doesn't include the path at all, e.g. EISDIR from readFile).
|
|
16
|
+
const err = e as { code?: string; message?: string; name?: string; path?: string };
|
|
17
|
+
const msg = String(err?.message ?? e);
|
|
18
|
+
|
|
19
|
+
// ENOENT — missing local file path.
|
|
20
|
+
if (err?.code === "ENOENT") {
|
|
21
|
+
const path = err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?";
|
|
22
|
+
process.stderr.write(`error: file not found: ${path}\n`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
// EISDIR — caller passed a directory where an HTML file (or other
|
|
26
|
+
// single-file artifact) was expected. Surfaced repeatedly in
|
|
27
|
+
// back-to-back cold-start dogfoods (2026-05-15) as the worst raw-
|
|
28
|
+
// stack-trace first impression in the toolkit. Almost every vrt
|
|
29
|
+
// subcommand accepts `<html-or-url>` as its first positional, so
|
|
30
|
+
// catching the directory case here covers all of them at once.
|
|
31
|
+
// Node's fsPromises.readFile drops `err.path`, so we fall back to
|
|
32
|
+
// scanning argv for any positional that exists as a directory.
|
|
33
|
+
if (err?.code === "EISDIR") {
|
|
34
|
+
const argvDir = findDirectoryArg();
|
|
35
|
+
const path = err.path ?? msg.match(/EISDIR:[^']*'([^']+)'/)?.[1] ?? argvDir ?? "?";
|
|
36
|
+
const hint = path === "?"
|
|
37
|
+
? " hint: pass the path to a specific .html file."
|
|
38
|
+
: ` hint: pass the path to a specific .html file inside it (e.g. ${path}/page.html).`;
|
|
39
|
+
process.stderr.write(`error: expected an HTML file, got a directory: ${path}\n${hint}\n`);
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
// Playwright navigation failure (DNS / connection refused / SSL).
|
|
43
|
+
if (
|
|
44
|
+
/net::ERR_NAME_NOT_RESOLVED/i.test(msg)
|
|
45
|
+
|| /net::ERR_CONNECTION_REFUSED/i.test(msg)
|
|
46
|
+
|| /Cannot navigate to invalid URL/i.test(msg)
|
|
47
|
+
) {
|
|
48
|
+
const url = msg.match(/Navigating to ([^,]+)/i)?.[1]
|
|
49
|
+
?? msg.match(/(https?:\/\/[^\s"]+)/)?.[1]
|
|
50
|
+
?? "the URL";
|
|
51
|
+
let reason = "failed to load";
|
|
52
|
+
if (/ERR_NAME_NOT_RESOLVED/i.test(msg)) reason = "host could not be resolved (check the URL)";
|
|
53
|
+
else if (/ERR_CONNECTION_REFUSED/i.test(msg)) reason = "connection refused (is the server running?)";
|
|
54
|
+
else if (/invalid URL/i.test(msg)) reason = "not a valid URL";
|
|
55
|
+
process.stderr.write(`error: cannot load ${url}: ${reason}\n`);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
// Playwright timeout.
|
|
59
|
+
if (/Timeout \d+ms exceeded/i.test(msg)) {
|
|
60
|
+
process.stderr.write(`error: page load timed out (${msg.match(/Timeout \d+ms exceeded[^.]*/i)?.[0] ?? msg})\n`);
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
// Default: full error for the developer.
|
|
64
|
+
console.error(e);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* EISDIR fallback: Node's `fsPromises.readFile` doesn't attach `.path`
|
|
70
|
+
* to the error, and the message string doesn't include the path
|
|
71
|
+
* either. Scan argv for the first positional that exists as a
|
|
72
|
+
* directory — close enough since most vrt subcommands take exactly
|
|
73
|
+
* one path argument and the failure happens during the initial read.
|
|
74
|
+
*/
|
|
75
|
+
function findDirectoryArg(): string | undefined {
|
|
76
|
+
for (const arg of process.argv.slice(2)) {
|
|
77
|
+
if (arg.startsWith("-")) continue;
|
|
78
|
+
try {
|
|
79
|
+
if (statSync(arg).isDirectory()) return arg;
|
|
80
|
+
} catch {
|
|
81
|
+
// arg doesn't exist as a path; keep scanning.
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|