@mizchi/vlmkit-core 0.9.0 → 0.11.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.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/a11y-semantic.d.mts +1 -6
  3. package/dist/a11y-semantic.mjs +1 -6
  4. package/dist/apng.d.mts +42 -0
  5. package/dist/apng.mjs +199 -0
  6. package/dist/arg-reader.d.mts +3 -1
  7. package/dist/arg-reader.mjs +8 -1
  8. package/dist/auth-state.d.mts +14 -3
  9. package/dist/auth-state.mjs +30 -6
  10. package/dist/bitmap-font.d.mts +48 -0
  11. package/dist/bitmap-font.mjs +945 -0
  12. package/dist/browser-launch.d.mts +65 -0
  13. package/dist/browser-launch.mjs +194 -0
  14. package/dist/cli-args.d.mts +1 -6
  15. package/dist/cli-args.mjs +1 -6
  16. package/dist/cli-error.d.mts +79 -1
  17. package/dist/cli-error.mjs +188 -20
  18. package/dist/dom-equivalence.d.mts +2 -7
  19. package/dist/dom-equivalence.mjs +1 -6
  20. package/dist/element-compare.mjs +8 -11
  21. package/dist/filmstrip.d.mts +121 -0
  22. package/dist/filmstrip.mjs +181 -0
  23. package/dist/gate-config.d.mts +107 -22
  24. package/dist/gate-config.mjs +138 -9
  25. package/dist/heatmap.d.mts +48 -4
  26. package/dist/heatmap.mjs +157 -12
  27. package/dist/index.d.mts +8 -6
  28. package/dist/index.mjs +6 -4
  29. package/dist/mask.d.mts +66 -2
  30. package/dist/mask.mjs +91 -4
  31. package/dist/page-load.d.mts +83 -0
  32. package/dist/page-load.mjs +116 -0
  33. package/dist/page-open.d.mts +123 -2
  34. package/dist/page-open.mjs +176 -6
  35. package/dist/plugin/args.d.mts +86 -0
  36. package/dist/plugin/args.mjs +162 -0
  37. package/dist/plugin/browser.d.mts +6 -0
  38. package/dist/plugin/browser.mjs +6 -0
  39. package/dist/plugin/cli-entry.d.mts +11 -0
  40. package/dist/plugin/cli-entry.mjs +69 -0
  41. package/dist/plugin/contract.d.mts +270 -0
  42. package/dist/plugin/contract.mjs +51 -0
  43. package/dist/plugin/index.d.mts +82 -0
  44. package/dist/plugin/index.mjs +81 -0
  45. package/dist/plugin/load.d.mts +36 -0
  46. package/dist/plugin/load.mjs +98 -0
  47. package/dist/plugin/registry.d.mts +60 -0
  48. package/dist/plugin/registry.mjs +160 -0
  49. package/dist/plugin/rule-tier.d.mts +65 -0
  50. package/dist/plugin/rule-tier.mjs +77 -0
  51. package/dist/plugin/rules.d.mts +112 -0
  52. package/dist/plugin/rules.mjs +188 -0
  53. package/dist/plugin/runner.d.mts +198 -0
  54. package/dist/plugin/runner.mjs +440 -0
  55. package/dist/png-utils.d.mts +31 -1
  56. package/dist/png-utils.mjs +24 -1
  57. package/dist/project-config.d.mts +12 -0
  58. package/dist/project-config.mjs +28 -0
  59. package/dist/rect-overlap.d.mts +41 -0
  60. package/dist/rect-overlap.mjs +28 -0
  61. package/dist/run-ledger.d.mts +56 -2
  62. package/dist/run-ledger.mjs +102 -11
  63. package/dist/types.d.mts +60 -1
  64. package/dist/version.d.mts +20 -0
  65. package/dist/version.mjs +20 -0
  66. package/dist/webp.d.mts +31 -0
  67. package/dist/webp.mjs +105 -0
  68. package/package.json +19 -3
  69. package/dist/legacy-names.d.mts +0 -48
  70. package/dist/legacy-names.mjs +0 -134
@@ -0,0 +1,65 @@
1
+ import { Browser, BrowserType, LaunchOptions } from "playwright";
2
+
3
+ //#region src/browser-launch.d.ts
4
+ type BrowserEngine = "chromium" | "firefox" | "webkit";
5
+ /**
6
+ * Engine name → Playwright browser type.
7
+ *
8
+ * Only `stress/cross-browser.ts` needs more than Chromium (it had its own
9
+ * `ENGINE_BY_NAME` table); the other 64 sites are Chromium-only, which is why
10
+ * `engine` defaults to `"chromium"` rather than being required.
11
+ */
12
+ declare const BROWSER_ENGINES: Record<BrowserEngine, BrowserType>;
13
+ declare const ALL_BROWSER_ENGINES: readonly BrowserEngine[];
14
+ /**
15
+ * A launch that failed for a reason we can explain.
16
+ *
17
+ * `message` is the *finished* operator-facing text, "error: " prefix and all —
18
+ * `handleCliError` writes it verbatim so the CLI output is byte-identical to
19
+ * what it printed when the same diagnosis lived only in the error handler.
20
+ * `cause` keeps the original Playwright error for anyone who wants the stack.
21
+ */
22
+ declare class BrowserLaunchError extends Error {
23
+ readonly name = "BrowserLaunchError";
24
+ constructor(message: string, options?: {
25
+ cause?: unknown;
26
+ });
27
+ }
28
+ interface LaunchBrowserOptions {
29
+ /** Defaults to `"chromium"`. */
30
+ engine?: BrowserEngine;
31
+ /**
32
+ * Passed to `browserType.launch()` verbatim. The 4 sites that pass `args`
33
+ * (font-hinting determinism, headless GPU) depend on this being untouched —
34
+ * dropping an arg silently changes what gets rendered.
35
+ */
36
+ launch?: LaunchOptions;
37
+ /**
38
+ * Extra diagnosis tried *before* the built-in missing-browser one, for the
39
+ * failure modes a single package cannot know about. The css-challenge and
40
+ * migration entry points pass the Codex/macOS sandbox detector that lives in
41
+ * `@mizchi/vlmkit-capture` — core cannot import it (capture depends on core),
42
+ * so it arrives as a hook instead of a second copy.
43
+ *
44
+ * Return the finished message, or `null` to decline.
45
+ */
46
+ diagnose?: (error: unknown) => string | null;
47
+ }
48
+ /**
49
+ * Launch a browser and hand it to the caller, who owns closing it.
50
+ *
51
+ * Prefer `withBrowser` — this exists for the handful of sites that cannot have
52
+ * a scope (a factory that returns a Browser, a browser owned by a session).
53
+ */
54
+ declare function launchBrowser(options?: LaunchBrowserOptions): Promise<Browser>;
55
+ /**
56
+ * Launch a browser, run `fn`, and close the browser whether `fn` throws or not.
57
+ *
58
+ * The `finally` is deliberately not `.catch(() => {})`-guarded: the 51 sites
59
+ * this replaces all wrote `finally { await browser.close(); }`, so a close
60
+ * failure masking a body failure is pre-existing behaviour, not something this
61
+ * refactor gets to change.
62
+ */
63
+ declare function withBrowser<T>(fn: (browser: Browser) => Promise<T>, options?: LaunchBrowserOptions): Promise<T>;
64
+ //#endregion
65
+ export { ALL_BROWSER_ENGINES, BROWSER_ENGINES, BrowserEngine, BrowserLaunchError, LaunchBrowserOptions, launchBrowser, withBrowser };
@@ -0,0 +1,194 @@
1
+ import { formatMissingPlaywrightBrowserError } from "./cli-error.mjs";
2
+ import { chromium, firefox, webkit } from "playwright";
3
+ //#region src/browser-launch.ts
4
+ /**
5
+ * The one place a browser is launched.
6
+ *
7
+ * Measured before this module existed (2026-08-10, repo-wide grep for
8
+ * `.launch(`): **65 call sites, no shared helper.** Grouped by what they pass
9
+ * and what they do around it:
10
+ *
11
+ * 60 bare `launch()` — no options at all
12
+ * 4 `launch({ args })` — font-hinting / GPU flags (probes + design-runs)
13
+ * 1 `launch({ headless })`
14
+ *
15
+ * 51 close in a `finally`
16
+ * 9 close on the straight line after the body (leaks on any throw)
17
+ * 4 never close in that scope (browser handed to a caller)
18
+ * 1 `return chromium.launch()` (the `CaptureBackend` factory)
19
+ *
20
+ * Three separate changes had to work around the absence of a choke point:
21
+ *
22
+ * 1. Missing-browser diagnosis got bolted onto `handleCliError` instead of
23
+ * onto the launch, so only the CLI ever gets it — a library caller of
24
+ * `runIntegrityCheck` sees a raw Playwright stack.
25
+ * 2. `--timeout` / `--wait-until` / `--har` were threaded through 20 gates and
26
+ * got a shared *navigation* helper (`page-open.ts`); the launch did not.
27
+ * 3. Every site repeats its own `try { … } finally { await browser.close() }`,
28
+ * and the 9 that forgot the `finally` leak a Chromium process whenever the
29
+ * measurement throws.
30
+ *
31
+ * Two entry points, because the sites genuinely come in two shapes:
32
+ *
33
+ * - `withBrowser(fn)` for the 51 scoped sites — close is guaranteed, and a
34
+ * thrown callback can no longer leak.
35
+ * - `launchBrowser()` for the 5 sites that hand the browser to someone else
36
+ * (`CaptureBackend.launch`, `createBrowser()` in css-challenge-core, the
37
+ * nullable `fileSources ? null : launch()` in diff-pr). They get the
38
+ * diagnosis; they keep owning the close, because there is no scope to close
39
+ * at.
40
+ *
41
+ * Deliberately NOT in the `@mizchi/vlmkit-core` barrel: this module imports
42
+ * Playwright at module load, same as `element-compare.ts` and `mask.ts`. Deep
43
+ * import it (`@mizchi/vlmkit-core/browser-launch.ts`).
44
+ */
45
+ /**
46
+ * Engine name → Playwright browser type.
47
+ *
48
+ * Only `stress/cross-browser.ts` needs more than Chromium (it had its own
49
+ * `ENGINE_BY_NAME` table); the other 64 sites are Chromium-only, which is why
50
+ * `engine` defaults to `"chromium"` rather than being required.
51
+ */
52
+ const BROWSER_ENGINES = {
53
+ chromium,
54
+ firefox,
55
+ webkit
56
+ };
57
+ const ALL_BROWSER_ENGINES = [
58
+ "chromium",
59
+ "firefox",
60
+ "webkit"
61
+ ];
62
+ /**
63
+ * A launch that failed for a reason we can explain.
64
+ *
65
+ * `message` is the *finished* operator-facing text, "error: " prefix and all —
66
+ * `handleCliError` writes it verbatim so the CLI output is byte-identical to
67
+ * what it printed when the same diagnosis lived only in the error handler.
68
+ * `cause` keeps the original Playwright error for anyone who wants the stack.
69
+ */
70
+ var BrowserLaunchError = class extends Error {
71
+ name = "BrowserLaunchError";
72
+ constructor(message, options) {
73
+ super(message, options);
74
+ }
75
+ };
76
+ /**
77
+ * Turn a launch failure into something an operator can act on, or leave it
78
+ * exactly as it was.
79
+ *
80
+ * Rethrowing the original untouched when nothing recognizes it is the point:
81
+ * `handleCliError` still has branches for navigation failures, timeouts and the
82
+ * raw missing-browser shape, and wrapping every error would have routed them
83
+ * all into the generic `console.error(e)` fallthrough.
84
+ */
85
+ function diagnoseLaunchFailure(error, options) {
86
+ const extra = options.diagnose?.(error);
87
+ if (extra) return new BrowserLaunchError(extra, { cause: error });
88
+ const missing = formatMissingPlaywrightBrowserError(error);
89
+ if (missing) return new BrowserLaunchError(missing, { cause: error });
90
+ return error;
91
+ }
92
+ /**
93
+ * Launch a browser and hand it to the caller, who owns closing it.
94
+ *
95
+ * Prefer `withBrowser` — this exists for the handful of sites that cannot have
96
+ * a scope (a factory that returns a Browser, a browser owned by a session).
97
+ */
98
+ async function launchBrowser(options = {}) {
99
+ const engine = BROWSER_ENGINES[options.engine ?? "chromium"];
100
+ try {
101
+ return instrumentNavigation(await engine.launch(options.launch));
102
+ } catch (error) {
103
+ throw diagnoseLaunchFailure(error, options);
104
+ }
105
+ }
106
+ /** How many still-pending requests to name in a timeout. Enough to see a pattern, not a log dump. */
107
+ const NAMED_PENDING_REQUESTS = 3;
108
+ /**
109
+ * Make every page this browser opens explain its own navigation timeouts.
110
+ *
111
+ * Done at the launch rather than at the navigation because there are **42
112
+ * `.goto(` call sites across 20 files**, three of which hand-roll the same
113
+ * `{ waitUntil: options.waitUntil ?? "networkidle", timeout: options.timeout ?? 30000 }`
114
+ * — so a fix applied to `navigatePage` reaches one of them and looks finished.
115
+ * Wrapping `newPage` here is the only edit that covers all 42.
116
+ *
117
+ * The whole failure used to be one line — `error: page load timed out (Timeout
118
+ * 30000ms exceeded)` — and two dogfood agents working on separate tasks
119
+ * independently called it the worst thing they hit:
120
+ *
121
+ * "It doesn't say the default wait state is `networkidle`, doesn't say
122
+ * `--wait-until` exists, doesn't say a request is still open, doesn't name it.
123
+ * The tool *knows* the milestone it was waiting on and that `/api/live` is in
124
+ * flight."
125
+ *
126
+ * "Dead end as guidance, useful as evidence. Reproduced the reported symptom;
127
+ * told me nothing about how to proceed."
128
+ *
129
+ * It is #112's item 1 restated: "the timeout error reads like the tool can't
130
+ * handle the page rather than like a hint to change approach". Everything needed
131
+ * is present at the moment of failure; it just was not said.
132
+ */
133
+ function instrumentNavigation(browser) {
134
+ if (typeof browser?.newPage !== "function") return browser;
135
+ const originalNewPage = browser.newPage.bind(browser);
136
+ browser.newPage = async (...args) => {
137
+ const page = await originalNewPage(...args);
138
+ const inflight = /* @__PURE__ */ new Map();
139
+ page.on("request", (r) => inflight.set(r.url(), Date.now()));
140
+ page.on("requestfinished", (r) => inflight.delete(r.url()));
141
+ page.on("requestfailed", (r) => inflight.delete(r.url()));
142
+ const originalGoto = page.goto.bind(page);
143
+ page.goto = async (url, gotoOptions) => {
144
+ try {
145
+ return await originalGoto(url, gotoOptions);
146
+ } catch (error) {
147
+ throw explainNavigationTimeout(error, gotoOptions, inflight);
148
+ }
149
+ };
150
+ return page;
151
+ };
152
+ return browser;
153
+ }
154
+ /**
155
+ * Restate a navigation timeout as the three things the caller needs: which
156
+ * milestone was waited on, what was still open, and which flag ends the wait.
157
+ *
158
+ * Any other error passes through untouched — `cli-error.ts` already has branches
159
+ * for a refused connection, an unresolvable host and a blocked port, and this
160
+ * must not shadow them.
161
+ */
162
+ function explainNavigationTimeout(error, gotoOptions, inflight) {
163
+ const message = error instanceof Error ? error.message : String(error);
164
+ if (!/Timeout \d+ms exceeded/i.test(message)) return error;
165
+ const waitUntil = gotoOptions?.waitUntil ?? "load";
166
+ const timeout = gotoOptions?.timeout ?? Number(message.match(/Timeout (\d+)ms/i)?.[1] ?? 3e4);
167
+ const now = Date.now();
168
+ const pending = [...inflight.entries()].sort((a, b) => a[1] - b[1]).map(([requestUrl, at]) => `${requestUrl} (open ${((now - at) / 1e3).toFixed(1)}s)`);
169
+ const lines = [`page load timed out after ${timeout}ms waiting for \`${waitUntil}\``];
170
+ if (pending.length > 0) lines.push(` ${pending.length} request(s) still open:`, ...pending.slice(0, NAMED_PENDING_REQUESTS).map((p) => ` ${p}`), ...pending.length > NAMED_PENDING_REQUESTS ? [` and ${pending.length - NAMED_PENDING_REQUESTS} more`] : []);
171
+ if (waitUntil === "networkidle") lines.push(" The page may have rendered long before this — `networkidle` needs every connection to close,", " which a stream or a poll never does. Try `--wait-until load` (or `domcontentloaded`),", " or pin the network with `--har <file>`. Raising `--timeout` will not help an endpoint that never closes.");
172
+ else lines.push(" Raise `--timeout <ms>`, or relax `--wait-until` further.");
173
+ const explained = new Error(lines.join("\n"));
174
+ explained.cause = error;
175
+ return explained;
176
+ }
177
+ /**
178
+ * Launch a browser, run `fn`, and close the browser whether `fn` throws or not.
179
+ *
180
+ * The `finally` is deliberately not `.catch(() => {})`-guarded: the 51 sites
181
+ * this replaces all wrote `finally { await browser.close(); }`, so a close
182
+ * failure masking a body failure is pre-existing behaviour, not something this
183
+ * refactor gets to change.
184
+ */
185
+ async function withBrowser(fn, options = {}) {
186
+ const browser = await launchBrowser(options);
187
+ try {
188
+ return await fn(browser);
189
+ } finally {
190
+ await browser.close();
191
+ }
192
+ }
193
+ //#endregion
194
+ export { ALL_BROWSER_ENGINES, BROWSER_ENGINES, BrowserLaunchError, launchBrowser, withBrowser };
@@ -26,10 +26,5 @@ declare function getArgValues(name: string): string[];
26
26
  declare function getPositionalArgs(valueFlags?: readonly string[]): string[];
