@mizchi/vlmkit-core 0.8.1 → 0.9.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  VRT diff engine and shared types. Pure-TypeScript image / DOM / a11y / visual
4
4
  comparison primitives — no Playwright required for the lightweight surface.
5
5
 
6
- Part of the [`vrt`](https://github.com/mizchi/vrt) monorepo.
6
+ Part of the [`vlmkit`](https://github.com/mizchi/vrt) monorepo.
7
7
 
8
8
  ## Install
9
9
 
@@ -0,0 +1,52 @@
1
+ //#region src/arg-reader.d.ts
2
+ /**
3
+ * Argv readers that take the array explicitly, and refuse to guess.
4
+ *
5
+ * `cli-args.ts` binds to `process.argv` at import time, which makes it
6
+ * untestable and unusable from a dispatcher-driven leaf. The hand-rolled
7
+ * readers that grew in its place all shared two silent failure modes:
8
+ *
9
+ * - `--output --json` consumed `--json` as the output directory;
10
+ * - `--concurrency abc` produced `NaN`, and `NaN` does not fail loudly. It
11
+ * made `runPool` build zero lanes and "successfully" run nothing.
12
+ *
13
+ * So a missing value is an error, a value that looks like another flag is an
14
+ * error, and a numeric flag is validated where it is read rather than wherever
15
+ * the NaN eventually lands.
16
+ */
17
+ declare function hasFlag(argv: readonly string[], name: string): boolean;
18
+ /**
19
+ * Last occurrence wins, matching how shells and most CLIs behave when a flag is
20
+ * repeated. Throws when the value is missing or is another flag.
21
+ */
22
+ declare function readFlag(argv: readonly string[], name: string): string | undefined;
23
+ /** Every occurrence, for repeatable flags (`--gate`, `--only`, `--pages`). */
24
+ declare function readAll(argv: readonly string[], name: string): string[];
25
+ interface NumberFlagOptions {
26
+ min?: number;
27
+ max?: number;
28
+ integer?: boolean;
29
+ }
30
+ declare function readNumber(argv: readonly string[], name: string, options?: NumberFlagOptions): number | undefined;
31
+ declare function readInt(argv: readonly string[], name: string, options?: NumberFlagOptions): number | undefined;
32
+ /**
33
+ * Arguments that are neither a flag nor a flag's value.
34
+ *
35
+ * The caller has to name the flags that take values, because argv alone cannot
36
+ * tell `--concurrency 4` (a value) from `--quiet page.html` (a positional). The
37
+ * hand-rolled version of this was a for-loop per CLI that advanced its own
38
+ * index, i.e. the same knowledge encoded three times.
39
+ */
40
+ declare function readPositionals(argv: readonly string[], valueFlags?: readonly string[]): string[];
41
+ /**
42
+ * Split a command string into argv, honouring quotes.
43
+ *
44
+ * Needed because gate commands are authored as single strings — in a config
45
+ * file (`"check copy --manifest copy/press kit.txt"`) or on the command line
46
+ * (`--gate 'check breakpoints --mask ".hero, .promo"'`). Splitting on
47
+ * whitespace would hand the gate `kit.txt` and `.promo"` as separate
48
+ * arguments, which fails in a way that looks like the gate's fault.
49
+ */
50
+ declare function tokenizeCommand(command: string): string[];
51
+ //#endregion
52
+ export { NumberFlagOptions, hasFlag, readAll, readFlag, readInt, readNumber, readPositionals, tokenizeCommand };
@@ -0,0 +1,129 @@
1
+ import { UsageError } from "./cli-error.mjs";
2
+ //#region src/arg-reader.ts
3
+ /**
4
+ * Argv readers that take the array explicitly, and refuse to guess.
5
+ *
6
+ * `cli-args.ts` binds to `process.argv` at import time, which makes it
7
+ * untestable and unusable from a dispatcher-driven leaf. The hand-rolled
8
+ * readers that grew in its place all shared two silent failure modes:
9
+ *
10
+ * - `--output --json` consumed `--json` as the output directory;
11
+ * - `--concurrency abc` produced `NaN`, and `NaN` does not fail loudly. It
12
+ * made `runPool` build zero lanes and "successfully" run nothing.
13
+ *
14
+ * So a missing value is an error, a value that looks like another flag is an
15
+ * error, and a numeric flag is validated where it is read rather than wherever
16
+ * the NaN eventually lands.
17
+ */
18
+ const flagName = (name) => name.startsWith("-") ? name : `--${name}`;
19
+ /** A value must not itself look like a flag — `-1` is a value, `--json` is not. */
20
+ const looksLikeFlag = (value) => /^--/.test(value) || /^-[a-zA-Z]/.test(value);
21
+ function hasFlag(argv, name) {
22
+ return argv.includes(flagName(name));
23
+ }
24
+ /**
25
+ * Last occurrence wins, matching how shells and most CLIs behave when a flag is
26
+ * repeated. Throws when the value is missing or is another flag.
27
+ */
28
+ function readFlag(argv, name) {
29
+ const flag = flagName(name);
30
+ const index = argv.lastIndexOf(flag);
31
+ if (index < 0) return void 0;
32
+ const value = argv[index + 1];
33
+ if (value === void 0) throw new UsageError(`${flag} needs a value`);
34
+ if (looksLikeFlag(value)) throw new UsageError(`${flag} needs a value, got the next flag ${value}`);
35
+ return value;
36
+ }
37
+ /** Every occurrence, for repeatable flags (`--gate`, `--only`, `--pages`). */
38
+ function readAll(argv, name) {
39
+ const flag = flagName(name);
40
+ const out = [];
41
+ for (let i = 0; i < argv.length; i++) {
42
+ if (argv[i] !== flag) continue;
43
+ const value = argv[i + 1];
44
+ if (value === void 0) throw new UsageError(`${flag} needs a value`);
45
+ if (looksLikeFlag(value)) throw new UsageError(`${flag} needs a value, got the next flag ${value}`);
46
+ out.push(value);
47
+ i++;
48
+ }
49
+ return out;
50
+ }
51
+ function readNumber(argv, name, options = {}) {
52
+ const raw = readFlag(argv, name);
53
+ if (raw === void 0) return void 0;
54
+ const flag = flagName(name);
55
+ const value = Number.parseFloat(raw);
56
+ if (!Number.isFinite(value) || !/^-?\d+(\.\d+)?$/.test(raw.trim())) throw new UsageError(`${flag} must be a number, got "${raw}"`);
57
+ if (options.integer && !Number.isInteger(value)) throw new UsageError(`${flag} must be a whole number, got "${raw}"`);
58
+ if (options.min !== void 0 && value < options.min) throw new UsageError(`${flag} must be >= ${options.min}, got ${value}`);
59
+ if (options.max !== void 0 && value > options.max) throw new UsageError(`${flag} must be <= ${options.max}, got ${value}`);
60
+ return value;
61
+ }
62
+ function readInt(argv, name, options = {}) {
63
+ return readNumber(argv, name, {
64
+ ...options,
65
+ integer: true
66
+ });
67
+ }
68
+ /**
69
+ * Arguments that are neither a flag nor a flag's value.
70
+ *
71
+ * The caller has to name the flags that take values, because argv alone cannot
72
+ * tell `--concurrency 4` (a value) from `--quiet page.html` (a positional). The
73
+ * hand-rolled version of this was a for-loop per CLI that advanced its own
74
+ * index, i.e. the same knowledge encoded three times.
75
+ */
76
+ function readPositionals(argv, valueFlags = []) {
77
+ const takesValue = new Set(valueFlags.map(flagName));
78
+ const out = [];
79
+ for (let i = 0; i < argv.length; i++) {
80
+ const arg = argv[i];
81
+ if (takesValue.has(arg)) {
82
+ i++;
83
+ continue;
84
+ }
85
+ if (arg.startsWith("-")) continue;
86
+ out.push(arg);
87
+ }
88
+ return out;
89
+ }
90
+ /**
91
+ * Split a command string into argv, honouring quotes.
92
+ *
93
+ * Needed because gate commands are authored as single strings — in a config
94
+ * file (`"check copy --manifest copy/press kit.txt"`) or on the command line
95
+ * (`--gate 'check breakpoints --mask ".hero, .promo"'`). Splitting on
96
+ * whitespace would hand the gate `kit.txt` and `.promo"` as separate
97
+ * arguments, which fails in a way that looks like the gate's fault.
98
+ */
99
+ function tokenizeCommand(command) {
100
+ const out = [];
101
+ let current = "";
102
+ let quote = null;
103
+ let started = false;
104
+ for (const char of command) {
105
+ if (quote) {
106
+ if (char === quote) quote = null;
107
+ else current += char;
108
+ continue;
109
+ }
110
+ if (char === "\"" || char === "'") {
111
+ quote = char;
112
+ started = true;
113
+ continue;
114
+ }
115
+ if (/\s/.test(char)) {
116
+ if (started) out.push(current);
117
+ current = "";
118
+ started = false;
119
+ continue;
120
+ }
121
+ current += char;
122
+ started = true;
123
+ }
124
+ if (quote) throw new UsageError(`Unterminated ${quote} quote in command: ${command}`);
125
+ if (started) out.push(current);
126
+ return out;
127
+ }
128
+ //#endregion
129
+ export { hasFlag, readAll, readFlag, readInt, readNumber, readPositionals, tokenizeCommand };
@@ -0,0 +1,30 @@
1
+ //#region src/auth-state.d.ts
2
+ declare const STORAGE_STATE_ENV = "VLMKIT_STORAGE_STATE";
3
+ /**
4
+ * Explicit flag beats env; returns undefined when neither is set. A blank
5
+ * explicit value counts as "not passed" and falls through to the
6
+ * environment, so `--storage-state "$MAYBE_UNSET"` in a script does not
7
+ * silently disable an env-configured session.
8
+ */
9
+ declare function storageStatePath(explicit?: string): string | undefined;
10
+ /**
11
+ * Validate eagerly and loudly. A silently ignored auth file would send the
12
+ * caller straight back to the failure this feature exists to fix — an
13
+ * unauthenticated measurement that looks like a real result.
14
+ */
15
+ declare function readStorageState(path: string): {
16
+ cookies: unknown[];
17
+ origins: unknown[];
18
+ };
19
+ /**
20
+ * Merge `storageState` into Playwright page options when configured.
21
+ * `browser.newPage(options)` forwards context options, so every gate can
22
+ * adopt this by wrapping its existing options object.
23
+ */
24
+ declare function withAuthState<T extends object>(base: T, explicit?: string): T & {
25
+ storageState?: string;
26
+ };
27
+ /** One-line notice so a run that used auth says so in its output. */
28
+ declare function authStateNotice(explicit?: string): string | null;
29
+ //#endregion
30
+ export { STORAGE_STATE_ENV, authStateNotice, readStorageState, storageStatePath, withAuthState };
@@ -0,0 +1,82 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ //#region src/auth-state.ts
4
+ /**
5
+ * Authenticated-page support for the gates.
6
+ *
7
+ * The 2026-08-01 hard-target audit made the auth gap loud (a redirect to a
8
+ * login wall is now a reported defect instead of a silent CLEAN), but loud
9
+ * failure is not access: for most product apps the interesting pages —
10
+ * dashboard, checkout, settings — are all behind a session. This closes
11
+ * that by accepting a Playwright storage-state file, which is the format
12
+ * `playwright codegen --save-storage` and `context.storageState()` already
13
+ * produce, so teams reuse the artifact their e2e suite has.
14
+ *
15
+ * Two ways in, because gate invocations live in CI yaml / npm scripts and
16
+ * threading a flag through every one of them is the exact config sprawl
17
+ * this project is trying not to create:
18
+ * - `--storage-state <path>` on any URL-capable gate
19
+ * - `VLMKIT_STORAGE_STATE=<path>` for all of them at once
20
+ *
21
+ * An explicit flag always wins over the environment.
22
+ */
23
+ const STORAGE_STATE_ENV = "VLMKIT_STORAGE_STATE";
24
+ /**
25
+ * Explicit flag beats env; returns undefined when neither is set. A blank
26
+ * explicit value counts as "not passed" and falls through to the
27
+ * environment, so `--storage-state "$MAYBE_UNSET"` in a script does not
28
+ * silently disable an env-configured session.
29
+ */
30
+ function storageStatePath(explicit) {
31
+ for (const candidate of [explicit, process.env[STORAGE_STATE_ENV]]) if (candidate && candidate.trim() !== "") return candidate;
32
+ }
33
+ /**
34
+ * Validate eagerly and loudly. A silently ignored auth file would send the
35
+ * caller straight back to the failure this feature exists to fix — an
36
+ * unauthenticated measurement that looks like a real result.
37
+ */
38
+ function readStorageState(path) {
39
+ const abs = resolve(path);
40
+ let raw;
41
+ try {
42
+ raw = readFileSync(abs, "utf8");
43
+ } catch {
44
+ throw new Error(`storage state file not found: ${abs}\nCreate one with: npx playwright codegen --save-storage=auth.json <your-login-url>`);
45
+ }
46
+ let parsed;
47
+ try {
48
+ parsed = JSON.parse(raw);
49
+ } catch {
50
+ throw new Error(`storage state file is not valid JSON: ${abs}`);
51
+ }
52
+ const obj = parsed;
53
+ if (!obj || typeof obj !== "object" || !Array.isArray(obj.cookies) && !Array.isArray(obj.origins)) throw new Error(`storage state file has no "cookies" or "origins" array: ${abs}\nExpected a Playwright storage-state file (context.storageState() output).`);
54
+ const cookies = Array.isArray(obj.cookies) ? obj.cookies : [];
55
+ const origins = Array.isArray(obj.origins) ? obj.origins : [];
56
+ if (cookies.length === 0 && origins.length === 0) throw new Error(`storage state file carries no cookies and no origins: ${abs}\nIt would authenticate nothing — re-capture it after logging in.`);
57
+ return {
58
+ cookies,
59
+ origins
60
+ };
61
+ }
62
+ /**
63
+ * Merge `storageState` into Playwright page options when configured.
64
+ * `browser.newPage(options)` forwards context options, so every gate can
65
+ * adopt this by wrapping its existing options object.
66
+ */
67
+ function withAuthState(base, explicit) {
68
+ const path = storageStatePath(explicit);
69
+ if (!path) return base;
70
+ readStorageState(path);
71
+ return {
72
+ ...base,
73
+ storageState: resolve(path)
74
+ };
75
+ }
76
+ /** One-line notice so a run that used auth says so in its output. */
77
+ function authStateNotice(explicit) {
78
+ const path = storageStatePath(explicit);
79
+ return path ? `auth: storage state from ${resolve(path)}` : null;
80
+ }
81
+ //#endregion
82
+ export { STORAGE_STATE_ENV, authStateNotice, readStorageState, storageStatePath, withAuthState };
@@ -1,11 +1,35 @@
1
1
  //#region src/cli-args.d.ts
2
- /** Shared CLI argument parsing helpers */
3
- declare const args: string[];
4
2
  declare function getArg(name: string, fallback: string): string;
5
3
  declare function getArg(name: string): string | undefined;
4
+ /**
5
+ * Numeric flags, validated. Callers used to write `parseInt(getArg(n, d), 10)`,
6
+ * which is where a bad value became `NaN` — far from the flag that caused it.
7
+ */
8
+ declare function getIntArg(name: string, fallback: number, options?: {
9
+ min?: number;
10
+ max?: number;
11
+ }): number;
12
+ declare function getFloatArg(name: string, fallback: number, options?: {
13
+ min?: number;
14
+ max?: number;
15
+ }): number;
6
16
  declare function hasFlag(name: string): boolean;
7
17
  declare function getArgValues(name: string): string[];
8
- /** Get positional args (not flags or flag values) */
9
- declare function getPositionalArgs(): string[];
18
+ /**
19
+ * Positional arguments.
20
+ *
21
+ * `valueFlags` names the flags that consume the next argument — required,
22
+ * because argv alone cannot tell `--limit 30` from `--md model-name`. The old
23
+ * implementation assumed *every* flag takes a value, which silently dropped a
24
+ * positional that happened to follow a boolean flag.
25
+ */
26
+ declare function getPositionalArgs(valueFlags?: readonly string[]): string[];
27
+ /** Raw argv tail, for callers doing their own scanning. */
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[];
10
34
  //#endregion
11
- export { args, getArg, getArgValues, getPositionalArgs, hasFlag };
35
+ export { args, getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
package/dist/cli-args.mjs CHANGED
@@ -1,21 +1,63 @@
1
+ import { hasFlag as hasFlag$1, readAll, readFlag, readNumber, readPositionals } from "./arg-reader.mjs";
1
2
  //#region src/cli-args.ts
2
- /** Shared CLI argument parsing helpers */
3
- const args = process.argv.slice(2);
3
+ /**
4
+ * Shared CLI argument helpers, kept as the ergonomic `process.argv`-bound
5
+ * facade over `arg-reader.ts`.
6
+ *
7
+ * This used to be a standalone implementation, and it silently produced wrong
8
+ * values. `getArg("seed", fallback)` returned whatever followed the flag, so
9
+ * `fix-loop --seed --mode selector` yielded `"--mode"`, and the caller's
10
+ * `parseInt` turned that into a `NaN` seed with no complaint. Every reader here
11
+ * now delegates to `arg-reader`, which treats a flag-shaped value and a
12
+ * non-numeric number as errors.
13
+ *
14
+ * `argv()` is read per call rather than captured at import time, so a leaf
15
+ * reached through the CLI dispatcher — which rewrites `process.argv` before
16
+ * loading the leaf — sees the arguments it was actually given.
17
+ */
18
+ const argv = () => process.argv.slice(2);
4
19
  function getArg(name, fallback) {
5
- const idx = args.indexOf(`--${name}`);
6
- return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
20
+ const value = readFlag(argv(), name);
21
+ return value === void 0 || value === "" ? fallback : value;
22
+ }
23
+ /**
24
+ * Numeric flags, validated. Callers used to write `parseInt(getArg(n, d), 10)`,
25
+ * which is where a bad value became `NaN` — far from the flag that caused it.
26
+ */
27
+ function getIntArg(name, fallback, options = {}) {
28
+ return readNumber(argv(), name, {
29
+ ...options,
30
+ integer: true
31
+ }) ?? fallback;
32
+ }
33
+ function getFloatArg(name, fallback, options = {}) {
34
+ return readNumber(argv(), name, options) ?? fallback;
7
35
  }
8
36
  function hasFlag(name) {
9
- return args.includes(`--${name}`);
37
+ return hasFlag$1(argv(), name);
10
38
  }
11
39
  function getArgValues(name) {
12
- const values = [];
13
- for (let i = 0; i < args.length; i++) if (args[i] === `--${name}` && args[i + 1]) values.push(args[i + 1]);
14
- return values;
40
+ return readAll(argv(), name);
41
+ }
42
+ /**
43
+ * Positional arguments.
44
+ *
45
+ * `valueFlags` names the flags that consume the next argument — required,
46
+ * because argv alone cannot tell `--limit 30` from `--md model-name`. The old
47
+ * implementation assumed *every* flag takes a value, which silently dropped a
48
+ * positional that happened to follow a boolean flag.
49
+ */
50
+ function getPositionalArgs(valueFlags = []) {
51
+ return readPositionals(argv(), valueFlags);
15
52
  }
16
- /** Get positional args (not flags or flag values) */
17
- function getPositionalArgs() {
18
- return args.filter((a, i) => !a.startsWith("--") && (i === 0 || !args[i - 1]?.startsWith("--")));
53
+ /** Raw argv tail, for callers doing their own scanning. */
54
+ function getRawArgs() {
55
+ return argv();
19
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();
20
62
  //#endregion
21
- export { args, getArg, getArgValues, getPositionalArgs, hasFlag };
63
+ export { args, getArg, getArgValues, getFloatArg, getIntArg, getPositionalArgs, getRawArgs, hasFlag };
@@ -1,4 +1,12 @@
1
1
  //#region src/cli-error.d.ts
2
+ /**
3
+ * A bad flag or missing argument — the caller's typo, not a defect. Thrown by
4
+ * `arg-reader` and printed as one line, because a stack trace for
5
+ * `--concurrency abc` buries the one sentence that fixes it.
6
+ */
7
+ declare class UsageError extends Error {
8
+ readonly name = "UsageError";
9
+ }
2
10
  declare function handleCliError(e: unknown): never;
3
11
  //#endregion
4
- export { handleCliError };
12
+ export { UsageError, handleCliError };
@@ -2,16 +2,28 @@ import { statSync } from "node:fs";
2
2
  //#region src/cli-error.ts
3
3
  /**
4
4
  * Shared CLI error-prettifier. Recognizes common error shapes that
5
- * make `vrt` look user-hostile (ENOENT stack traces, Playwright
5
+ * make `vlmkit` look user-hostile (ENOENT stack traces, Playwright
6
6
  * navigation errors with absolute source paths) and rewrites them
7
7
  * to a one-line message.
8
8
  *
9
9
  * Use:
10
10
  * main().catch(handleCliError);
11
11
  */
12
+ /**
13
+ * A bad flag or missing argument — the caller's typo, not a defect. Thrown by
14
+ * `arg-reader` and printed as one line, because a stack trace for
15
+ * `--concurrency abc` buries the one sentence that fixes it.
16
+ */
17
+ var UsageError = class extends Error {
18
+ name = "UsageError";
19
+ };
12
20
  function handleCliError(e) {
13
21
  const err = e;
14
22
  const msg = String(err?.message ?? e);
23
+ if (err?.name === "UsageError") {
24
+ process.stderr.write(`error: ${msg}\n`);
25
+ process.exit(1);
26
+ }
15
27
  if (err?.code === "ENOENT") {
16
28
  const path = err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?";
17
29
  process.stderr.write(`error: file not found: ${path}\n`);
@@ -44,7 +56,7 @@ function handleCliError(e) {
44
56
  * EISDIR fallback: Node's `fsPromises.readFile` doesn't attach `.path`
45
57
  * to the error, and the message string doesn't include the path
46
58
  * either. Scan argv for the first positional that exists as a
47
- * directory — close enough since most vrt subcommands take exactly
59
+ * directory — close enough since most vlmkit subcommands take exactly
48
60
  * one path argument and the failure happens during the initial read.
49
61
  */
50
62
  function findDirectoryArg() {
@@ -56,4 +68,4 @@ function findDirectoryArg() {
56
68
  }
57
69
  }
58
70
  //#endregion
59
- export { handleCliError };
71
+ export { UsageError, handleCliError };
@@ -2,8 +2,8 @@
2
2
  import { compareScreenshots } from "./heatmap.mjs";
3
3
  import { applyMask, parseMaskSelectors } from "./mask.mjs";
4
4
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "./terminal-colors.mjs";
5
- import { mkdir, readFile, writeFile } from "node:fs/promises";
6
5
  import { join, resolve } from "node:path";
6
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
7
7
  import { chromium } from "playwright";
8
8
  //#region src/element-compare.ts
9
9
  /**
@@ -13,9 +13,9 @@ import { chromium } from "playwright";
13
13
  * compares individual DOM elements independently via locator.screenshot().
14
14
  *
15
15
  * Usage:
16
- * vrt elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
16
+ * vlmkit diff elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
17
17
  * --selectors "header,main,footer"
18
- * vrt elements before.html after.html --selectors "header,.content,.sidebar"
18
+ * vlmkit diff elements before.html after.html --selectors "header,.content,.sidebar"
19
19
  */
20
20
  async function captureElementScreenshot(page, selector, outputPath) {
21
21
  const locator = page.locator(selector).first();
@@ -194,12 +194,12 @@ function parseArgs(args) {
194
194
  function formatUsage() {
195
195
  return [
196
196
  "Usage:",
197
- " vrt diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
198
- " vrt diff component before.html after.html --selectors \"header,.content\"",
197
+ " vlmkit diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
198
+ " vlmkit diff component before.html after.html --selectors \"header,.content\"",
199
199
  "",
200
200
  "Aliases:",
201
- " vrt diff elements",
202
- " vrt elements",
201
+ " vlmkit diff elements",
202
+ " vlmkit diff elements",
203
203
  "",
204
204
  "Options:",
205
205
  " --selectors <sel1,sel2,...> CSS selectors to compare (required)",
@@ -0,0 +1,116 @@
1
+ //#region src/gate-config.d.ts
2
+ /**
3
+ * `vlmkit.gates.json` — one reviewed file that says which gates run on which
4
+ * pages, and holds every suppression with a reason attached.
5
+ *
6
+ * Why this exists: the documented convention was npm scripts, one line per
7
+ * page. Three separate reviewers landed on the same complaint — the scripts
8
+ * stop scaling around twenty pages, and once a `--allow-invisible` or an
9
+ * integrity exemption is inlined in a script, the only way to audit what has
10
+ * been silenced repo-wide is `grep`. A suppression nobody can enumerate is a
11
+ * suppression nobody revisits.
12
+ *
13
+ * Two decisions make the file worth reviewing rather than just worth having:
14
+ *
15
+ * 1. **A suppression must carry a reason.** Parsing fails without one. The
16
+ * flag alone records what was silenced but not why, which is exactly the
17
+ * state that makes a reviewer approve it again a year later.
18
+ * 2. **An expired suppression is dropped, not applied.** It is reported
19
+ * loudly and the gate goes back to failing. An expiry date that keeps
20
+ * working after it passes is a comment, not a deadline.
21
+ */
22
+ interface GateSuppression {
23
+ /**
24
+ * Gate this applies to, as a prefix of the gate command: `check copy`
25
+ * matches `check copy --manifest x.txt`.
26
+ */
27
+ gate: string;
28
+ /** Flag(s) appended to that gate's invocation, e.g. `--allow-invisible visually-hidden`. */
29
+ flag: string;
30
+ /** Why this is acceptable. Required — an unexplained suppression is unauditable. */
31
+ reason: string;
32
+ /** Who signed off. Optional but reported, so an unowned entry is visible. */
33
+ owner?: string;
34
+ /** `YYYY-MM-DD`. Omitted means permanent, which the inventory counts separately. */
35
+ expires?: string;
36
+ }
37
+ interface GatePage {
38
+ /** Short stable name for `--only` and reports. Defaults to the source. */
39
+ id?: string;
40
+ /** File path, glob, or URL handed to each gate. */
41
+ source: string;
42
+ /** Gate commands for this page. Falls back to `defaults.gates`. */
43
+ gates?: string[];
44
+ /** Extra gates for this page on top of the defaults. */
45
+ extraGates?: string[];
46
+ suppressions?: GateSuppression[];
47
+ }
48
+ interface GateConfig {
49
+ defaults?: {
50
+ gates?: string[];
51
+ suppressions?: GateSuppression[];
52
+ };
53
+ pages: GatePage[];
54
+ }
55
+ interface ResolvedSuppression extends GateSuppression {
56
+ /** Page id this came from, or `defaults`. */
57
+ scope: string;
58
+ status: "active" | "expired" | "permanent";
59
+ /** Days until expiry; negative when overdue, null when permanent. */
60
+ daysLeft: number | null;
61
+ }
62
+ interface GateJob {
63
+ pageId: string;
64
+ source: string;
65
+ /** Gate command with any active suppression flags already appended. */
66
+ gate: string;
67
+ /** The gate as written in the config, before suppression flags. */
68
+ baseGate: string;
69
+ appliedSuppressions: ResolvedSuppression[];
70
+ }
71
+ interface GatePlan {
72
+ jobs: GateJob[];
73
+ /** Every suppression the config declares, resolved against `now`. */
74
+ suppressions: ResolvedSuppression[];
75
+ /**
76
+ * Suppressions past their expiry. Their flags are NOT applied — the gate
77
+ * fails again — and callers are expected to print these before running.
78
+ */
79
+ expired: ResolvedSuppression[];
80
+ }
81
+ declare const GATE_CONFIG_FILENAMES: string[];
82
+ /** Parse and validate. Every error names the JSON path so the fix is obvious. */
83
+ declare function parseGateConfig(raw: string): GateConfig;
84
+ declare function resolveSuppression(s: GateSuppression, scope: string, now: Date): ResolvedSuppression;
85
+ interface ResolveOptions {
86
+ now?: Date;
87
+ /** Page ids or sources to keep. Substring match, so `admin` selects a subtree. */
88
+ only?: string[];
89
+ }
90
+ /**
91
+ * Turn the config into the exact list of gate invocations to run.
92
+ *
93
+ * Suppression flags are appended to matching gates only when active. An
94
+ * expired one is surfaced in `plan.expired` and deliberately left off the
95
+ * command line: the gate returns to failing, which is what an expiry date is
96
+ * supposed to mean.
97
+ */
98
+ declare function resolveGatePlan(config: GateConfig, options?: ResolveOptions): GatePlan;
99
+ /**
100
+ * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
101
+ * but not `check copyright`, and `check` matches every check gate.
102
+ */
103
+ declare function gateMatches(gate: string, pattern: string): boolean;
104
+ interface SuppressionSummary {
105
+ rows: ResolvedSuppression[];
106
+ active: number;
107
+ expired: number;
108
+ permanent: number;
109
+ /** Active entries with no owner — visible rather than tolerated silently. */
110
+ unowned: number;
111
+ /** Active entries expiring within `soonDays`. */
112
+ expiringSoon: number;
113
+ }
114
+ declare function summarizeSuppressions(suppressions: ResolvedSuppression[], soonDays?: number): SuppressionSummary;
115
+ //#endregion
116
+ export { GATE_CONFIG_FILENAMES, GateConfig, GateJob, GatePage, GatePlan, GateSuppression, ResolveOptions, ResolvedSuppression, SuppressionSummary, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };