@mizchi/vlmkit-core 0.9.1 → 0.11.1

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 (57) hide show
  1. package/dist/apng.d.mts +42 -0
  2. package/dist/apng.mjs +199 -0
  3. package/dist/auth-state.d.mts +14 -3
  4. package/dist/auth-state.mjs +30 -6
  5. package/dist/bitmap-font.d.mts +48 -0
  6. package/dist/bitmap-font.mjs +945 -0
  7. package/dist/browser-launch.d.mts +65 -0
  8. package/dist/browser-launch.mjs +194 -0
  9. package/dist/cli-error.d.mts +73 -1
  10. package/dist/cli-error.mjs +164 -32
  11. package/dist/element-compare.mjs +8 -11
  12. package/dist/filmstrip.d.mts +121 -0
  13. package/dist/filmstrip.mjs +181 -0
  14. package/dist/gate-config.d.mts +107 -22
  15. package/dist/gate-config.mjs +138 -9
  16. package/dist/heatmap.d.mts +48 -4
  17. package/dist/heatmap.mjs +157 -12
  18. package/dist/index.d.mts +6 -4
  19. package/dist/index.mjs +4 -2
  20. package/dist/mask.d.mts +66 -2
  21. package/dist/mask.mjs +91 -4
  22. package/dist/page-load.d.mts +83 -0
  23. package/dist/page-load.mjs +116 -0
  24. package/dist/page-open.d.mts +123 -2
  25. package/dist/page-open.mjs +176 -6
  26. package/dist/plugin/args.d.mts +86 -0
  27. package/dist/plugin/args.mjs +162 -0
  28. package/dist/plugin/browser.d.mts +6 -0
  29. package/dist/plugin/browser.mjs +6 -0
  30. package/dist/plugin/cli-entry.d.mts +11 -0
  31. package/dist/plugin/cli-entry.mjs +69 -0
  32. package/dist/plugin/contract.d.mts +270 -0
  33. package/dist/plugin/contract.mjs +51 -0
  34. package/dist/plugin/index.d.mts +82 -0
  35. package/dist/plugin/index.mjs +81 -0
  36. package/dist/plugin/load.d.mts +36 -0
  37. package/dist/plugin/load.mjs +98 -0
  38. package/dist/plugin/registry.d.mts +60 -0
  39. package/dist/plugin/registry.mjs +160 -0
  40. package/dist/plugin/rule-tier.d.mts +65 -0
  41. package/dist/plugin/rule-tier.mjs +77 -0
  42. package/dist/plugin/rules.d.mts +112 -0
  43. package/dist/plugin/rules.mjs +188 -0
  44. package/dist/plugin/runner.d.mts +198 -0
  45. package/dist/plugin/runner.mjs +440 -0
  46. package/dist/png-utils.d.mts +31 -1
  47. package/dist/png-utils.mjs +24 -1
  48. package/dist/rect-overlap.d.mts +41 -0
  49. package/dist/rect-overlap.mjs +28 -0
  50. package/dist/run-ledger.d.mts +56 -2
  51. package/dist/run-ledger.mjs +102 -11
  52. package/dist/types.d.mts +60 -1
  53. package/dist/version.d.mts +20 -0
  54. package/dist/version.mjs +20 -0
  55. package/dist/webp.d.mts +31 -0
  56. package/dist/webp.mjs +105 -0
  57. package/package.json +17 -3
@@ -1,5 +1,6 @@
1
1
  import { withAuthState } from "./auth-state.mjs";
2
2
  import { describeRedirect } from "./navigation-redirect.mjs";
3
+ import { readFileSync } from "node:fs";
3
4
  import { resolve } from "node:path";
4
5
  import { pathToFileURL } from "node:url";
5
6
  //#region src/page-open.ts
@@ -20,14 +21,45 @@ import { pathToFileURL } from "node:url";
20
21
  * `check a11y contrast` as **0 failures**, because the gate measured unstyled
21
22
  * markup. Inlining the same CSS in a `<style>` block made the same gate report
22
23
  * the failure correctly. Ten gates read a user's file and pushed it through
23
- * `setContent` with no base URL.
24
+ * `setContent` with no base URL. All ten now navigate; the last two —
25
+ * `check a11y focus` and `check drift component` — went across on 2026-08-10,
26
+ * and they were the worst of the set because both read geometry rather than a
27
+ * style value, so unstyled markup did not degrade the measurement, it inverted
28
+ * it. `fixtures/external-assets/README.md` carries the before/after numbers.
24
29
  *