27
27
  /** Raw argv tail, for callers doing their own scanning. */
28
28
  declare function getRawArgs(): string[];
29
- /**
30
- * @deprecated Captured at import time, so it is empty or stale in a leaf loaded
31
- * through the dispatcher. Use `getRawArgs()`.
32
- */
33
- declare const args: string[];
34
29
  //#endregion
35
- export { args, getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
30
+ export { getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
package/dist/cli-args.mjs CHANGED
@@ -54,10 +54,5 @@ function getPositionalArgs(valueFlags = []) {
54
54
  function getRawArgs() {
55
55
  return argv();
56
56
  }
57
- /**
58
- * @deprecated Captured at import time, so it is empty or stale in a leaf loaded
59
- * through the dispatcher. Use `getRawArgs()`.
60
- */
61
- const args = argv();
62
57
  //#endregion
63
- export { args, getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
58
+ export { getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
@@ -7,6 +7,84 @@
7
7
  declare class UsageError extends Error {
8
8
  readonly name = "UsageError";
9
9
  }
10
+ /**
11
+ * The `playwright` peer range. Duplicated from this package's own
12
+ * `peerDependencies` because the shipped bundle has no reliable path back to
13
+ * its manifest (tsdown flattens `dist/`, and the root CLI bundle inlines this
14
+ * module into a hashed chunk). `tests/playwright-peer-contract.test.mjs` reads
15
+ * the manifest and fails if the two drift, so the duplication cannot rot
16
+ * silently.
17
+ */
18
+ declare const PLAYWRIGHT_PEER_RANGE = ">=1.61 <2";
19
+ /** Playwright install target: which `playwright` *this* process resolved. */
20
+ interface PlaywrightInstallTarget {
21
+ version: string;
22
+ /** Directory of the resolved `playwright` package — the identity the reporter of #112 could not see. */
23
+ packageDir: string;
24
+ cliPath: string;
25
+ nodePath: string;
26
+ }
27
+ /**
28
+ * Resolve the `playwright` that vlmkit itself imports, not the one a package
29
+ * manager would pick for `pnpm exec`.
30
+ *
31
+ * Issue #112 (item 2): with two Playwright versions in the tree, the launch
32
+ * failure told the user to run `pnpm exec playwright install`, which resolves
33
+ * from the *project* root and downloads that Playwright's browser build. In the
34
+ * report that was build 1228 while vlmkit's own Playwright wanted 1234, so the
35
+ * advice never fixed anything. `createRequire(import.meta.url)` resolves from
36
+ * this module's location, i.e. from inside vlmkit's own package — the same
37
+ * lookup the `import { chromium } from "playwright"` at the 51 launch sites
38
+ * performs — so the command we print targets the installation that failed.
39
+ */
40
+ declare function resolvePlaywrightInstallTarget(): PlaywrightInstallTarget | null;
41
+ /**
42
+ * Which engine to reinstall, read off the executable path Playwright printed.
43
+ *
44
+ * Hardcoding `chromium` was wrong for `stress cross-browser`, which launches
45
+ * firefox and webkit too. Playwright names the download directory after the
46
+ * engine (`firefox-1490/`, `webkit-2247/`, `chromium_headless_shell-1228/`), so
47
+ * the missing path is itself the answer. Both chromium flavours map to
48
+ * `chromium`: `playwright install chromium` fetches the headless shell as well
49
+ * (verified against the 1.61.1 CLI, which lists both under that one name).
50
+ */
51
+ declare function playwrightEngineFromLaunchError(message: string): "chromium" | "firefox" | "webkit";
52
+ /** `node <resolved playwright>/cli.js install <engine>` — quoted for a shell. */
53
+ declare function playwrightInstallCommand(target: PlaywrightInstallTarget, engine?: "chromium" | "firefox" | "webkit"): string;
54
+ declare function formatMissingPlaywrightBrowserError(error: unknown, target?: PlaywrightInstallTarget | null): string | null;
55
+ /**
56
+ * `playwright` absent entirely, rather than present-but-browserless.
57
+ *
58
+ * It is a **required** peer, deliberately — the argument and its measurement
59
+ * live in `tests/playwright-peer-contract.test.mjs`, because a JSON manifest
60
+ * cannot hold a comment. Short version: the gate registry statically imports
61
+ * `perf.gate`, which statically imports `playwright`, so even the pixel-only
62
+ * commands fault at module load without it. Measured 2026-08-10: in a tree with
63
+ * the package removed, `vlmkit diff png --help` dies with ERR_MODULE_NOT_FOUND
64
+ * before printing usage. That raw stack is what this turns into one sentence.
65
+ */
66
+ declare function formatMissingPlaywrightModuleError(error: unknown): string | null;
67
+ /**
68
+ * Best-effort sanity check used by tests: does the resolved playwright actually
69
+ * have a `cli.js` to invoke? Kept exported so the happy-path test can assert the
70
+ * command we print is runnable rather than merely well-formed.
71
+ */
72
+ declare function resolvedPlaywrightHasCli(): boolean;
73
+ /**
74
+ * The one-line diagnosis for an error, or `null` when there isn't one.
75
+ *
76
+ * Split out of `handleCliError` so the branches are testable. They were not:
77
+ * the only entry point ended in `process.exit`, so covering a branch meant
78
+ * spawning a child process, and in practice nothing covered any of them. That
79
+ * is how the `ERR_FILE_NOT_FOUND` gap below reached a release — the ENOENT
80
+ * branch it duplicates has printed the right line since 2026-05-15, and no test
81
+ * noticed when ten gates stopped reaching it.
82
+ *
83
+ * `null` rather than a generic string on purpose: an unrecognized error should
84
+ * reach the developer whole, stack and all. A prettifier that invents a summary
85
+ * for everything is worse than one that admits it has nothing to add.
86
+ */
87
+ declare function formatCliError(e: unknown): string | null;
10
88
  declare function handleCliError(e: unknown): never;
11
89
  //#endregion
12
- export { UsageError, handleCliError };
90
+ export { PLAYWRIGHT_PEER_RANGE, PlaywrightInstallTarget, UsageError, formatCliError, formatMissingPlaywrightBrowserError, formatMissingPlaywrightModuleError, handleCliError, playwrightEngineFromLaunchError, playwrightInstallCommand, resolvePlaywrightInstallTarget, resolvedPlaywrightHasCli };
@@ -1,4 +1,7 @@
1
- import { statSync } from "node:fs";
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  //#region src/cli-error.ts
3
6
  /**
4
7
  * Shared CLI error-prettifier. Recognizes common error shapes that
@@ -8,6 +11,12 @@ import { statSync } from "node:fs";
8
11
  *
9
12
  * Use:
10
13
  * main().catch(handleCliError);
14
+ *
15
+ * Every CLI entry must go through it, *including* `scripts/vlmkit-bundled.mjs`
16
+ * — that is the one `tsdown.config.ts` builds into the published `bin`. It used
17
+ * to `console.error(error)` instead, which made everything below dead code in
18
+ * the shipped CLI while it kept working in the workspace (issue #112, item 2).
19
+ * `tests/playwright-peer-contract.test.mjs` guards that.
11
20
  */
12
21
  /**
13
22
  * A bad flag or missing argument — the caller's typo, not a defect. Thrown by
@@ -17,42 +26,201 @@ import { statSync } from "node:fs";
17
26
  var UsageError = class extends Error {
18
27
  name = "UsageError";
19
28
  };
20
- function handleCliError(e) {
29
+ /**
30
+ * The `playwright` peer range. Duplicated from this package's own
31
+ * `peerDependencies` because the shipped bundle has no reliable path back to
32
+ * its manifest (tsdown flattens `dist/`, and the root CLI bundle inlines this
33
+ * module into a hashed chunk). `tests/playwright-peer-contract.test.mjs` reads
34
+ * the manifest and fails if the two drift, so the duplication cannot rot
35
+ * silently.
36
+ */
37
+ const PLAYWRIGHT_PEER_RANGE = ">=1.61 <2";
38
+ function shellArg(value) {
39
+ return /^[A-Za-z0-9_./:@+-]+$/.test(value) ? value : JSON.stringify(value);
40
+ }
41
+ /**
42
+ * Resolve the `playwright` that vlmkit itself imports, not the one a package
43
+ * manager would pick for `pnpm exec`.
44
+ *
45
+ * Issue #112 (item 2): with two Playwright versions in the tree, the launch
46
+ * failure told the user to run `pnpm exec playwright install`, which resolves
47
+ * from the *project* root and downloads that Playwright's browser build. In the
48
+ * report that was build 1228 while vlmkit's own Playwright wanted 1234, so the
49
+ * advice never fixed anything. `createRequire(import.meta.url)` resolves from
50
+ * this module's location, i.e. from inside vlmkit's own package — the same
51
+ * lookup the `import { chromium } from "playwright"` at the 51 launch sites
52
+ * performs — so the command we print targets the installation that failed.
53
+ */
54
+ function resolvePlaywrightInstallTarget() {
55
+ try {
56
+ const manifestPath = createRequire(import.meta.url).resolve("playwright/package.json");
57
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
58
+ if (!manifest.version) return null;
59
+ const packageDir = dirname(manifestPath);
60
+ return {
61
+ version: manifest.version,
62
+ packageDir,
63
+ cliPath: join(packageDir, "cli.js"),
64
+ nodePath: process.execPath
65
+ };
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ /**
71
+ * Which engine to reinstall, read off the executable path Playwright printed.
72
+ *
73
+ * Hardcoding `chromium` was wrong for `stress cross-browser`, which launches
74
+ * firefox and webkit too. Playwright names the download directory after the
75
+ * engine (`firefox-1490/`, `webkit-2247/`, `chromium_headless_shell-1228/`), so
76
+ * the missing path is itself the answer. Both chromium flavours map to
77
+ * `chromium`: `playwright install chromium` fetches the headless shell as well
78
+ * (verified against the 1.61.1 CLI, which lists both under that one name).
79
+ */
80
+ function playwrightEngineFromLaunchError(message) {
81
+ if (/\bwebkit[-_]/i.test(message)) return "webkit";
82
+ if (/\bfirefox[-_]/i.test(message)) return "firefox";
83
+ return "chromium";
84
+ }
85
+ /** `node <resolved playwright>/cli.js install <engine>` — quoted for a shell. */
86
+ function playwrightInstallCommand(target, engine = "chromium") {
87
+ return [
88
+ target.nodePath,
89
+ target.cliPath,
90
+ "install",
91
+ engine
92
+ ].map(shellArg).join(" ");
93
+ }
94
+ function missingExecutablePath(message) {
95
+ return message.match(/Executable doesn't exist at\s+(\S+)/i)?.[1] ?? null;
96
+ }
97
+ function formatMissingPlaywrightBrowserError(error, target = resolvePlaywrightInstallTarget()) {
98
+ const message = String(error?.message ?? error);
99
+ if (!/browserType\.launch:[\s\S]*Executable doesn't exist at/i.test(message)) return null;
100
+ const engine = playwrightEngineFromLaunchError(message);
101
+ if (!target) return `error: Playwright has no ${engine} browser executable installed, and vlmkit could not resolve its own playwright package to name the install command.`;
102
+ const missing = missingExecutablePath(message);
103
+ return [
104
+ `error: Playwright ${target.version} has no ${engine} browser executable installed.`,
105
+ ...missing ? [` missing: ${missing}`] : [],
106
+ ` resolved: playwright@${target.version} at ${target.packageDir}`,
107
+ ` run: ${playwrightInstallCommand(target, engine)}`,
108
+ ` (\`npx/pnpm exec playwright install\` may resolve a different playwright and download a different build)`
109
+ ].join("\n");
110
+ }
111
+ /**
112
+ * `playwright` absent entirely, rather than present-but-browserless.
113
+ *
114
+ * It is a **required** peer, deliberately — the argument and its measurement
115
+ * live in `tests/playwright-peer-contract.test.mjs`, because a JSON manifest
116
+ * cannot hold a comment. Short version: the gate registry statically imports
117
+ * `perf.gate`, which statically imports `playwright`, so even the pixel-only
118
+ * commands fault at module load without it. Measured 2026-08-10: in a tree with
119
+ * the package removed, `vlmkit diff png --help` dies with ERR_MODULE_NOT_FOUND
120
+ * before printing usage. That raw stack is what this turns into one sentence.
121
+ */
122
+ function formatMissingPlaywrightModuleError(error) {
123
+ const err = error;
124
+ const message = String(err?.message ?? error);
125
+ if (!(err?.code === "ERR_MODULE_NOT_FOUND" || /ERR_MODULE_NOT_FOUND/.test(message) || /Cannot find (?:package|module)/i.test(message))) return null;
126
+ if (!/Cannot find (?:package|module) ['"]playwright['"]/i.test(message)) return null;
127
+ const importer = message.match(/imported from\s+(\S+)/i)?.[1] ?? null;
128
+ return [
129
+ `error: the \`playwright\` package is not installed.`,
130
+ ` vlmkit declares it as a required peer dependency (${PLAYWRIGHT_PEER_RANGE}). Every`,
131
+ ` command loads it, the pixel-only ones included, because the gate`,
132
+ ` registry imports the browser gates eagerly.`,
133
+ ...importer ? [` imported by: ${importer}`] : [],
134
+ ` run: npm install --save-dev playwright (or pnpm add -D / yarn add -D)`,
135
+ ` then install its browsers with that installation's own CLI:`,
136
+ ` node node_modules/playwright/cli.js install chromium`
137
+ ].join("\n");
138
+ }
139
+ /**
140
+ * Best-effort sanity check used by tests: does the resolved playwright actually
141
+ * have a `cli.js` to invoke? Kept exported so the happy-path test can assert the
142
+ * command we print is runnable rather than merely well-formed.
143
+ */
144
+ function resolvedPlaywrightHasCli() {
145
+ const target = resolvePlaywrightInstallTarget();
146
+ return target !== null && existsSync(target.cliPath);
147
+ }
148
+ /**
149
+ * The one-line diagnosis for an error, or `null` when there isn't one.
150
+ *
151
+ * Split out of `handleCliError` so the branches are testable. They were not:
152
+ * the only entry point ended in `process.exit`, so covering a branch meant
153
+ * spawning a child process, and in practice nothing covered any of them. That
154
+ * is how the `ERR_FILE_NOT_FOUND` gap below reached a release — the ENOENT
155
+ * branch it duplicates has printed the right line since 2026-05-15, and no test
156
+ * noticed when ten gates stopped reaching it.
157
+ *
158
+ * `null` rather than a generic string on purpose: an unrecognized error should
159
+ * reach the developer whole, stack and all. A prettifier that invents a summary
160
+ * for everything is worse than one that admits it has nothing to add.
161
+ */
162
+ function formatCliError(e) {
21
163
  const err = e;
22
164
  const msg = String(err?.message ?? e);
23
- if (err?.name === "UsageError") {
24
- process.stderr.write(`error: ${msg}\n`);
25
- process.exit(1);
26
- }
27
- if (err?.code === "ENOENT") {
28
- const path = err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?";
29
- process.stderr.write(`error: file not found: ${path}\n`);
30
- process.exit(1);
31
- }
165
+ if (err?.name === "UsageError") return `error: ${msg}`;
166
+ if (err?.name === "BrowserLaunchError") return msg.startsWith("error: ") ? msg : `error: ${msg}`;
167
+ if (err?.code === "ENOENT") return `error: file not found: ${err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?"}`;
32
168
  if (err?.code === "EISDIR") {
33
169
  const argvDir = findDirectoryArg();
34
170
  const path = err.path ?? msg.match(/EISDIR:[^']*'([^']+)'/)?.[1] ?? argvDir ?? "?";
35
- 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).`;
36
- process.stderr.write(`error: expected an HTML file, got a directory: ${path}\n${hint}\n`);
37
- process.exit(1);
171
+ return `error: expected an HTML file, got a directory: ${path}\n${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).`}`;
38
172
  }
39
- if (/net::ERR_NAME_NOT_RESOLVED/i.test(msg) || /net::ERR_CONNECTION_REFUSED/i.test(msg) || /Cannot navigate to invalid URL/i.test(msg)) {
173
+ const missingBrowser = formatMissingPlaywrightBrowserError(e);
174
+ if (missingBrowser) return missingBrowser;
175
+ const missingModule = formatMissingPlaywrightModuleError(e);
176
+ if (missingModule) return missingModule;
177
+ if (/net::ERR_FILE_NOT_FOUND/i.test(msg)) return `error: file not found: ${navigationTargetPath(msg)}`;
178
+ if (/net::ERR_NAME_NOT_RESOLVED/i.test(msg) || /net::ERR_CONNECTION_REFUSED/i.test(msg) || /net::ERR_UNSAFE_PORT/i.test(msg) || /Cannot navigate to invalid URL/i.test(msg)) {
40
179
  const url = msg.match(/Navigating to ([^,]+)/i)?.[1] ?? msg.match(/(https?:\/\/[^\s"]+)/)?.[1] ?? "the URL";
41
180
  let reason = "failed to load";
42
181
  if (/ERR_NAME_NOT_RESOLVED/i.test(msg)) reason = "host could not be resolved (check the URL)";
43
182
  else if (/ERR_CONNECTION_REFUSED/i.test(msg)) reason = "connection refused (is the server running?)";
183
+ else if (/ERR_UNSAFE_PORT/i.test(msg)) reason = "Chromium refuses to fetch this port (it is on the blocked-port list) — try another port";
44
184
  else if (/invalid URL/i.test(msg)) reason = "not a valid URL";
45
- process.stderr.write(`error: cannot load ${url}: ${reason}\n`);
46
- process.exit(1);
185
+ return `error: cannot load ${url}: ${reason}`;
47
186
  }
48
- if (/Timeout \d+ms exceeded/i.test(msg)) {
49
- process.stderr.write(`error: page load timed out (${msg.match(/Timeout \d+ms exceeded[^.]*/i)?.[0] ?? msg})\n`);
187
+ if (/^page load timed out after \d+ms waiting for/.test(msg)) return `error: ${msg}`;
188
+ if (/^the --har recording holds nothing for /.test(msg)) return `error: ${msg}`;
189
+ if (/Timeout \d+ms exceeded/i.test(msg)) return `error: page load timed out (${msg.match(/Timeout \d+ms exceeded[^.]*/i)?.[0] ?? msg})`;
190
+ return null;
191
+ }
192
+ function handleCliError(e) {
193
+ const diagnosis = formatCliError(e);
194
+ if (diagnosis !== null) {
195
+ process.stderr.write(`${diagnosis}\n`);
50
196
  process.exit(1);
51
197
  }
52
198
  console.error(e);
53
199
  process.exit(1);
54
200
  }
55
201
  /**
202
+ * The path a failed `page.goto` was aiming at, as an ordinary filesystem path.
203
+ *
204
+ * Playwright reports `net::ERR_FILE_NOT_FOUND at file:///abs/nope.html`, and a
205
+ * `file://` URL is the wrong thing to echo back: the caller typed a path, and a
206
+ * percent-encoded URL of it is harder to compare against what they typed. This
207
+ * decodes it so the message matches the ENOENT branch's exactly.
208
+ *
209
+ * Falls back to the raw match, then to scanning argv, because a message shape
210
+ * that changes with a Playwright upgrade should degrade to a worse path rather
211
+ * than to no message at all.
212
+ */
213
+ function navigationTargetPath(msg) {
214
+ const url = msg.match(/(file:\/\/\/[^\s"']+)/)?.[1];
215
+ if (url) try {
216
+ return fileURLToPath(url);
217
+ } catch {
218
+ return url;
219
+ }
220
+ for (const arg of process.argv.slice(2)) if (!arg.startsWith("-") && /\.html?$/i.test(arg)) return arg;
221
+ return "?";
222
+ }
223
+ /**
56
224
  * EISDIR fallback: Node's `fsPromises.readFile` doesn't attach `.path`
57
225
  * to the error, and the message string doesn't include the path
58
226
  * either. Scan argv for the first positional that exists as a
@@ -68,4 +236,4 @@ function findDirectoryArg() {
68
236
  }
69
237
  }
70
238
  //#endregion
71
- export { UsageError, handleCliError };
239
+ export { PLAYWRIGHT_PEER_RANGE, UsageError, formatCliError, formatMissingPlaywrightBrowserError, formatMissingPlaywrightModuleError, handleCliError, playwrightEngineFromLaunchError, playwrightInstallCommand, resolvePlaywrightInstallTarget, resolvedPlaywrightHasCli };
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * Both pure helpers (sequence diff) and a browser-side capture script live
16
16
  * here; migration-compare evaluates the script with `page.evaluate()`
17
- * and feeds the results into `evaluateDomEquivalence`.
17
+ * and feeds the results into `verifyDomEquivalence`.
18
18
  */
19
19
  interface DomFingerprint {
20
20
  headingTexts: string[];
@@ -35,7 +35,6 @@ interface DomEquivalenceResult {
35
35
  /**
36
36
  * Verify structural DOM equivalence between two captured fingerprints.
37
37
  *
38
- * @since 0.5.0 — replaces `evaluateDomEquivalence`.
39
38
  */
40
39
  declare function verifyDomEquivalence(baseline: DomFingerprint, variant: DomFingerprint): DomEquivalenceResult;
41
40
  /**
@@ -43,9 +42,5 @@ declare function verifyDomEquivalence(baseline: DomFingerprint, variant: DomFing
43
42
  * `page.evaluate()`; produces a {@link DomFingerprint}.
44
43
  */
45
44
  declare const DOM_FINGERPRINT_BROWSER_SCRIPT = "(() => {\n const norm = (s) => (s || \"\").replace(/\\s+/g, \" \").trim();\n const headingTexts = Array.from(document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\")).map((el) => norm(el.textContent));\n const buttonTexts = Array.from(document.querySelectorAll(\"button\")).map((el) => norm(el.textContent));\n const inputValues = Array.from(document.querySelectorAll(\"input, textarea, select\")).map((el) => {\n const v = el.value != null ? el.value : el.getAttribute(\"value\") || \"\";\n return norm(v);\n });\n const elementCount = document.querySelectorAll(\"*\").length;\n return { headingTexts, buttonTexts, inputValues, elementCount };\n})()";
46
- /**
47
- * @deprecated since 0.5.0 — use `verifyDomEquivalence` instead. Removed in 1.0.0.
48
- */
49
- declare const evaluateDomEquivalence: typeof verifyDomEquivalence;
50
45
  //#endregion
51
- export { DOM_FINGERPRINT_BROWSER_SCRIPT, DomEquivalenceResult, DomEquivalenceWarning, DomFingerprint, evaluateDomEquivalence, verifyDomEquivalence };
46
+ export { DOM_FINGERPRINT_BROWSER_SCRIPT, DomEquivalenceResult, DomEquivalenceWarning, DomFingerprint, verifyDomEquivalence };
@@ -31,7 +31,6 @@ const ELEMENT_COUNT_DRIFT_THRESHOLD = .05;
31
31
  /**
32
32
  * Verify structural DOM equivalence between two captured fingerprints.
33
33
  *
34
- * @since 0.5.0 — replaces `evaluateDomEquivalence`.
35
34
  */
36
35
  function verifyDomEquivalence(baseline, variant) {
37
36
  const warnings = [];
@@ -83,9 +82,5 @@ const DOM_FINGERPRINT_BROWSER_SCRIPT = `(() => {
83
82
  const elementCount = document.querySelectorAll("*").length;
84
83
  return { headingTexts, buttonTexts, inputValues, elementCount };
85
84
  })()`;
86
- /**
87
- * @deprecated since 0.5.0 — use `verifyDomEquivalence` instead. Removed in 1.0.0.
88
- */
89
- const evaluateDomEquivalence = verifyDomEquivalence;
90
85
  //#endregion
91
- export { DOM_FINGERPRINT_BROWSER_SCRIPT, evaluateDomEquivalence, verifyDomEquivalence };
86
+ export { DOM_FINGERPRINT_BROWSER_SCRIPT, verifyDomEquivalence };