@mizchi/vlmkit-core 0.8.0 → 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.
Files changed (81) hide show
  1. package/README.md +1 -1
  2. package/dist/a11y-semantic.d.mts +34 -0
  3. package/dist/a11y-semantic.mjs +261 -0
  4. package/dist/arg-reader.d.mts +52 -0
  5. package/dist/arg-reader.mjs +129 -0
  6. package/dist/auth-state.d.mts +30 -0
  7. package/dist/auth-state.mjs +82 -0
  8. package/dist/authored-style-capture.d.mts +42 -0
  9. package/dist/authored-style-capture.mjs +117 -0
  10. package/dist/authored-style-diff.d.mts +15 -0
  11. package/dist/authored-style-diff.mjs +16 -0
  12. package/dist/cli-args.d.mts +35 -0
  13. package/dist/cli-args.mjs +63 -0
  14. package/dist/cli-error.d.mts +12 -0
  15. package/dist/cli-error.mjs +71 -0
  16. package/dist/computed-style-capture.d.mts +41 -0
  17. package/dist/computed-style-capture.mjs +589 -0
  18. package/dist/computed-style-diff.d.mts +83 -0
  19. package/dist/computed-style-diff.mjs +123 -0
  20. package/dist/diff-regions.d.mts +8 -0
  21. package/dist/diff-regions.mjs +52 -0
  22. package/dist/dom-equivalence.d.mts +51 -0
  23. package/dist/dom-equivalence.mjs +91 -0
  24. package/dist/dom-position-styles.d.mts +166 -0
  25. package/dist/dom-position-styles.mjs +296 -0
  26. package/dist/element-compare.d.mts +71 -0
  27. package/dist/element-compare.mjs +269 -0
  28. package/dist/gate-config.d.mts +116 -0
  29. package/dist/gate-config.mjs +169 -0
  30. package/dist/gate-exit.d.mts +45 -0
  31. package/dist/gate-exit.mjs +25 -0
  32. package/dist/heatmap-regions.d.mts +57 -0
  33. package/dist/heatmap-regions.mjs +158 -0
  34. package/dist/heatmap.d.mts +86 -0
  35. package/dist/heatmap.mjs +510 -0
  36. package/dist/image-resize.d.mts +34 -0
  37. package/dist/image-resize.mjs +92 -0
  38. package/dist/index.d.mts +15 -0
  39. package/dist/index.mjs +14 -0
  40. package/dist/legacy-names.d.mts +48 -0
  41. package/dist/legacy-names.mjs +134 -0
  42. package/dist/mask.d.mts +18 -0
  43. package/dist/mask.mjs +27 -0
  44. package/dist/navigation-redirect.d.mts +28 -0
  45. package/dist/navigation-redirect.mjs +47 -0
  46. package/dist/page-open.d.mts +102 -0
  47. package/dist/page-open.mjs +133 -0
  48. package/dist/png-utils.d.mts +30 -0
  49. package/dist/png-utils.mjs +80 -0
  50. package/dist/region-shift.d.mts +20 -0
  51. package/dist/region-shift.mjs +128 -0
  52. package/dist/run-ledger.d.mts +14 -0
  53. package/dist/run-ledger.mjs +31 -0
  54. package/dist/terminal-colors.d.mts +12 -0
  55. package/dist/terminal-colors.mjs +14 -0
  56. package/dist/text-rows.d.mts +121 -0
  57. package/dist/text-rows.mjs +246 -0
  58. package/{src/types.ts → dist/types.d.mts} +88 -206
  59. package/dist/types.mjs +1 -0
  60. package/package.json +17 -5
  61. package/src/a11y-semantic.ts +0 -384
  62. package/src/authored-style-capture.ts +0 -185
  63. package/src/authored-style-diff.ts +0 -32
  64. package/src/cli-args.ts +0 -29
  65. package/src/cli-error.ts +0 -85
  66. package/src/computed-style-capture.ts +0 -717
  67. package/src/computed-style-diff.ts +0 -192
  68. package/src/diff-regions.ts +0 -70
  69. package/src/dom-equivalence.ts +0 -158
  70. package/src/dom-position-styles.ts +0 -457
  71. package/src/element-compare.ts +0 -354
  72. package/src/heatmap-regions.ts +0 -245
  73. package/src/heatmap.ts +0 -670
  74. package/src/image-resize.ts +0 -112
  75. package/src/index.ts +0 -105
  76. package/src/mask.ts +0 -41
  77. package/src/png-utils.ts +0 -86
  78. package/src/region-shift.ts +0 -173
  79. package/src/run-ledger.ts +0 -39
  80. package/src/terminal-colors.ts +0 -13
  81. package/src/text-rows.ts +0 -412
