@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,128 @@
1
+ //#region src/region-shift.ts
2
+ const MIN_REGION_EDGE = 8;
3
+ const MIN_PEAK = .6;
4
+ /** The shifted-lag peak must beat the zero-lag correlation by this much. */
5
+ const MIN_PEAK_ADVANTAGE = .15;
6
+ function estimateRegionShift(baseline, current, region, maxOffset = 64) {
7
+ if (region.width < MIN_REGION_EDGE || region.height < MIN_REGION_EDGE) return null;
8
+ const width = Math.min(baseline.width, current.width);
9
+ const height = Math.min(baseline.height, current.height);
10
+ const x0 = clamp(region.x - maxOffset, 0, width);
11
+ const x1 = clamp(region.x + region.width + maxOffset, 0, width);
12
+ const y0 = clamp(region.y, 0, height);
13
+ const y1 = clamp(region.y + region.height, 0, height);
14
+ const yw0 = clamp(region.y - maxOffset, 0, height);
15
+ const yw1 = clamp(region.y + region.height + maxOffset, 0, height);
16
+ const xr0 = clamp(region.x, 0, width);
17
+ const xr1 = clamp(region.x + region.width, 0, width);
18
+ if (x1 <= x0 || y1 <= y0 || yw1 <= yw0 || xr1 <= xr0) return null;
19
+ const horizontal = bestLag(columnProfile(baseline, x0, x1, y0, y1), columnProfile(current, x0, x1, y0, y1), maxOffset);
20
+ const vertical = bestLag(rowProfile(baseline, xr0, xr1, yw0, yw1), rowProfile(current, xr0, xr1, yw0, yw1), maxOffset);
21
+ const dx = acceptAxis(horizontal) ? horizontal.lag : 0;
22
+ const dy = acceptAxis(vertical) ? vertical.lag : 0;
23
+ if (dx === 0 && dy === 0) return null;
24
+ const confidences = [];
25
+ if (dx !== 0) confidences.push(horizontal.peak);
26
+ if (dy !== 0) confidences.push(vertical.peak);
27
+ return {
28
+ dx,
29
+ dy,
30
+ confidence: Number(Math.max(...confidences).toFixed(3))
31
+ };
32
+ }
33
+ function acceptAxis(result) {
34
+ return !result.flat && result.lag !== 0 && result.peak >= MIN_PEAK && result.peak - result.zeroLag >= MIN_PEAK_ADVANTAGE;
35
+ }
36
+ /**
37
+ * Find the lag maximizing normalized cross-correlation between two
38
+ * mean-subtracted profiles. Positive lag = current content sits at a
39
+ * higher coordinate than baseline (moved right / down).
40
+ */
41
+ function bestLag(base, curr, maxOffset) {
42
+ const a = meanSubtract(base);
43
+ const b = meanSubtract(curr);
44
+ if (a.flat || b.flat) return {
45
+ lag: 0,
46
+ peak: 0,
47
+ zeroLag: 0,
48
+ flat: true
49
+ };
50
+ let bestLag = 0;
51
+ let bestVal = -Infinity;
52
+ let zeroVal = 0;
53
+ const n = Math.min(a.values.length, b.values.length);
54
+ const limit = Math.min(maxOffset, n - 1);
55
+ for (let lag = -limit; lag <= limit; lag++) {
56
+ let dot = 0;
57
+ let normA = 0;
58
+ let normB = 0;
59
+ for (let i = 0; i < n; i++) {
60
+ const j = i + lag;
61
+ if (j < 0 || j >= n) continue;
62
+ dot += a.values[i] * b.values[j];
63
+ normA += a.values[i] * a.values[i];
64
+ normB += b.values[j] * b.values[j];
65
+ }
66
+ if (normA === 0 || normB === 0) continue;
67
+ const val = dot / Math.sqrt(normA * normB);
68
+ if (lag === 0) zeroVal = val;
69
+ if (val > bestVal) {
70
+ bestVal = val;
71
+ bestLag = lag;
72
+ }
73
+ }
74
+ if (!Number.isFinite(bestVal)) return {
75
+ lag: 0,
76
+ peak: 0,
77
+ zeroLag: 0,
78
+ flat: true
79
+ };
80
+ return {
81
+ lag: bestLag,
82
+ peak: bestVal,
83
+ zeroLag: zeroVal,
84
+ flat: false
85
+ };
86
+ }
87
+ function meanSubtract(profile) {
88
+ let sum = 0;
89
+ for (const v of profile) sum += v;
90
+ const mean = sum / profile.length;
91
+ const values = new Float64Array(profile.length);
92
+ let variance = 0;
93
+ for (let i = 0; i < profile.length; i++) {
94
+ values[i] = profile[i] - mean;
95
+ variance += values[i] * values[i];
96
+ }
97
+ return {
98
+ values,
99
+ flat: variance / profile.length < 1
100
+ };
101
+ }
102
+ function columnProfile(img, x0, x1, y0, y1) {
103
+ const profile = new Float64Array(x1 - x0);
104
+ for (let x = x0; x < x1; x++) {
105
+ let sum = 0;
106
+ for (let y = y0; y < y1; y++) sum += lumaAt(img, x, y);
107
+ profile[x - x0] = sum / (y1 - y0);
108
+ }
109
+ return profile;
110
+ }
111
+ function rowProfile(img, x0, x1, y0, y1) {
112
+ const profile = new Float64Array(y1 - y0);
113
+ for (let y = y0; y < y1; y++) {
114
+ let sum = 0;
115
+ for (let x = x0; x < x1; x++) sum += lumaAt(img, x, y);
116
+ profile[y - y0] = sum / (x1 - x0);
117
+ }
118
+ return profile;
119
+ }
120
+ function lumaAt(img, x, y) {
121
+ const i = (y * img.width + x) * 4;
122
+ return .299 * img.data[i] + .587 * img.data[i + 1] + .114 * img.data[i + 2];
123
+ }
124
+ function clamp(value, min, max) {
125
+ return Math.max(min, Math.min(max, value));
126
+ }
127
+ //#endregion
128
+ export { estimateRegionShift };
@@ -0,0 +1,14 @@
1
+ //#region src/run-ledger.d.ts
2
+ interface RunLedgerEntry {
3
+ /** Tool name, e.g. "build-page", "check-breakpoints", "verify-markup". */
4
+ tool: string;
5
+ /** Primary input (attempt HTML or URL). */
6
+ source: string;
7
+ /** Secondary input (target PNG, manifest, ...) when applicable. */
8
+ target?: string;
9
+ /** Headline numbers, tool-specific but flat (matched/missing/extra/status/diffRatio...). */
10
+ headline: Record<string, string | number | boolean | null>;
11
+ }
12
+ declare function appendRunLedger(entry: RunLedgerEntry, cwd?: string): void;
13
+ //#endregion
14
+ export { RunLedgerEntry, appendRunLedger };
@@ -0,0 +1,31 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ //#region src/run-ledger.ts
4
+ /**
5
+ * Append-only run ledger for agent-loop tools.
6
+ *
7
+ * Every measurement invocation (`build page`, the dynamic gates,
8
+ * `verify markup`) appends one JSONL line to `.vlmkit/run-ledger.jsonl`
9
+ * under the working directory. This turns the "rounds" KPI from an agent
10
+ * self-report into an auditable record: a verifier can check that the
11
+ * agent actually re-measured after each fix, and how the headline numbers
12
+ * moved round by round (see docs/knowledge.md "Markup Agent KPI" — round
13
+ * counts were self-reported and unreliable in 5/5 S5 runs).
14
+ *
15
+ * Writes are best-effort: a ledger failure must never break the tool run.
16
+ * Opt out with VLMKIT_NO_LEDGER=1 (e.g. CI bulk runs).
17
+ */
18
+ function appendRunLedger(entry, cwd = process.cwd()) {
19
+ if (process.env.VLMKIT_NO_LEDGER === "1") return;
20
+ try {
21
+ const dir = join(cwd, ".vlmkit");
22
+ mkdirSync(dir, { recursive: true });
23
+ const line = JSON.stringify({
24
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
25
+ ...entry
26
+ });
27
+ appendFileSync(join(dir, "run-ledger.jsonl"), line + "\n");
28
+ } catch {}
29
+ }
30
+ //#endregion
31
+ export { appendRunLedger };
@@ -0,0 +1,12 @@
1
+ //#region src/terminal-colors.d.ts
2
+ /** Shared ANSI terminal color codes and helpers */
3
+ declare const DIM = "\u001B[2m";
4
+ declare const RESET = "\u001B[0m";
5
+ declare const GREEN = "\u001B[32m";
6
+ declare const RED = "\u001B[31m";
7
+ declare const YELLOW = "\u001B[33m";
8
+ declare const CYAN = "\u001B[36m";
9
+ declare const BOLD = "\u001B[1m";
10
+ declare function hr(width?: number): void;
11
+ //#endregion
12
+ export { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr };
@@ -0,0 +1,14 @@
1
+ //#region src/terminal-colors.ts
2
+ /** Shared ANSI terminal color codes and helpers */
3
+ const DIM = "\x1B[2m";
4
+ const RESET = "\x1B[0m";
5
+ const GREEN = "\x1B[32m";
6
+ const RED = "\x1B[31m";
7
+ const YELLOW = "\x1B[33m";
8
+ const CYAN = "\x1B[36m";
9
+ const BOLD = "\x1B[1m";
10
+ function hr(width = 72) {
11
+ console.log(`${DIM}${"─".repeat(width)}${RESET}`);
12
+ }
13
+ //#endregion
14
+ export { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr };
@@ -0,0 +1,121 @@
1
+ //#region src/text-rows.d.ts
2
+ interface TextRow {
3
+ /** Optional OCR/debug text when a caller can supply it. Pixel extraction does not infer this. */
4
+ text?: string;
5
+ /** Y-coordinate of the row's vertical center. */
6
+ yCenter: number;
7
+ /** Top y of the run of dark rows (inclusive). */
8
+ yStart: number;
9
+ /** Bottom y of the run of dark rows (inclusive). */
10
+ yEnd: number;
11
+ /** Mean luminance across the band (0-255). */
12
+ meanLuma: number;
13
+ /** Approximate height in pixels. */
14
+ height: number;
15
+ /**
16
+ * Estimated font-size in px, derived from band height. Typical UI
17
+ * fonts have a band height ≈ 0.75 × fontSize (the band spans
18
+ * baseline to ascender; descenders push it a bit further). Rounded
19
+ * to the nearest common UI size (12, 14, 16, 18, 20, 24, …, 72).
20
+ */
21
+ estimatedFontSize?: number;
22
+ /**
23
+ * Ink density inside the text's horizontal bounding box. Computed
24
+ * as (dark pixels with luma < 100) / (pixels in text-bbox). Larger
25
+ * values = thicker strokes = bolder weight. Empirical buckets:
26
+ * - < 0.10 → regular / light
27
+ * - 0.10-0.16 → medium / semibold
28
+ * - > 0.16 → bold / heavy
29
+ * Noisy on short text — compare same-content baseline vs variant
30
+ * for high-confidence weight-mismatch detection.
31
+ */
32
+ inkDensity?: number;
33
+ /** Bucketed weight class — heuristic, see `inkDensity` doc. */
34
+ weightBucket?: "light" | "regular" | "medium" | "bold";
35
+ /** Horizontal extent of ink within the band (px from left edge of image). */
36
+ inkLeft?: number;
37
+ inkRight?: number;
38
+ }
39
+ interface MatchedTextRow {
40
+ /** Position in the ordered list of detected rows (0 = topmost). */
41
+ rank: number;
42
+ baseline: TextRow;
43
+ variant: TextRow;
44
+ /** variant.yCenter − baseline.yCenter (px). */
45
+ deltaY: number;
46
+ }
47
+ interface RowGapDelta {
48
+ /** Rank of the row above the gap. */
49
+ aboveRank: number;
50
+ /** Rank of the row below the gap. */
51
+ belowRank: number;
52
+ /** Baseline gap (yCenter[below] − yCenter[above]). */
53
+ baselineGap: number;
54
+ /** Variant gap. */
55
+ variantGap: number;
56
+ /** variantGap − baselineGap; positive means the gap grew. */
57
+ delta: number;
58
+ }
59
+ interface ExtractTextRowsOptions {
60
+ /**
61
+ * Minimum dip in mean luminance (vs. the median row luminance) for a
62
+ * row to be considered "text". Default 12 — picks up body text but
63
+ * ignores subpixel-rendering noise.
64
+ */
65
+ minLumaDip?: number;
66
+ /** Minimum band height in px. Default 4. */
67
+ minBandHeight?: number;
68
+ /** Maximum bands to return (top-N by yCenter, i.e. all of them). */
69
+ maxBands?: number;
70
+ }
71
+ declare function extractTextRowsFromRgba(data: Uint8Array, width: number, height: number, options?: ExtractTextRowsOptions): TextRow[];
72
+ declare function extractTextRowsFromFile(path: string, options?: ExtractTextRowsOptions): Promise<TextRow[]>;
73
+ /**
74
+ * Pair text rows by ordered index. When baseline has 6 rows and variant
75
+ * has 6 rows, this maps row #0 → row #0, #1 → #1, etc. When the counts
76
+ * differ, only the prefix common to both is matched.
77
+ *
78
+ * Reports rows with |Δy| above `minDeltaY` to keep the table focused on
79
+ * actionable shifts (small subpixel deltas are excluded by default).
80
+ */
81
+ declare function matchTextRows(baseline: TextRow[], variant: TextRow[], minDeltaY?: number): MatchedTextRow[];
82
+ /**
83
+ * Compute per-pair gap deltas from baseline ↔ variant row matches.
84
+ * The gap above row N+1 = `row[N+1].yCenter − row[N].yCenter` — the
85
+ * vertical distance between consecutive text bands. If the gap
86
+ * differs between baseline and variant, the spacing between those
87
+ * two pieces of content is wrong, and the fix is on the preceding
88
+ * element's `margin-bottom` / `padding-bottom`.
89
+ *
90
+ * Subagent G v3 dogfood: "once IoU > 0.98, the remaining ~1.7%
91
+ * diff is text baseline Δy in the 2-19px range, and the report
92
+ * doesn't yet suggest which CSS knob to turn." Gap deltas tell
93
+ * the agent exactly which margin to adjust.
94
+ */
95
+ interface TypographyMismatch {
96
+ rank: number;
97
+ baselineFontSize?: number;
98
+ variantFontSize?: number;
99
+ baselineWeight?: TextRow["weightBucket"];
100
+ variantWeight?: TextRow["weightBucket"];
101
+ baselineDensity?: number;
102
+ variantDensity?: number;
103
+ /** "size" | "weight" | "both" */
104
+ kind: "size" | "weight" | "both";
105
+ }
106
+ /**
107
+ * Compare typography hints across ordered baseline ↔ variant pairs.
108
+ * Reports rows where:
109
+ * - estimated font-size buckets differ (different snapped px), OR
110
+ * - weight buckets differ ("regular" vs "bold").
111
+ *
112
+ * Same-content assumption: when baseline and variant render the same
113
+ * text content, ink density is directly comparable. When content
114
+ * differs, density can vary by character makeup ("iii" vs "WWW")
115
+ * and the comparison is noisier — only large bucket jumps are
116
+ * surfaced.
117
+ */
118
+ declare function compareRowTypography(baseline: TextRow[], variant: TextRow[], minDensityDelta?: number): TypographyMismatch[];
119
+ declare function computeRowGapDeltas(baseline: TextRow[], variant: TextRow[], minAbsoluteDelta?: number): RowGapDelta[];
120
+ //#endregion
121
+ export { ExtractTextRowsOptions, MatchedTextRow, RowGapDelta, TextRow, TypographyMismatch, compareRowTypography, computeRowGapDeltas, extractTextRowsFromFile, extractTextRowsFromRgba, matchTextRows };
@@ -0,0 +1,246 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { PNG } from "pngjs";
3
+ //#region src/text-rows.ts
4
+ /**
5
+ * Text-row y-position extraction.
6
+ *
7
+ * Subagent F's wish-list item: "I need 'the `$24` text row is at y=420
8
+ * in the reference but y=380 in mine' as a first-class signal — without
9
+ * needing DOM correspondence."
10
+ *
11
+ * Compute the per-row mean luminance of an RGBA image. Text rows are
12
+ * darker than the surrounding whitespace (assuming light background;
13
+ * the dark-bg case is handled by symmetry: we just look for *dips*
14
+ * relative to the local average, regardless of polarity). Group
15
+ * consecutive dark rows into "text bands" and report each band's
16
+ * y-center.
17
+ *
18
+ * Pair baseline rows with variant rows by order (band #N in baseline ↔
19
+ * band #N in variant) and emit Δy. When the agent's rendering has the
20
+ * right *number* of text rows but wrong y-positions, this surfaces the
21
+ * shift directly.
22
+ */
23
+ const DEFAULT_MIN_LUMA_DIP = 12;
24
+ const DEFAULT_MIN_BAND_HEIGHT = 4;
25
+ const DEFAULT_MAX_BANDS = 64;
26
+ function rowStats(data, width, height) {
27
+ const mean = new Float32Array(height);
28
+ const range = new Float32Array(height);
29
+ for (let y = 0; y < height; y++) {
30
+ let sum = 0, mn = 255, mx = 0;
31
+ const rowStart = y * width * 4;
32
+ for (let x = 0; x < width; x++) {
33
+ const idx = rowStart + x * 4;
34
+ const L = .299 * data[idx] + .587 * data[idx + 1] + .114 * data[idx + 2];
35
+ sum += L;
36
+ if (L < mn) mn = L;
37
+ if (L > mx) mx = L;
38
+ }
39
+ mean[y] = sum / width;
40
+ range[y] = mx - mn;
41
+ }
42
+ return {
43
+ mean,
44
+ range
45
+ };
46
+ }
47
+ function median(values) {
48
+ if (values.length === 0) return 0;
49
+ const sorted = Float32Array.from(values).sort();
50
+ const mid = sorted.length >> 1;
51
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
52
+ }
53
+ /** Snap a raw px height to the nearest common UI font-size bucket. */
54
+ function snapFontSize(rawPx) {
55
+ const buckets = [
56
+ 10,
57
+ 11,
58
+ 12,
59
+ 13,
60
+ 14,
61
+ 16,
62
+ 18,
63
+ 20,
64
+ 22,
65
+ 24,
66
+ 28,
67
+ 32,
68
+ 36,
69
+ 40,
70
+ 48,
71
+ 56,
72
+ 64,
73
+ 72
74
+ ];
75
+ let best = buckets[0];
76
+ let bestDist = Math.abs(rawPx - best);
77
+ for (const b of buckets) {
78
+ const d = Math.abs(rawPx - b);
79
+ if (d < bestDist) {
80
+ best = b;
81
+ bestDist = d;
82
+ }
83
+ }
84
+ return best;
85
+ }
86
+ function bucketWeight(density) {
87
+ if (density < .15) return "light";
88
+ if (density < .27) return "regular";
89
+ if (density < .36) return "medium";
90
+ return "bold";
91
+ }
92
+ /**
93
+ * Compute typography hints (font-size estimate, ink density, weight
94
+ * bucket) for a band by sampling its pixels. Mutates the band in
95
+ * place. From subagent G v3 dogfood: "next blocker is sub-pixel
96
+ * vertical spacing tuning — and a font-size / weight estimate per
97
+ * heatmap region would push this to < 1% in one more round."
98
+ */
99
+ function annotateTypography(band, data, width, height) {
100
+ const inkThreshold = Math.max(40, band.meanLuma - 50);
101
+ let inkLeft = width, inkRight = -1;
102
+ let inkPixels = 0;
103
+ for (let y = band.yStart; y <= band.yEnd && y < height; y++) for (let x = 0; x < width; x++) {
104
+ const i = (y * width + x) * 4;
105
+ if (.299 * data[i] + .587 * data[i + 1] + .114 * data[i + 2] < inkThreshold) {
106
+ if (x < inkLeft) inkLeft = x;
107
+ if (x > inkRight) inkRight = x;
108
+ inkPixels++;
109
+ }
110
+ }
111
+ if (inkRight < inkLeft) return;
112
+ const inkArea = (inkRight - inkLeft + 1) * (band.yEnd - band.yStart + 1);
113
+ const density = inkArea > 0 ? inkPixels / inkArea : 0;
114
+ band.estimatedFontSize = snapFontSize(band.height / .92);
115
+ band.inkDensity = density;
116
+ band.weightBucket = bucketWeight(density);
117
+ band.inkLeft = inkLeft;
118
+ band.inkRight = inkRight;
119
+ }
120
+ function extractTextRowsFromRgba(data, width, height, options = {}) {
121
+ if (width <= 0 || height <= 0) return [];
122
+ const minDip = options.minLumaDip ?? DEFAULT_MIN_LUMA_DIP;
123
+ const minBandH = options.minBandHeight ?? DEFAULT_MIN_BAND_HEIGHT;
124
+ const maxBands = options.maxBands ?? DEFAULT_MAX_BANDS;
125
+ const MIN_INK_RANGE = 80;
126
+ const { mean: rowMeans, range: rowRanges } = rowStats(data, width, height);
127
+ const med = median(rowMeans);
128
+ const bands = [];
129
+ let runStart = -1;
130
+ let runSum = 0;
131
+ for (let y = 0; y < height; y++) {
132
+ const meanDip = med - rowMeans[y] >= minDip;
133
+ const hasInk = rowRanges[y] >= MIN_INK_RANGE;
134
+ if (meanDip || hasInk) {
135
+ if (runStart < 0) {
136
+ runStart = y;
137
+ runSum = 0;
138
+ }
139
+ runSum += rowMeans[y];
140
+ } else if (runStart >= 0) {
141
+ const bandH = y - runStart;
142
+ if (bandH >= minBandH) bands.push({
143
+ yStart: runStart,
144
+ yEnd: y - 1,
145
+ yCenter: Math.round((runStart + y - 1) / 2),
146
+ height: bandH,
147
+ meanLuma: runSum / bandH
148
+ });
149
+ runStart = -1;
150
+ }
151
+ }
152
+ if (runStart >= 0) {
153
+ const bandH = height - runStart;
154
+ if (bandH >= minBandH) bands.push({
155
+ yStart: runStart,
156
+ yEnd: height - 1,
157
+ yCenter: Math.round((runStart + height - 1) / 2),
158
+ height: bandH,
159
+ meanLuma: runSum / bandH
160
+ });
161
+ }
162
+ const capped = bands.slice(0, maxBands);
163
+ for (const band of capped) annotateTypography(band, data, width, height);
164
+ return capped;
165
+ }
166
+ async function extractTextRowsFromFile(path, options = {}) {
167
+ const buf = await readFile(path);
168
+ const png = PNG.sync.read(buf);
169
+ return extractTextRowsFromRgba(png.data, png.width, png.height, options);
170
+ }
171
+ /**
172
+ * Pair text rows by ordered index. When baseline has 6 rows and variant
173
+ * has 6 rows, this maps row #0 → row #0, #1 → #1, etc. When the counts
174
+ * differ, only the prefix common to both is matched.
175
+ *
176
+ * Reports rows with |Δy| above `minDeltaY` to keep the table focused on
177
+ * actionable shifts (small subpixel deltas are excluded by default).
178
+ */
179
+ function matchTextRows(baseline, variant, minDeltaY = 2) {
180
+ const out = [];
181
+ const n = Math.min(baseline.length, variant.length);
182
+ for (let i = 0; i < n; i++) {
183
+ const dy = variant[i].yCenter - baseline[i].yCenter;
184
+ if (Math.abs(dy) >= minDeltaY) out.push({
185
+ rank: i,
186
+ baseline: baseline[i],
187
+ variant: variant[i],
188
+ deltaY: dy
189
+ });
190
+ }
191
+ return out;
192
+ }
193
+ /**
194
+ * Compare typography hints across ordered baseline ↔ variant pairs.
195
+ * Reports rows where:
196
+ * - estimated font-size buckets differ (different snapped px), OR
197
+ * - weight buckets differ ("regular" vs "bold").
198
+ *
199
+ * Same-content assumption: when baseline and variant render the same
200
+ * text content, ink density is directly comparable. When content
201
+ * differs, density can vary by character makeup ("iii" vs "WWW")
202
+ * and the comparison is noisier — only large bucket jumps are
203
+ * surfaced.
204
+ */
205
+ function compareRowTypography(baseline, variant, minDensityDelta = .04) {
206
+ const n = Math.min(baseline.length, variant.length);
207
+ const out = [];
208
+ for (let i = 0; i < n; i++) {
209
+ const b = baseline[i], v = variant[i];
210
+ if (b.estimatedFontSize === void 0 || v.estimatedFontSize === void 0) continue;
211
+ const sizeDiffers = b.estimatedFontSize !== v.estimatedFontSize;
212
+ const densityDelta = Math.abs((b.inkDensity ?? 0) - (v.inkDensity ?? 0));
213
+ const weightDiffers = b.weightBucket !== v.weightBucket && densityDelta >= minDensityDelta;
214
+ if (!sizeDiffers && !weightDiffers) continue;
215
+ out.push({
216
+ rank: i,
217
+ baselineFontSize: b.estimatedFontSize,
218
+ variantFontSize: v.estimatedFontSize,
219
+ baselineWeight: b.weightBucket,
220
+ variantWeight: v.weightBucket,
221
+ baselineDensity: b.inkDensity,
222
+ variantDensity: v.inkDensity,
223
+ kind: sizeDiffers && weightDiffers ? "both" : sizeDiffers ? "size" : "weight"
224
+ });
225
+ }
226
+ return out;
227
+ }
228
+ function computeRowGapDeltas(baseline, variant, minAbsoluteDelta = 2) {
229
+ const n = Math.min(baseline.length, variant.length);
230
+ const out = [];
231
+ for (let i = 0; i < n - 1; i++) {
232
+ const baseGap = baseline[i + 1].yCenter - baseline[i].yCenter;
233
+ const varGap = variant[i + 1].yCenter - variant[i].yCenter;
234
+ const delta = varGap - baseGap;
235
+ if (Math.abs(delta) >= minAbsoluteDelta) out.push({
236
+ aboveRank: i,
237
+ belowRank: i + 1,
238
+ baselineGap: baseGap,
239
+ variantGap: varGap,
240
+ delta
241
+ });
242
+ }
243
+ return out;
244
+ }
245
+ //#endregion
246
+ export { compareRowTypography, computeRowGapDeltas, extractTextRowsFromFile, extractTextRowsFromRgba, matchTextRows };