25
30
  * So: load by navigation whenever the bytes on disk are what we want, and when
26
31
  * a gate must mutate the HTML first (inflate text for i18n, force a theme,
27
32
  * delete a CSS rule), navigate to the source and *then* replace the markup, so
28
33
  * the document keeps a base URL its siblings resolve against.
29
34
  */
30
- const isUrlSource = (source) => /^https?:\/\//.test(source);
35
+ /**
36
+ * Is this source already a URL, or is it a path that has to become one?
37
+ *
38
+ * `file:` belongs here and did not use to. This function said `https?` only, so a
39
+ * `file://` source fell into the path branch and `resolve()` mangled it exactly the way
40
+ * the comment on `resolveSource` warns about for `http`:
41
+ *
42
+ * vlmkit check a11y contrast "file:///repo/fixtures/page.html"
43
+ * error: file not found: /repo/file:/repo/fixtures/page.html
44
+ *
45
+ * Measured — the same fixture passed as a plain path inspected 31 elements and found 2
46
+ * contrast failures. Everything reaching a page through `openSource` / `sourceToUrl`
47
+ * carried it: `check a11y contrast` / `touch` / `focus`, `check theme`, `stress i18n`,
48
+ * `stress media`, `check tokens`, `check consistency`.
49
+ *
50
+ * It is also the clearest case of the duplication pattern in the repo. Eight modules
51
+ * wrote their own `isUrl` — animation-eval, motion-detect, breakpoint-check, copy-check,
52
+ * integrity-check, scroll-behavior, scroll-scan, media-variants — and all eight spell it
53
+ * `/^(https?|file):\/\//`. They are right and the shared helper they were meant to
54
+ * replace was wrong, which is why the commands that hand-rolled the check kept working
55
+ * (`check story --gallery "file://$PWD/index.html"`, the recipe in CLAUDE.md, is fine)
56
+ * while the ones written the documented way did not.
57
+ *
58
+ * Scoped to these two schemes rather than "anything with a scheme" on purpose: `data:`
59
+ * and `about:` are not sources any caller resolves, and a bare Windows drive letter
60
+ * (`C:\page.html`) must stay a path.
61
+ */
62
+ const isUrlSource = (source) => /^(https?|file):\/\//.test(source);
31
63
  /**
32
64
  * Normalize a source for storage and display: an absolute path for a file, the
33
65
  * URL untouched for a URL.
@@ -70,12 +102,148 @@ function sourceToUrl(source) {
70
102
  * network idle anyway, so the 8 `load` and 2 `domcontentloaded` call sites are
71
103
  * equivalent to the 71 `networkidle` ones **provided they settle**. The
72
104
  * difference that mattered was always the settle, never the load state.
105
+ *
106
+ * ## The fourth part: entrance animations
107
+ *
108
+ * Added 2026-08-16, from dogfooding `examples/solitaire/`. Idle + fonts + 250ms is not enough
109
+ * for a page that animates itself in, and the failure has the same shape as the three above —
110
+ * reported as a defect in the page rather than as looking too early:
111
+ *
112
+ * - `check integrity` reported `low-contrast-text … 4.12:1` on a card whose colour is 5.8:1.
113
+ * It had measured the card at `opacity: 0.2` **in mid-flight during a 960ms deal
114
+ * animation**, and the finding arrived with a selector, so a reader goes looking for a
115
+ * colour bug that does not exist. With the animation finished the same gate says CLEAN.
116
+ *
117
+ * So this now also waits for every animation that HAS an end to reach it, via
118
+ * `Animation.finished` over `document.getAnimations()`.
119
+ *
120
+ * Infinite animations are excluded rather than waited on, which is the whole reason this is
121
+ * safe to put in the shared settle: a spinner, a marquee or a pulsing badge never finishes, and
122
+ * awaiting it would hang every gate on every page that has one. `animationCapMs` bounds the
123
+ * wait regardless, because a long finite animation is not worth stalling a run for — a page
124
+ * with a 30-second intro gets measured at the cap and that is the correct trade.
73
125
  */
74
- async function settlePage(page, settleMs = 250) {
126
+ async function settlePage(page, settleMs = 250, animationCapMs = 2e3) {
75
127
  await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {});
76
128
  await page.evaluate(() => document.fonts ? document.fonts.ready.then(() => void 0) : void 0).catch(() => {});
129
+ if (animationCapMs > 0) await waitForAnimations(page, animationCapMs);
77
130
  if (settleMs > 0) await page.waitForTimeout(settleMs);
78
131
  }