@@ -0,0 +1,48 @@
1
+ //#region src/legacy-names.d.ts
2
+ declare const STATE_DIR = ".vlmkit";
3
+ declare const LEGACY_STATE_DIR = ".vrt";
4
+ declare const CONFIG_FILE = "vlmkit.config.json";
5
+ declare const LEGACY_CONFIG_FILE = "vrt.config.json";
6
+ declare function noteLegacyName(oldName: string, newName: string, detail?: string): void;
7
+ /** Reset between tests. */
8
+ declare function resetLegacyNotices(): void;
9
+ /**
10
+ * Absolute path for a state entry, preferring `.vlmkit/<entry>` and falling back
11
+ * to an existing `.vrt/<entry>`.
12
+ *
13
+ * Writers get the new path unless the old one is already populated, so a
14
+ * project keeps appending where its history is instead of starting a second,
15
+ * half-empty baseline set beside it.
16
+ */
17
+ declare function resolveStatePath(cwd: string, entry: string): string;
18
+ /**
19
+ * Config filenames in search order: new before old, JSON before TOML (JSON wins
20
+ * when both exist, which was the pre-rename behaviour). `legacy: true` entries
21
+ * are what `findConfigPath` reports a notice for.
22
+ *
23
+ * Exported as data rather than a resolver because the caller also has to name
24
+ * every candidate in its "not found" error — listing only the new one would
25
+ * tell a project with a working `vrt.config.json` that it has no config.
26
+ */
27
+ declare const CONFIG_CANDIDATES: readonly {
28
+ name: string;
29
+ legacy: boolean;
30
+ }[];
31
+ /**
32
+ * `VLMKIT_FOO`, falling back to `VRT_FOO`.
33
+ *
34
+ * Pass the suffix, not the whole name, so a call site cannot mismatch the two
35
+ * halves — `readEnv("LLM_MODEL")` reads `VLMKIT_LLM_MODEL` then `VRT_LLM_MODEL`.
36
+ * An empty string counts as unset, matching how the previous `process.env.X ||`
37
+ * reads behaved.
38
+ */
39
+ declare function readEnv(suffix: string): string | undefined;
40
+ /**
41
+ * `DEBUG_VLMKIT`, falling back to `DEBUG_VRT`. Separate from `readEnv` because
42
+ * this one is a prefix, not a suffix — `DEBUG_VRT`, not `VRT_DEBUG`.
43
+ */
44
+ declare function debugEnabled(): boolean;
45
+ /** Every env suffix that has both spellings, so the docs and tests can enumerate. */
46
+ declare const ENV_SUFFIXES: readonly ["BASE_URL", "CAPTURE_BACKEND", "CONFIG_FILE", "CONFIG_PATH", "LLM_MODEL", "LLM_PROVIDER", "PROJECT_ROOT", "VLM_MODEL"];
47
+ //#endregion
48
+ export { CONFIG_CANDIDATES, CONFIG_FILE, ENV_SUFFIXES, LEGACY_CONFIG_FILE, LEGACY_STATE_DIR, STATE_DIR, debugEnabled, noteLegacyName, readEnv, resetLegacyNotices, resolveStatePath };
@@ -0,0 +1,134 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ //#region src/legacy-names.ts
4
+ /**
5
+ * Backward compatibility for the `vrt` → `vlmkit` rename of things that are not
6
+ * text: the state directory, the config filename, and the environment
7
+ * variables.
8
+ *
9
+ * The command-name rename was pure text — nothing on disk moved. These three
10
+ * are different: rename them without a fallback and every existing project
11
+ * silently loses its approved baselines, stops finding its config, and drops
12
+ * whatever its CI exports. So each new name is preferred, each old name still
13
+ * works, and using an old one prints one line saying so.
14
+ *
15
+ * ## Why per-subpath and not per-directory
16
+ *
17
+ * `.vlmkit/` already exists in any project that has run a gate — the run
18
+ * ledger, `gates`, `markup-loop` and `copy-review` all live there, while
19
+ * `baselines`, `runs` and `last-diff-for-agent.json` were still under `.vrt/`.
20
+ * So "if `.vlmkit/` is missing, use `.vrt/`" would resolve to the new directory
21
+ * immediately and lose the baselines anyway. The check has to be on the
22
+ * specific entry: `.vlmkit/baselines` vs `.vrt/baselines`.
23
+ *
24
+ * ## What is deliberately NOT here
25
+ *
26
+ * Values that leave this process or land in someone else's file — the
27
+ * `X-Title` header sent to OpenRouter, the Playwright `projectName` that
28
+ * appears inside snapshot paths, the plan schema's `vrt?:` field, the published
29
+ * OpenAPI title. Those are wire and data formats, not local state, and moving
30
+ * them is a separate decision.
31
+ */
32
+ const STATE_DIR = ".vlmkit";
33
+ const LEGACY_STATE_DIR = ".vrt";
34
+ const CONFIG_FILE = "vlmkit.config.json";
35
+ const LEGACY_CONFIG_FILE = "vrt.config.json";
36
+ /** One notice per distinct old name per process — a loop must not spam. */
37
+ const announced = /* @__PURE__ */ new Set();
38
+ function noteLegacyName(oldName, newName, detail = "") {
39
+ if (announced.has(oldName)) return;
40
+ announced.add(oldName);
41
+ const tag = !process.env.NO_COLOR && process.stderr.isTTY ? "\x1B[33m[vlmkit legacy]\x1B[0m" : "[vlmkit legacy]";
42
+ process.stderr.write(`${tag} using ${oldName} — rename to ${newName}; support ends in 1.0.0${detail ? `. ${detail}` : ""}\n`);
43
+ }
44
+ /** Reset between tests. */
45
+ function resetLegacyNotices() {
46
+ announced.clear();
47
+ }
48
+ /**
49
+ * Absolute path for a state entry, preferring `.vlmkit/<entry>` and falling back
50
+ * to an existing `.vrt/<entry>`.
51
+ *
52
+ * Writers get the new path unless the old one is already populated, so a
53
+ * project keeps appending where its history is instead of starting a second,
54
+ * half-empty baseline set beside it.
55
+ */
56
+ function resolveStatePath(cwd, entry) {
57
+ const next = resolve(cwd, join(STATE_DIR, entry));
58
+ if (existsSync(next)) return next;
59
+ const legacy = resolve(cwd, join(LEGACY_STATE_DIR, entry));
60
+ if (existsSync(legacy)) {
61
+ noteLegacyName(`${LEGACY_STATE_DIR}/${entry}`, `${STATE_DIR}/${entry}`, "move it to keep using one location");
62
+ return legacy;
63
+ }
64
+ return next;
65
+ }
66
+ /**
67
+ * Config filenames in search order: new before old, JSON before TOML (JSON wins
68
+ * when both exist, which was the pre-rename behaviour). `legacy: true` entries
69
+ * are what `findConfigPath` reports a notice for.
70
+ *
71
+ * Exported as data rather than a resolver because the caller also has to name
72
+ * every candidate in its "not found" error — listing only the new one would
73
+ * tell a project with a working `vrt.config.json` that it has no config.
74
+ */
75
+ const CONFIG_CANDIDATES = [
76
+ {
77
+ name: CONFIG_FILE,
78
+ legacy: false
79
+ },
80
+ {
81
+ name: "vlmkit.config.toml",
82
+ legacy: false
83
+ },
84
+ {
85
+ name: LEGACY_CONFIG_FILE,
86
+ legacy: true
87
+ },
88
+ {
89
+ name: "vrt.config.toml",
90
+ legacy: true
91
+ }
92
+ ];
93
+ /**
94
+ * `VLMKIT_FOO`, falling back to `VRT_FOO`.
95
+ *
96
+ * Pass the suffix, not the whole name, so a call site cannot mismatch the two
97
+ * halves — `readEnv("LLM_MODEL")` reads `VLMKIT_LLM_MODEL` then `VRT_LLM_MODEL`.
98
+ * An empty string counts as unset, matching how the previous `process.env.X ||`
99
+ * reads behaved.
100
+ */
101
+ function readEnv(suffix) {
102
+ const next = process.env[`VLMKIT_${suffix}`];
103
+ if (next) return next;
104
+ const legacy = process.env[`VRT_${suffix}`];
105
+ if (legacy) {
106
+ noteLegacyName(`VRT_${suffix}`, `VLMKIT_${suffix}`);
107
+ return legacy;
108
+ }
109
+ }
110
+ /**
111
+ * `DEBUG_VLMKIT`, falling back to `DEBUG_VRT`. Separate from `readEnv` because
112
+ * this one is a prefix, not a suffix — `DEBUG_VRT`, not `VRT_DEBUG`.
113
+ */
114
+ function debugEnabled() {
115
+ if (process.env.DEBUG_VLMKIT) return true;
116
+ if (process.env.DEBUG_VRT) {
117
+ noteLegacyName("DEBUG_VRT", "DEBUG_VLMKIT");
118
+ return true;
119
+ }
120
+ return false;
121
+ }
122
+ /** Every env suffix that has both spellings, so the docs and tests can enumerate. */
123
+ const ENV_SUFFIXES = [
124
+ "BASE_URL",
125
+ "CAPTURE_BACKEND",
126
+ "CONFIG_FILE",
127
+ "CONFIG_PATH",
128
+ "LLM_MODEL",
129
+ "LLM_PROVIDER",
130
+ "PROJECT_ROOT",
131
+ "VLM_MODEL"
132
+ ];
133
+ //#endregion
134
+ export { CONFIG_CANDIDATES, CONFIG_FILE, ENV_SUFFIXES, LEGACY_CONFIG_FILE, LEGACY_STATE_DIR, STATE_DIR, debugEnabled, noteLegacyName, readEnv, resetLegacyNotices, resolveStatePath };
@@ -0,0 +1,18 @@
1
+ import { Page } from "playwright";
2
+
3
+ //#region src/mask.d.ts
4
+ /**
5
+ * Inject mask styles into the page.
6
+ * Sets visibility: hidden on target selectors including descendants.
7
+ */
8
+ declare function applyMask(page: Page, selectors: string[]): Promise<void>;
9
+ /**
10
+ * Parse selector array from CLI --mask flags.
11
+ * Supports comma-separated or multiple --mask flags.
12
+ *
13
+ * --mask ".stars,.carousel"
14
+ * --mask ".stars" --mask ".carousel"
15
+ */
16
+ declare function parseMaskSelectors(args: string[]): string[];
17
+ //#endregion
18
+ export { applyMask, parseMaskSelectors };
package/dist/mask.mjs ADDED
@@ -0,0 +1,27 @@
1
+ //#region src/mask.ts
2
+ /**
3
+ * Inject mask styles into the page.
4
+ * Sets visibility: hidden on target selectors including descendants.
5
+ */
6
+ async function applyMask(page, selectors) {
7
+ if (selectors.length === 0) return;
8
+ const css = selectors.map((s) => `${s} { visibility: hidden !important; }`).join("\n");
9
+ await page.addStyleTag({ content: css });
10
+ }
11
+ /**
12
+ * Parse selector array from CLI --mask flags.
13
+ * Supports comma-separated or multiple --mask flags.
14
+ *
15
+ * --mask ".stars,.carousel"
16
+ * --mask ".stars" --mask ".carousel"
17
+ */
18
+ function parseMaskSelectors(args) {
19
+ const selectors = [];
20
+ for (let i = 0; i < args.length; i++) if (args[i] === "--mask" && args[i + 1]) for (const s of args[i + 1].split(",")) {
21
+ const trimmed = s.trim();
22
+ if (trimmed) selectors.push(trimmed);
23
+ }
24
+ return selectors;
25
+ }
26
+ //#endregion
27
+ export { applyMask, parseMaskSelectors };
@@ -0,0 +1,28 @@
1
+ //#region src/navigation-redirect.d.ts
2
+ /**
3
+ * Redirect disclosure for gates that navigate.
4
+ *
5
+ * Discovered by the 2026-08-01 hard-target audit: pointing a gate at an
6
+ * auth-walled route (`/dashboard` behind a session cookie) silently
7
+ * followed the 302 to `/login` and measured THAT page. `check integrity`
8
+ * reported `verdict: CLEAN` — a green gate on a page that never rendered,
9
+ * which is worse than an error, and `check copy` reported the dashboard's
10
+ * copy as "missing" when the real problem was that it was never visited.
11
+ *
12
+ * A gate must never report on a URL it did not measure. This helper
13
+ * compares requested vs. final URL and returns a message when they differ
14
+ * in a way the caller should hear about.
15
+ *
16
+ * Deliberately quiet about cosmetic redirects — scheme upgrade, added or
17
+ * dropped trailing slash, host canonicalization (www.) — because those
18
+ * still land on the intended page and crying wolf about them would train
19
+ * users to ignore the warning.
20
+ */
21
+ /**
22
+ * Returns a human-readable warning when the final URL is a different page
23
+ * than the one requested, or `null` when the navigation landed where the
24
+ * caller intended (or when either URL is unparseable / not http(s)).
25
+ */
26
+ declare function describeRedirect(requested: string, final: string): string | null;
27
+ //#endregion
28
+ export { describeRedirect };
@@ -0,0 +1,47 @@
1
+ //#region src/navigation-redirect.ts
2
+ /**
3
+ * Redirect disclosure for gates that navigate.
4
+ *
5
+ * Discovered by the 2026-08-01 hard-target audit: pointing a gate at an
6
+ * auth-walled route (`/dashboard` behind a session cookie) silently
7
+ * followed the 302 to `/login` and measured THAT page. `check integrity`
8
+ * reported `verdict: CLEAN` — a green gate on a page that never rendered,
9
+ * which is worse than an error, and `check copy` reported the dashboard's
10
+ * copy as "missing" when the real problem was that it was never visited.
11
+ *
12
+ * A gate must never report on a URL it did not measure. This helper
13
+ * compares requested vs. final URL and returns a message when they differ
14
+ * in a way the caller should hear about.
15
+ *
16
+ * Deliberately quiet about cosmetic redirects — scheme upgrade, added or
17
+ * dropped trailing slash, host canonicalization (www.) — because those
18
+ * still land on the intended page and crying wolf about them would train
19
+ * users to ignore the warning.
20
+ */
21
+ function normalizePath(pathname) {
22
+ const p = pathname.replace(/\/+$/, "");
23
+ return p === "" ? "/" : p;
24
+ }
25
+ /**
26
+ * Returns a human-readable warning when the final URL is a different page
27
+ * than the one requested, or `null` when the navigation landed where the
28
+ * caller intended (or when either URL is unparseable / not http(s)).
29
+ */
30
+ function describeRedirect(requested, final) {
31
+ if (!requested || !final || requested === final) return null;
32
+ let a, b;
33
+ try {
34
+ a = new URL(requested);
35
+ b = new URL(final);
36
+ } catch {
37
+ return null;
38
+ }
39
+ if (a.protocol !== "http:" && a.protocol !== "https:") return null;
40
+ const hostA = a.hostname.replace(/^www\./, "");
41
+ const hostB = b.hostname.replace(/^www\./, "");
42
+ if (normalizePath(a.pathname) === normalizePath(b.pathname) && hostA === hostB) return null;
43
+ const hint = /login|signin|sign-in|auth|sso|account\/login/i.test(b.pathname) ? " This looks like a login wall: the gate measured the sign-in page, NOT the page you asked about. Pass a logged-in Playwright storage state (--storage-state <file>, or VLMKIT_STORAGE_STATE), or point the gate at a route that does not need auth." : " The gate measured the destination, not the URL you passed.";
44
+ return `redirected: requested ${a.pathname}${a.search} but measured ${b.href}.${hint}`;
45
+ }
46
+ //#endregion
47
+ export { describeRedirect };
@@ -0,0 +1,102 @@
1
+ import { Browser, Page, ViewportSize } from "playwright";
2
+
3
+ //#region src/page-open.d.ts
4
+ declare const isUrlSource: (source: string) => boolean;
5
+ /**
6
+ * Normalize a source for storage and display: an absolute path for a file, the
7
+ * URL untouched for a URL.
8
+ *
9
+ * `resolve()` alone mangles a URL into a path — `resolve("http://x/p.html")`
10
+ * yields `<cwd>/http:/x/p.html`, which then fails as "file not found" and tells
11
+ * the caller nothing about what actually went wrong.
12
+ */
13
+ declare function resolveSource(source: string): string;
14
+ /** File path or URL → a URL Playwright can navigate to. */
15
+ declare function sourceToUrl(source: string): string;
16
+ /**
17
+ * Wait for the page to stop moving: bounded network idle, then webfonts, then
18
+ * one frame. Every part is best-effort — a page with a long-poll connection
19
+ * never reaches network idle, and refusing to measure it would be worse than
20
+ * measuring it slightly early.
21
+ *
22
+ * **A gate that navigates and does not call this measures the wrong document.**
23
+ * `load` fires before a client-rendered view paints, and the failure is never
24
+ * reported as "I looked too early" — it is reported as a defect in the page:
25
+ *
26
+ * - 2026-08-01: `check interactions` said "interactive elements: 0" on a React
27
+ * page with a button, two links and a scroller. It measured the "Loading…"
28
+ * placeholder.
29
+ * - 2026-08-02: `verify flow` failed `count .card expected 2, measured 0` on a
30
+ * page where `check layout` measured 2 at the same instant, and
31
+ * `build page` screenshotted a candidate at 5.3% of its settled ink — so
32
+ * every component came back missing. Both blamed the markup.
33
+ *
34
+ * Playwright *actions* auto-wait, which is why this stayed hidden: a click on a
35
+ * late-rendered element is safe. Reads are not — `page.evaluate`,
36
+ * `page.screenshot` and `getBoundingClientRect` all sample the DOM at that
37
+ * instant.
38
+ *
39
+ * `waitUntil` is not the axis. `goto(load)` followed by this settle waits for
40
+ * network idle anyway, so the 8 `load` and 2 `domcontentloaded` call sites are
41
+ * equivalent to the 71 `networkidle` ones **provided they settle**. The
42
+ * difference that mattered was always the settle, never the load state.
43
+ */
44
+ declare function settlePage(page: Page, settleMs?: number): Promise<void>;
45
+ interface OpenPageOptions {
46
+ viewport?: ViewportSize;
47
+ deviceScaleFactor?: number;
48
+ /** `prefers-color-scheme` for the page's context (theme-parity opens both). */
49
+ colorScheme?: "light" | "dark" | "no-preference";
50
+ /** Playwright storage state for pages behind a login. */
51
+ storageState?: string;
52
+ waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
53
+ timeout?: number;
54
+ /** Extra quiet time after load. 0 skips it. */
55
+ settleMs?: number;
56
+ /** Skip settling entirely (a gate that measures load timing does its own). */
57
+ skipSettle?: boolean;
58
+ }
59
+ interface OpenedPage {
60
+ page: Page;
61
+ /**
62
+ * Human-readable note when a URL redirected somewhere meaningful (a login
63
+ * wall), else null. Gates surface this so an auth-walled route cannot come
64
+ * back CLEAN by measuring the login page.
65
+ */
66
+ redirect: string | null;
67
+ }
68
+ /**
69
+ * Open a file or URL by navigation, so relative assets resolve.
70
+ */
71
+ declare function openSource(browser: Browser, source: string, options?: OpenPageOptions): Promise<OpenedPage>;
72
+ interface OpenHtmlOptions extends OpenPageOptions {
73
+ /**
74
+ * The file or URL this HTML came from. The page navigates there first, so the
75
+ * document keeps that base URL and the mutated copy still resolves the
76
+ * stylesheets and images sitting next to the original.
77
+ *
78
+ * Omit only for HTML synthesized from nothing.
79
+ */
80
+ baseSource?: string;
81
+ }
82
+ /**
83
+ * Open HTML a gate has rewritten in memory (inflated text, forced theme,
84
+ * deleted rule).
85
+ *
86
+ * Prefer `openSource` when the bytes on disk are what should be measured.
87
+ *
88
+ * Navigate-then-replace, because the obvious alternative does not work.
89
+ * Measured on the same one-line fixture (external `style.css` setting
90
+ * `p { color: rgb(4,5,6) }`):
91
+ *
92
+ * setContent + injected `<base href="file:///dir/">` -> rgb(0, 0, 0)
93
+ * goto(file) then setContent -> rgb(4, 5, 6)
94
+ *
95
+ * A `<base>` cannot rescue it: the `setContent` document has an opaque origin,
96
+ * and Chromium blocks a `file://` subresource from one. Navigating first gives
97
+ * the document a real base URL, and `setContent` replaces the markup without
98
+ * discarding it.
99
+ */
100
+ declare function openHtml(browser: Browser, html: string, options?: OpenHtmlOptions): Promise<Page>;
101
+ //#endregion
102
+ export { OpenHtmlOptions, OpenPageOptions, OpenedPage, isUrlSource, openHtml, openSource, resolveSource, settlePage, sourceToUrl };
@@ -0,0 +1,133 @@
1
+ import { withAuthState } from "./auth-state.mjs";
2
+ import { describeRedirect } from "./navigation-redirect.mjs";
3
+ import { resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/page-open.ts
6
+ /**
7
+ * One way to open the page under test.
8
+ *
9
+ * Two mechanisms had grown up side by side, and they do not measure the same
10
+ * document:
11
+ *
12
+ * - `page.goto(pathToFileURL(file))` — the document has an origin, so
13
+ * `<link rel="stylesheet" href="style.css">`, `<img src="hero.png">` and
14
+ * relative scripts all resolve.
15
+ * - `page.setContent(await readFile(file))` — the document's base URL is
16
+ * `about:blank`, so every relative reference silently fails to load.
17
+ *
18
+ * Measured consequence (2026-08-02): a page with `p { color: #bbbbbb }` in an
19
+ * external stylesheet — 1.92:1 on white, a clear WCAG failure — was reported by
20
+ * `check a11y contrast` as **0 failures**, because the gate measured unstyled
21
+ * markup. Inlining the same CSS in a `<style>` block made the same gate report
22
+ * the failure correctly. Ten gates read a user's file and pushed it through
23
+ * `setContent` with no base URL.
24
+ *
25
+ * So: load by navigation whenever the bytes on disk are what we want, and when
26
+ * a gate must mutate the HTML first (inflate text for i18n, force a theme,
27
+ * delete a CSS rule), navigate to the source and *then* replace the markup, so
28
+ * the document keeps a base URL its siblings resolve against.
29
+ */
30
+ const isUrlSource = (source) => /^https?:\/\//.test(source);
31
+ /**
32
+ * Normalize a source for storage and display: an absolute path for a file, the
33
+ * URL untouched for a URL.
34
+ *
35
+ * `resolve()` alone mangles a URL into a path — `resolve("http://x/p.html")`
36
+ * yields `<cwd>/http:/x/p.html`, which then fails as "file not found" and tells
37
+ * the caller nothing about what actually went wrong.
38
+ */
39
+ function resolveSource(source) {
40
+ return isUrlSource(source) ? source : resolve(source);
41
+ }
42
+ /** File path or URL → a URL Playwright can navigate to. */
43
+ function sourceToUrl(source) {
44
+ return isUrlSource(source) ? source : pathToFileURL(resolve(source)).href;
45
+ }
46
+ /**
47
+ * Wait for the page to stop moving: bounded network idle, then webfonts, then
48
+ * one frame. Every part is best-effort — a page with a long-poll connection
49
+ * never reaches network idle, and refusing to measure it would be worse than
50
+ * measuring it slightly early.
51
+ *
52
+ * **A gate that navigates and does not call this measures the wrong document.**
53
+ * `load` fires before a client-rendered view paints, and the failure is never
54
+ * reported as "I looked too early" — it is reported as a defect in the page:
55
+ *
56
+ * - 2026-08-01: `check interactions` said "interactive elements: 0" on a React
57
+ * page with a button, two links and a scroller. It measured the "Loading…"
58
+ * placeholder.
59
+ * - 2026-08-02: `verify flow` failed `count .card expected 2, measured 0` on a
60
+ * page where `check layout` measured 2 at the same instant, and
61
+ * `build page` screenshotted a candidate at 5.3% of its settled ink — so
62
+ * every component came back missing. Both blamed the markup.
63
+ *
64
+ * Playwright *actions* auto-wait, which is why this stayed hidden: a click on a
65
+ * late-rendered element is safe. Reads are not — `page.evaluate`,
66
+ * `page.screenshot` and `getBoundingClientRect` all sample the DOM at that
67
+ * instant.
68
+ *
69
+ * `waitUntil` is not the axis. `goto(load)` followed by this settle waits for
70
+ * network idle anyway, so the 8 `load` and 2 `domcontentloaded` call sites are
71
+ * equivalent to the 71 `networkidle` ones **provided they settle**. The
72
+ * difference that mattered was always the settle, never the load state.
73
+ */
74
+ async function settlePage(page, settleMs = 250) {
75
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {});
76
+ await page.evaluate(() => document.fonts ? document.fonts.ready.then(() => void 0) : void 0).catch(() => {});
77
+ if (settleMs > 0) await page.waitForTimeout(settleMs);
78
+ }
79
+ function pageOptions(options) {
80
+ return withAuthState({
81
+ ...options.viewport ? { viewport: options.viewport } : {},
82
+ ...options.deviceScaleFactor !== void 0 ? { deviceScaleFactor: options.deviceScaleFactor } : {},
83
+ ...options.colorScheme ? { colorScheme: options.colorScheme } : {}
84
+ }, options.storageState);
85
+ }
86
+ /**
87
+ * Open a file or URL by navigation, so relative assets resolve.
88
+ */
89
+ async function openSource(browser, source, options = {}) {
90
+ const page = await browser.newPage(pageOptions(options));
91
+ await page.goto(sourceToUrl(source), {
92
+ waitUntil: options.waitUntil ?? "networkidle",
93
+ timeout: options.timeout ?? 3e4
94
+ });
95
+ if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250);
96
+ return {
97
+ page,
98
+ redirect: isUrlSource(source) ? describeRedirect(source, page.url()) : null
99
+ };
100
+ }
101
+ /**
102
+ * Open HTML a gate has rewritten in memory (inflated text, forced theme,
103
+ * deleted rule).
104
+ *
105
+ * Prefer `openSource` when the bytes on disk are what should be measured.
106
+ *
107
+ * Navigate-then-replace, because the obvious alternative does not work.
108
+ * Measured on the same one-line fixture (external `style.css` setting
109
+ * `p { color: rgb(4,5,6) }`):
110
+ *
111
+ * setContent + injected `<base href="file:///dir/">` -> rgb(0, 0, 0)
112
+ * goto(file) then setContent -> rgb(4, 5, 6)
113
+ *
114
+ * A `<base>` cannot rescue it: the `setContent` document has an opaque origin,
115
+ * and Chromium blocks a `file://` subresource from one. Navigating first gives
116
+ * the document a real base URL, and `setContent` replaces the markup without
117
+ * discarding it.
118
+ */
119
+ async function openHtml(browser, html, options = {}) {
120
+ const page = await browser.newPage(pageOptions(options));
121
+ if (options.baseSource) await page.goto(sourceToUrl(options.baseSource), {
122
+ waitUntil: "domcontentloaded",
123
+ timeout: options.timeout ?? 3e4
124
+ });
125
+ await page.setContent(html, {
126
+ waitUntil: options.waitUntil ?? "networkidle",
127
+ timeout: options.timeout ?? 3e4
128
+ });
129
+ if (!options.skipSettle) await settlePage(page, options.settleMs ?? 250);
130
+ return page;
131
+ }
132
+ //#endregion
133
+ export { isUrlSource, openHtml, openSource, resolveSource, settlePage, sourceToUrl };
@@ -0,0 +1,30 @@
1
+ //#region src/png-utils.d.ts
2
+ interface PngData {
3
+ width: number;
4
+ height: number;
5
+ data: Uint8Array;
6
+ }
7
+ /**
8
+ * Crop or pad an image to the target dimensions.
9
+ * Only handles the common region; overflow is zero-filled.
10
+ */
11
+ declare function cropImage(img: PngData, w: number, h: number): PngData;
12
+ /**
13
+ * Crop an arbitrary rectangle out of an image.
14
+ *
15
+ * Unlike {@link cropImage} (which only clips the top-left common region),
16
+ * this extracts a region at an arbitrary (x, y) offset. The rectangle is
17
+ * clamped to the image bounds, so the returned crop may be smaller than
18
+ * requested when the region overruns an edge (or off the top-left).
19
+ */
20
+ declare function cropRegion(img: PngData, x: number, y: number, w: number, h: number): PngData;
21
+ /**
22
+ * Read a PNG file and return RGBA pixel data.
23
+ */
24
+ declare function decodePng(path: string): Promise<PngData>;
25
+ /**
26
+ * Write RGBA pixel data to a PNG file.
27
+ */
28
+ declare function encodePng(path: string, data: PngData): Promise<void>;
29
+ //#endregion
30
+ export { PngData, cropImage, cropRegion, decodePng, encodePng };
@@ -0,0 +1,80 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ //#region src/png-utils.ts
3
+ /**
4
+ * PNG I/O utilities
5
+ *
6
+ * Low-level PNG decode/encode using pngjs.
7
+ * Used by heatmap.ts and other modules that need raw pixel data.
8
+ */
9
+ /**
10
+ * Crop or pad an image to the target dimensions.
11
+ * Only handles the common region; overflow is zero-filled.
12
+ */
13
+ function cropImage(img, w, h) {
14
+ if (img.width === w && img.height === h) return img;
15
+ const data = new Uint8Array(w * h * 4);
16
+ for (let y = 0; y < h; y++) {
17
+ const srcOffset = y * img.width * 4;
18
+ const dstOffset = y * w * 4;
19
+ data.set(img.data.subarray(srcOffset, srcOffset + w * 4), dstOffset);
20
+ }
21
+ return {
22
+ width: w,
23
+ height: h,
24
+ data
25
+ };
26
+ }
27
+ /**
28
+ * Crop an arbitrary rectangle out of an image.
29
+ *
30
+ * Unlike {@link cropImage} (which only clips the top-left common region),
31
+ * this extracts a region at an arbitrary (x, y) offset. The rectangle is
32
+ * clamped to the image bounds, so the returned crop may be smaller than
33
+ * requested when the region overruns an edge (or off the top-left).
34
+ */
35
+ function cropRegion(img, x, y, w, h) {
36
+ const x0 = Math.max(0, Math.min(Math.floor(x), img.width));
37
+ const y0 = Math.max(0, Math.min(Math.floor(y), img.height));
38
+ const x1 = Math.max(x0, Math.min(Math.floor(x + w), img.width));
39
+ const y1 = Math.max(y0, Math.min(Math.floor(y + h), img.height));
40
+ const cw = x1 - x0;
41
+ const ch = y1 - y0;
42
+ const data = new Uint8Array(cw * ch * 4);
43
+ for (let row = 0; row < ch; row++) {
44
+ const srcOffset = ((y0 + row) * img.width + x0) * 4;
45
+ const dstOffset = row * cw * 4;
46
+ data.set(img.data.subarray(srcOffset, srcOffset + cw * 4), dstOffset);
47
+ }
48
+ return {
49
+ width: cw,
50
+ height: ch,
51
+ data
52
+ };
53
+ }
54
+ /**
55
+ * Read a PNG file and return RGBA pixel data.
56
+ */
57
+ async function decodePng(path) {
58
+ const { PNG } = await import("pngjs");
59
+ const buffer = await readFile(path);
60
+ const png = PNG.sync.read(buffer);
61
+ return {
62
+ width: png.width,
63
+ height: png.height,
64
+ data: new Uint8Array(png.data.buffer, png.data.byteOffset, png.data.byteLength)
65
+ };
66
+ }
67
+ /**
68
+ * Write RGBA pixel data to a PNG file.
69
+ */
70
+ async function encodePng(path, data) {
71
+ const { PNG } = await import("pngjs");
72
+ const png = new PNG({
73
+ width: data.width,
74
+ height: data.height
75
+ });
76
+ Buffer.from(data.data.buffer, data.data.byteOffset, data.data.byteLength).copy(png.data);
77
+ await writeFile(path, PNG.sync.write(png));
78
+ }
79
+ //#endregion
80
+ export { cropImage, cropRegion, decodePng, encodePng };
@@ -0,0 +1,20 @@
1
+ import { PngData } from "./png-utils.mjs";
2
+
3
+ //#region src/region-shift.d.ts
4
+ interface RegionShiftEstimate {
5
+ /** Content moved by +dx px horizontally in current (vs baseline). */
6
+ dx: number;
7
+ /** Content moved by +dy px vertically in current (vs baseline). */
8
+ dy: number;
9
+ /** 0..1; correlation peak strength of the dominant axis. */
10
+ confidence: number;
11
+ }
12
+ interface RegionRect {
13
+ x: number;
14
+ y: number;
15
+ width: number;
16
+ height: number;
17
+ }
18
+ declare function estimateRegionShift(baseline: PngData, current: PngData, region: RegionRect, maxOffset?: number): RegionShiftEstimate | null;
19
+ //#endregion
20
+ export { RegionShiftEstimate, estimateRegionShift };