132
+ /**
133
+ * Wait for the finite animations to finish, capped.
134
+ *
135
+ * `getAnimations()` covers CSS animations, CSS transitions and Web Animations alike, so this
136
+ * needs no cooperation from the page — no marker attribute, no convention.
137
+ *
138
+ * The cap is enforced in the PAGE with `Promise.race`, not by a Playwright timeout around the
139
+ * evaluate: a rejected `evaluate` would have to be swallowed, and swallowing it would hide a
140
+ * real error in the same `catch` as the timeout.
141
+ */
142
+ async function waitForAnimations(page, capMs) {
143
+ await page.evaluate(async (cap) => {
144
+ if (typeof document.getAnimations !== "function") return;
145
+ const finite = document.getAnimations().filter((animation) => {
146
+ const timing = animation.effect && "getComputedTiming" in animation.effect ? animation.effect.getComputedTiming() : null;
147
+ const iterations = timing ? timing.iterations : void 0;
148
+ return iterations !== Infinity && iterations !== null;
149
+ });
150
+ if (finite.length === 0) return;
151
+ await Promise.race([Promise.all(finite.map((animation) => animation.finished.catch(() => void 0))), new Promise((resolve) => setTimeout(resolve, cap))]);
152
+ }, capMs).catch(() => {});
153
+ }
154
+ /**
155
+ * Install HAR replay on a page, when the caller asked for it.
156
+ *
157
+ * `notFound: "abort"` rather than Playwright's default `"fallback"`, and that is
158
+ * a real trade the caller has to know about:
159
+ *
160
+ * - `abort` is what makes `--har` solve the problem it was added for. The hang
161
+ * in issue #112 was a third-party request that never settles; `fallback`
162
+ * would let that same request through to the network and the run would hang
163
+ * exactly as before. `abort` is also what makes a HAR run reproducible
164
+ * offline, which is the other reason to record one.
165
+ * - The cost: an *incomplete* HAR turns every un-recorded subresource into a
166
+ * failed request. On gates that judge resources — `check integrity`'s
167
+ * `broken-image` / `failed-stylesheet` / `broken-font` rules — that reads as
168
+ * a defect in the page rather than as a gap in the recording, so HAR
169
+ * completeness silently becomes part of the verdict. Record with
170
+ * `browser.newContext({ recordHar: { path } })` over the same navigation the
171
+ * gate will perform, and treat new findings under `--har` as suspect until
172
+ * the recording has been refreshed.
173
+ *
174
+ * This was already the behaviour at `check integrity`'s and `check design`'s own
175
+ * goto sites (both hardcoded `notFound: "abort"`); it lives here so the trade is
176
+ * documented once and the gates that have since adopted `--har` cannot disagree
177
+ * about it.
178
+ */
179
+ async function applyHar(page, har) {
180
+ if (!har) return null;
181
+ const path = resolve(har);
182
+ await page.routeFromHAR(path, { notFound: "abort" });
183
+ return trackHarMisses(page, path);
184
+ }
185
+ function trackHarMisses(page, path) {
186
+ const recorded = /* @__PURE__ */ new Set();
187
+ const origins = [];
188
+ try {
189
+ const har = JSON.parse(readFileSync(path, "utf-8"));
190
+ for (const entry of har.log?.entries ?? []) {
191
+ const url = entry.request?.url;
192
+ if (!url) continue;
193
+ recorded.add(url);
194
+ const origin = originOfUrl(url);
195
+ if (origin && !origins.includes(origin)) origins.push(origin);
196
+ }
197
+ } catch {}
198
+ const missed = [];
199
+ const isMiss = (url) => !recorded.has(url);
200
+ if (!(typeof page?.on === "function" && typeof page?.goto === "function")) return {
201
+ path,
202
+ origins,
203
+ isMiss,
204
+ misses: () => missed,
205
+ originMismatch: (pageUrl) => {
206
+ const target = originOfUrl(pageUrl);
207
+ if (!target || origins.length === 0) return null;
208
+ return origins.includes(target) ? null : target;
209
+ }
210
+ };
211
+ page.on("requestfailed", (request) => {
212
+ const url = request.url();
213
+ if (isMiss(url) && !missed.includes(url)) missed.push(url);
214
+ });
215
+ const originalGoto = page.goto.bind(page);
216
+ page.goto = async (url, gotoOptions) => {
217
+ try {
218
+ return await originalGoto(url, gotoOptions);
219
+ } catch (error) {
220
+ const message = error instanceof Error ? error.message : String(error);
221
+ const target = originOfUrl(url);
222
+ if (!/ERR_FAILED/.test(message) || !target || origins.length === 0 || origins.includes(target)) throw error;
223
+ const explained = /* @__PURE__ */ new Error(`the --har recording holds nothing for ${target}, so even the page itself was aborted.\n ${path}\n it recorded: ${origins.join(", ")}\n A HAR is keyed on the full URL, so a different host or port stops matching entirely. Re-record against ${target}, or serve the page on the recorded origin.`);
224
+ explained.cause = error;
225
+ throw explained;
226
+ }
227
+ };
228
+ return {
229
+ path,
230
+ origins,
231
+ isMiss,
232
+ misses: () => missed,
233
+ originMismatch: (pageUrl) => {
234
+ const target = originOfUrl(pageUrl);
235
+ if (!target || origins.length === 0) return null;
236
+ return origins.includes(target) ? null : target;
237
+ }
238
+ };
239
+ }
240
+ function originOfUrl(url) {
241
+ try {
242
+ return new URL(url).origin;
243
+ } catch {
244
+ return null;
245
+ }
246
+ }
79
247
  function pageOptions(options) {
80
248
  return withAuthState({
81
249
  ...options.viewport ? { viewport: options.viewport } : {},
@@ -88,11 +256,12 @@ function pageOptions(options) {
88
256
  */
89
257
  async function openSource(browser, source, options = {}) {
90
258
  const page = await browser.newPage(pageOptions(options));
259
+ await applyHar(page, options.har);
91
260
  await page.goto(sourceToUrl(source), {
92
261
  waitUntil: options.waitUntil ?? "networkidle",
93
262
  timeout: options.timeout ?? 3e4
94
263
  });
95
- if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250);
264
+ if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250, options.animationCapMs);
96
265
  return {
97
266
  page,
98
267
  redirect: isUrlSource(source) ? describeRedirect(source, page.url()) : null
@@ -118,6 +287,7 @@ async function openSource(browser, source, options = {}) {
118
287
  */
119
288
  async function openHtml(browser, html, options = {}) {
120
289
  const page = await browser.newPage(pageOptions(options));
290
+ await applyHar(page, options.har);
121
291
  if (options.baseSource) await page.goto(sourceToUrl(options.baseSource), {
122
292
  waitUntil: "domcontentloaded",
123
293
  timeout: options.timeout ?? 3e4
@@ -126,8 +296,8 @@ async function openHtml(browser, html, options = {}) {
126
296
  waitUntil: options.waitUntil ?? "networkidle",
127
297
  timeout: options.timeout ?? 3e4
128
298
  });
129
- if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250);
299
+ if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250, options.animationCapMs);
130
300
  return page;
131
301
  }
132
302
  //#endregion
133
- export { isUrlSource, openHtml, openSource, resolveSource, settlePage, sourceToUrl };
303
+ export { applyHar, isUrlSource, openHtml, openSource, resolveSource, settlePage, sourceToUrl };
@@ -0,0 +1,86 @@
1
+ //#region src/plugin/args.d.ts
2
+ /**
3
+ * Argument helpers for writing a gate — the shapes `arg-reader` does not cover.
4
+ *
5
+ * `../arg-reader.ts` already refuses to guess (a missing value is an error,
6
+ * `--output --json` does not consume the flag as a value). These are the two or
7
+ * three shapes it does not, kept in one place so gates stop re-implementing the
8
+ * loop that produced `Number.parseInt(argv[++i] ?? "12", 10)` twenty times over —
9
+ * a form that silently accepts `--max-findings --json` as `NaN`.
10
+ *
11
+ * These lived in `vlmkit-markup/src/gates/arg-helpers.ts` until v7, which is
12
+ * where a third-party plugin author found them: `firstPositional` is the first
13
+ * line of almost every gate's `parse`, and getting it meant taking a dependency
14
+ * on the markup package for an argv helper. Every function here is pure and
15
+ * imports nothing but core, so the old location was an accident of history
16
+ * rather than a boundary. Re-exported from `./index.ts`, which is the entry a
17
+ * plugin should import.
18
+ */
19
+ declare function firstPositional(argv: readonly string[], usage: string, valueFlags?: readonly string[]): string;
20
+ /**
21
+ * The first positional, or `undefined` when there is none.
22
+ *
23
+ * For gates whose source is optional because another flag supplies the input — the
24
+ * distinction `check integrity` needs in order to *reject* being given both a page and
25
+ * `--elements` rather than silently preferring one.
26
+ */
27
+ declare function firstPositionalOrUndefined(argv: readonly string[], valueFlags?: readonly string[]): string | undefined;
28
+ /**
29
+ * Drop an optionally-valued flag and whatever value it consumed.
30
+ *
31
+ * `readPositionals` takes a list of flags that *always* take a value, which
32
+ * cannot express `--vlm` (bare = default model, or `--vlm <id>`). Listing it
33
+ * would make bare `--vlm page.html` eat the source; omitting it made
34
+ * `--vlm <model> page.html` return the model id AS the source — the gate then
35
+ * tried to open `bytedance/ui-tars-1.5-7b` as a file. Both `check copy` and
36
+ * `check equivalence` shipped the second bug.
37
+ *
38
+ * The rule here is `vlmFlag`'s rule, so the two cannot disagree about which
39
+ * token is the model: the next token is the value iff it does not start with
40
+ * `-`. With that token removed, `--vlm page.html --target t.png` has no
41
+ * positional left and fails with the usage line, which is the honest outcome
42
+ * for a genuinely ambiguous command line.
43
+ */
44
+ declare function withoutOptionalValue(argv: readonly string[], name: string): string[];
45
+ /** `--breakpoints 768,1024` → `[768, 1024]`. Absent flag → `undefined`. */
46
+ declare function numberList(argv: readonly string[], name: string): number[] | undefined;
47
+ /**
48
+ * Like `numberList`, but for scales that are legitimately fractional
49
+ * (`--tolerance`-adjacent flags such as `--radius-scale 0,2,4.5`).
50
+ */
51
+ declare function numberListFloat(argv: readonly string[], name: string): number[] | undefined;
52
+ /** `--viewport 1280x720` → `{width, height}`. */
53
+ declare function viewportFlag(argv: readonly string[], name?: string): {
54
+ width: number;
55
+ height: number;
56
+ } | undefined;
57
+ declare function optionalInt(argv: readonly string[], name: string, options?: {
58
+ min?: number;
59
+ }): number | undefined;
60
+ /**
61
+ * `--vlm` (use the default model) or `--vlm <model-id>`. Returns `undefined`
62
+ * when the flag is absent, which is the "stay deterministic" default —
63
+ * every gate that accepts a VLM works without one.
64
+ *
65
+ * `readFlag` cannot express this: the value is optional, so a bare `--vlm`
66
+ * followed by another flag must not consume it.
67
+ */
68
+ declare function vlmFlag(argv: readonly string[], name?: string): string | true | undefined;
69
+ /**
70
+ * Default output directory for a gate run, keyed on what the run measured.
71
+ *
72
+ * One directory per gate is a clobber waiting to happen, and it has now bitten twice.
73
+ * v2's evidence agent read somebody else's report out of `check drift component`'s
74
+ * shared path — "`cat test-results/component-consistency/report.md` returned a
75
+ * *different* run [...] A parallel agent had clobbered it. I trusted the terminal."
76
+ * That was fixed for drift alone. v5's repair agent then noticed `check a11y contrast`
77
+ * writing to the repo root, and measuring it showed the same defect: two pages one
78
+ * after the other share `report.md` AND `page.png`, so the second silently replaces
79
+ * the first.
80
+ *
81
+ * `discriminator` is for a gate where the source is not the whole question - drift
82
+ * passes its `--selector`, since two selectors on one page are two different runs.
83
+ */
84
+ declare function runOutputDir(gateDir: string, source: string, discriminator?: string): string;
85
+ //#endregion
86
+ export { firstPositional, firstPositionalOrUndefined, numberList, numberListFloat, optionalInt, runOutputDir, viewportFlag, vlmFlag, withoutOptionalValue };
@@ -0,0 +1,162 @@
1
+ import { UsageError } from "../cli-error.mjs";
2
+ import { readFlag, readInt, readPositionals } from "../arg-reader.mjs";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/plugin/args.ts
6
+ /**
7
+ * Argument helpers for writing a gate — the shapes `arg-reader` does not cover.
8
+ *
9
+ * `../arg-reader.ts` already refuses to guess (a missing value is an error,
10
+ * `--output --json` does not consume the flag as a value). These are the two or
11
+ * three shapes it does not, kept in one place so gates stop re-implementing the
12
+ * loop that produced `Number.parseInt(argv[++i] ?? "12", 10)` twenty times over —
13
+ * a form that silently accepts `--max-findings --json` as `NaN`.
14
+ *
15
+ * These lived in `vlmkit-markup/src/gates/arg-helpers.ts` until v7, which is
16
+ * where a third-party plugin author found them: `firstPositional` is the first
17
+ * line of almost every gate's `parse`, and getting it meant taking a dependency
18
+ * on the markup package for an argv helper. Every function here is pure and
19
+ * imports nothing but core, so the old location was an accident of history
20
+ * rather than a boundary. Re-exported from `./index.ts`, which is the entry a
21
+ * plugin should import.
22
+ */
23
+ /**
24
+ * Flags that take a value, so `readPositionals` does not mistake the value
25
+ * for a positional. Extend per gate via the `valueFlags` argument.
26
+ */
27
+ const COMMON_VALUE_FLAGS = [
28
+ "--viewports",
29
+ "--viewport",
30
+ "--breakpoints",
31
+ "--height",
32
+ "--max-elements",
33
+ "--max-findings",
34
+ "--max-samples",
35
+ "--sweep-step",
36
+ "--timeout",
37
+ "--wait-until",
38
+ "--har",
39
+ "--storage-state",
40
+ "--allow",
41
+ "--contract",
42
+ "--elements",
43
+ "--image"
44
+ ];
45
+ function firstPositional(argv, usage, valueFlags = []) {
46
+ const first = firstPositionalOrUndefined(argv, valueFlags);
47
+ if (!first) throw new UsageError(`missing required argument. Usage: ${usage}`);
48
+ return first;
49
+ }
50
+ /**
51
+ * The first positional, or `undefined` when there is none.
52
+ *
53
+ * For gates whose source is optional because another flag supplies the input — the
54
+ * distinction `check integrity` needs in order to *reject* being given both a page and
55
+ * `--elements` rather than silently preferring one.
56
+ */
57
+ function firstPositionalOrUndefined(argv, valueFlags = []) {
58
+ return readPositionals(argv, [...COMMON_VALUE_FLAGS, ...valueFlags])[0];
59
+ }
60
+ /**
61
+ * Drop an optionally-valued flag and whatever value it consumed.
62
+ *
63
+ * `readPositionals` takes a list of flags that *always* take a value, which
64
+ * cannot express `--vlm` (bare = default model, or `--vlm <id>`). Listing it
65
+ * would make bare `--vlm page.html` eat the source; omitting it made
66
+ * `--vlm <model> page.html` return the model id AS the source — the gate then
67
+ * tried to open `bytedance/ui-tars-1.5-7b` as a file. Both `check copy` and
68
+ * `check equivalence` shipped the second bug.
69
+ *
70
+ * The rule here is `vlmFlag`'s rule, so the two cannot disagree about which
71
+ * token is the model: the next token is the value iff it does not start with
72
+ * `-`. With that token removed, `--vlm page.html --target t.png` has no
73
+ * positional left and fails with the usage line, which is the honest outcome
74
+ * for a genuinely ambiguous command line.
75
+ */
76
+ function withoutOptionalValue(argv, name) {
77
+ const flag = `--${name}`;
78
+ const out = [];
79
+ for (let i = 0; i < argv.length; i++) {
80
+ const arg = argv[i];
81
+ if (arg !== flag) {
82
+ out.push(arg);
83
+ continue;
84
+ }
85
+ const next = argv[i + 1];
86
+ if (next !== void 0 && !next.startsWith("-")) i++;
87
+ }
88
+ return out;
89
+ }
90
+ /** `--breakpoints 768,1024` → `[768, 1024]`. Absent flag → `undefined`. */
91
+ function numberList(argv, name) {
92
+ const raw = readFlag(argv, name);
93
+ if (raw === void 0) return void 0;
94
+ return raw.split(",").map((part) => part.trim()).filter(Boolean).map((part) => {
95
+ const n = Number.parseInt(part, 10);
96
+ if (!Number.isFinite(n)) throw new UsageError(`--${name}: "${part}" is not a number`);
97
+ return n;
98
+ });
99
+ }
100
+ /**
101
+ * Like `numberList`, but for scales that are legitimately fractional
102
+ * (`--tolerance`-adjacent flags such as `--radius-scale 0,2,4.5`).
103
+ */
104
+ function numberListFloat(argv, name) {
105
+ const raw = readFlag(argv, name);
106
+ if (raw === void 0) return void 0;
107
+ return raw.split(",").map((part) => part.trim()).filter(Boolean).map((part) => {
108
+ const n = Number.parseFloat(part);
109
+ if (!Number.isFinite(n)) throw new UsageError(`--${name}: "${part}" is not a number`);
110
+ return n;
111
+ });
112
+ }
113
+ /** `--viewport 1280x720` → `{width, height}`. */
114
+ function viewportFlag(argv, name = "viewport") {
115
+ const raw = readFlag(argv, name);
116
+ if (raw === void 0) return void 0;
117
+ const match = raw.match(/^(\d+)x(\d+)$/);
118
+ if (!match) throw new UsageError(`--${name} expects <width>x<height>, got ${JSON.stringify(raw)}`);
119
+ return {
120
+ width: Number(match[1]),
121
+ height: Number(match[2])
122
+ };
123
+ }
124
+ function optionalInt(argv, name, options = {}) {
125
+ return readInt(argv, name, options);
126
+ }
127
+ /**
128
+ * `--vlm` (use the default model) or `--vlm <model-id>`. Returns `undefined`
129
+ * when the flag is absent, which is the "stay deterministic" default —
130
+ * every gate that accepts a VLM works without one.
131
+ *
132
+ * `readFlag` cannot express this: the value is optional, so a bare `--vlm`
133
+ * followed by another flag must not consume it.
134
+ */
135
+ function vlmFlag(argv, name = "vlm") {
136
+ const index = argv.lastIndexOf(`--${name}`);
137
+ if (index < 0) return void 0;
138
+ const next = argv[index + 1];
139
+ return next !== void 0 && !next.startsWith("-") ? next : true;
140
+ }
141
+ /**
142
+ * Default output directory for a gate run, keyed on what the run measured.
143
+ *
144
+ * One directory per gate is a clobber waiting to happen, and it has now bitten twice.
145
+ * v2's evidence agent read somebody else's report out of `check drift component`'s
146
+ * shared path — "`cat test-results/component-consistency/report.md` returned a
147
+ * *different* run [...] A parallel agent had clobbered it. I trusted the terminal."
148
+ * That was fixed for drift alone. v5's repair agent then noticed `check a11y contrast`
149
+ * writing to the repo root, and measuring it showed the same defect: two pages one
150
+ * after the other share `report.md` AND `page.png`, so the second silently replaces
151
+ * the first.
152
+ *
153
+ * `discriminator` is for a gate where the source is not the whole question - drift
154
+ * passes its `--selector`, since two selectors on one page are two different runs.
155
+ */
156
+ function runOutputDir(gateDir, source, discriminator = "") {
157
+ const name = basename(source).replace(/\.[^.]+$/, "") || "page";
158
+ const hash = createHash("sha1").update(resolve(source) + " " + discriminator).digest("hex").slice(0, 8);
159
+ return join(process.cwd(), "test-results", gateDir, name.replace(/[^A-Za-z0-9._-]+/g, "-") + "-" + hash);
160
+ }
161
+ //#endregion
162
+ export { firstPositional, firstPositionalOrUndefined, numberList, numberListFloat, optionalInt, runOutputDir, viewportFlag, vlmFlag, withoutOptionalValue };
@@ -0,0 +1,6 @@
1
+ import { withAuthState } from "../auth-state.mjs";
2
+ import { launchBrowser, withBrowser } from "../browser-launch.mjs";
3
+ import { LedgerWrite, RunLedgerEntry, appendRunLedger, configureRunLedger, firstLedgerWrite } from "../run-ledger.mjs";
4
+ import { describeRedirect } from "../navigation-redirect.mjs";
5
+ import { HarReplay, applyHar, openSource } from "../page-open.mjs";
6
+ export { type HarReplay, type LedgerWrite, type RunLedgerEntry, appendRunLedger, applyHar, configureRunLedger, describeRedirect, firstLedgerWrite, launchBrowser, openSource, withAuthState, withBrowser };
@@ -0,0 +1,6 @@
1
+ import { withAuthState } from "../auth-state.mjs";
2
+ import { launchBrowser, withBrowser } from "../browser-launch.mjs";
3
+ import { describeRedirect } from "../navigation-redirect.mjs";
4
+ import { applyHar, openSource } from "../page-open.mjs";
5
+ import { appendRunLedger, configureRunLedger, firstLedgerWrite } from "../run-ledger.mjs";
6
+ export { appendRunLedger, applyHar, configureRunLedger, describeRedirect, firstLedgerWrite, launchBrowser, openSource, withAuthState, withBrowser };
@@ -0,0 +1,11 @@
1
+ //#region src/plugin/cli-entry.d.ts
2
+ /**
3
+ * @param moduleUrl always `import.meta.url` from the module asking.
4
+ * @param dispatcherName the module's name in `vlmkit`'s command table, when it has
5
+ * one. `delegate()` sets `__VLMKIT_DISPATCHER_LEAF__` and then imports the module,
6
+ * so for a dispatched command the env var is the entry signal and argv[1] is the
7
+ * dispatcher rather than the module.
8
+ */
9
+ declare function isCliEntry(moduleUrl: string, dispatcherName?: string): boolean;
10
+ //#endregion
11
+ export { isCliEntry };
@@ -0,0 +1,69 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/plugin/cli-entry.ts
5
+ /**
6
+ * "Was this module run, or imported?"
7
+ *
8
+ * The repo answered it by hand in several spellings. Two are wrong, and both were
9
+ * measured rather than reasoned about:
10
+ *
11
+ * - `process.argv[1]?.endsWith("thing.ts")` — a suffix match, so `run.ts` and
12
+ * `dry-run.ts` are indistinguishable (this repo had that collision for real, between
13
+ * `src/vrt/snapshot/snapshot.ts` and `src/cli/commands/snapshot.ts`), and it stops
14
+ * matching once the file is built to `.mjs`: `node dist/png-diff.mjs --help` printed
15
+ * nothing at all.
16
+ * - `new URL(import.meta.url).pathname === process.argv[1]` — a URL pathname is
17
+ * percent-encoded and argv is not, so any path containing a space fails:
18
+ * `/tmp/has%20space/x.mjs` never equals `/tmp/has space/x.mjs`. It is also broken on
19
+ * Windows, where `pathname` carries a leading slash before the drive letter. (Node
20
+ * absolutizes `argv[1]`, so a *relative* invocation does match — an earlier commit
21
+ * message of mine gave that as the reason and was wrong about it, though not about
22
+ * the fix.)
23
+ *
24
+ * It matters more than a tidiness question. Eleven command modules had NO guard at
25
+ * all — a bare `main().catch(...)` at the bottom — so importing one for a type or a
26
+ * helper *ran the command*. That is why they had 0% coverage: a test cannot import
27
+ * what executes on import. Giving them a guard is what makes them callable, and a
28
+ * guard is only trustworthy if it is exactly right about which module is the entry.
29
+ */
30
+ /**
31
+ * Resolve symlinks when we can, and fall back to a plain resolve when we cannot.
32
+ *
33
+ * This is what npm's bin shims require. `node_modules/.bin/vlmkit-generate` is a symlink
34
+ * to `dist/cli.mjs`, so `argv[1]` is the shim while `import.meta.url` is the real file:
35
+ * comparing resolved-but-not-realpathed paths gives `false`, and the CLI does nothing.
36
+ * Measured through a symlink — `resolve` only: false; `realpathSync` both sides: true.
37
+ * `vlmkit-generate` and `vlmkit-plan` had figured this out and carry their own
38
+ * `realpathSync` guard; they do not depend on core, which is why they keep it.
39
+ *
40
+ * `realpathSync` throws for a path that does not exist, which is why the fallback is
41
+ * here rather than at the call site — a guard that throws takes down the import instead
42
+ * of answering the question.
43
+ */
44
+ function canonical(path) {
45
+ try {
46
+ return realpathSync(path);
47
+ } catch {
48
+ return resolve(path);
49
+ }
50
+ }
51
+ /**
52
+ * @param moduleUrl always `import.meta.url` from the module asking.
53
+ * @param dispatcherName the module's name in `vlmkit`'s command table, when it has
54
+ * one. `delegate()` sets `__VLMKIT_DISPATCHER_LEAF__` and then imports the module,
55
+ * so for a dispatched command the env var is the entry signal and argv[1] is the
56
+ * dispatcher rather than the module.
57
+ */
58
+ function isCliEntry(moduleUrl, dispatcherName) {
59
+ if (dispatcherName && process.env.__VLMKIT_DISPATCHER_LEAF__ === dispatcherName) return true;
60
+ const invoked = process.argv[1];
61
+ if (!invoked) return false;
62
+ try {
63
+ return canonical(invoked) === canonical(fileURLToPath(moduleUrl));
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ //#endregion
69
+ export { isCliEntry };