framesheet 0.0.0-stage → 0.1.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 (69) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +212 -2
  3. package/dist/analysis.d.ts +84 -0
  4. package/dist/analysis.d.ts.map +1 -0
  5. package/dist/analysis.js +335 -0
  6. package/dist/analysis.js.map +1 -0
  7. package/dist/checks.d.ts +44 -0
  8. package/dist/checks.d.ts.map +1 -0
  9. package/dist/checks.js +200 -0
  10. package/dist/checks.js.map +1 -0
  11. package/dist/compose.d.ts +117 -0
  12. package/dist/compose.d.ts.map +1 -0
  13. package/dist/compose.js +236 -0
  14. package/dist/compose.js.map +1 -0
  15. package/dist/driver.d.ts +56 -0
  16. package/dist/driver.d.ts.map +1 -0
  17. package/dist/driver.js +94 -0
  18. package/dist/driver.js.map +1 -0
  19. package/dist/generated/assets.d.ts +9 -0
  20. package/dist/generated/assets.d.ts.map +1 -0
  21. package/dist/generated/assets.js +11 -0
  22. package/dist/generated/assets.js.map +1 -0
  23. package/dist/index.d.ts +15 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +14 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/inspect.d.ts +150 -0
  28. package/dist/inspect.d.ts.map +1 -0
  29. package/dist/inspect.js +570 -0
  30. package/dist/inspect.js.map +1 -0
  31. package/dist/models.d.ts +117 -0
  32. package/dist/models.d.ts.map +1 -0
  33. package/dist/models.js +9 -0
  34. package/dist/models.js.map +1 -0
  35. package/dist/pixels.d.ts +46 -0
  36. package/dist/pixels.d.ts.map +1 -0
  37. package/dist/pixels.js +237 -0
  38. package/dist/pixels.js.map +1 -0
  39. package/dist/pyfmt.d.ts +16 -0
  40. package/dist/pyfmt.d.ts.map +1 -0
  41. package/dist/pyfmt.js +54 -0
  42. package/dist/pyfmt.js.map +1 -0
  43. package/dist/report.schema.json +754 -0
  44. package/dist/sources.d.ts +32 -0
  45. package/dist/sources.d.ts.map +1 -0
  46. package/dist/sources.js +123 -0
  47. package/dist/sources.js.map +1 -0
  48. package/dist/test.d.ts +46 -0
  49. package/dist/test.d.ts.map +1 -0
  50. package/dist/test.js +58 -0
  51. package/dist/test.js.map +1 -0
  52. package/dist/timing.d.ts +30 -0
  53. package/dist/timing.d.ts.map +1 -0
  54. package/dist/timing.js +128 -0
  55. package/dist/timing.js.map +1 -0
  56. package/package.json +78 -4
  57. package/src/analysis.ts +416 -0
  58. package/src/checks.ts +261 -0
  59. package/src/compose.ts +303 -0
  60. package/src/driver.ts +115 -0
  61. package/src/generated/assets.ts +14 -0
  62. package/src/index.ts +44 -0
  63. package/src/inspect.ts +690 -0
  64. package/src/models.ts +130 -0
  65. package/src/pixels.ts +248 -0
  66. package/src/pyfmt.ts +55 -0
  67. package/src/sources.ts +131 -0
  68. package/src/test.ts +100 -0
  69. package/src/timing.ts +133 -0
package/src/models.ts ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Report types: the same shape as the Python package's `report.json`
3
+ * (`framesheet.models.InspectionResult`), checked against ../schema/report.schema.json.
4
+ * Field names are snake_case on purpose: one schema for both implementations.
5
+ */
6
+
7
+ export type Severity = "error" | "warning" | "info";
8
+ export type SourceKind = "svg" | "html";
9
+ export type ColorScheme = "light" | "dark";
10
+ /** An axis-aligned box as `[x, y, width, height]`. */
11
+ export type Rect = [number, number, number, number];
12
+
13
+ /** A single problem (or noteworthy fact) found by a static or render check. */
14
+ export interface Finding {
15
+ severity: Severity;
16
+ /** Stable, kebab-case identifier, e.g. `parked-at-origin` (see schema/finding-codes.json). */
17
+ code: string;
18
+ message: string;
19
+ check: "static" | "render";
20
+ /** Human-readable element label such as `circle#dot` or `text[2] "Hello"`. */
21
+ element: string | null;
22
+ /** Sample times (seconds) at which the problem was observed. */
23
+ times: number[] | null;
24
+ }
25
+
26
+ export type AnimationKind = "smil" | "css-animation" | "css-transition" | "web-animation";
27
+
28
+ /** Timing of one declarative animation, as reported by the browser. */
29
+ export interface AnimationTiming {
30
+ kind: AnimationKind;
31
+ target: string | null;
32
+ name: string | null;
33
+ /** Begin / delay in seconds (may be negative). */
34
+ start: number;
35
+ /** Duration of one iteration in seconds. */
36
+ duration: number;
37
+ /** Iteration count; `null` means infinite. */
38
+ iterations: number | null;
39
+ direction: string;
40
+ /** Seconds until the animation looks the same again (2x duration for alternate). */
41
+ period: number;
42
+ /** End of the active interval in seconds; `null` if infinite. */
43
+ end: number | null;
44
+ /** Computed `transform-box` of an SVG target whose transform is animated by CSS. */
45
+ transform_box: string | null;
46
+ }
47
+
48
+ export interface DurationInfo {
49
+ seconds: number;
50
+ method: "override" | "detected" | "fallback";
51
+ /** True if at least one animation repeats forever (or motion is JS-driven). */
52
+ looping: boolean;
53
+ detail: string;
54
+ animations: AnimationTiming[];
55
+ }
56
+
57
+ export interface FrameMetrics {
58
+ index: number;
59
+ t: number;
60
+ /** Share of pixels that differ from the previous frame (0 for the first frame). */
61
+ changed_ratio: number;
62
+ /** Bounding box (CSS px) of the pixels that changed vs. the previous frame. */
63
+ changed_box: Rect | null;
64
+ /** Path of the individual frame PNG, if frames were written. */
65
+ path: string | null;
66
+ }
67
+
68
+ export interface ElementTrack {
69
+ element: string;
70
+ /** `smil`, `css-animation`, `web-animation` and/or `moved` (geometry changed). */
71
+ animated_by: string[];
72
+ units: "viewBox" | "px";
73
+ /** One box per frame (`null` if not rendered at that frame). */
74
+ boxes: (Rect | null)[];
75
+ }
76
+
77
+ export interface LoopInfo {
78
+ checked: boolean;
79
+ seamless: boolean | null;
80
+ /** Changed-pixel share between `t=end-epsilon` and `t=0`. */
81
+ seam_ratio: number | null;
82
+ /** Changed-pixel share between `t=0` and `t=epsilon` (normal motion per step). */
83
+ step_ratio: number | null;
84
+ seam_box: Rect | null;
85
+ detail: string;
86
+ }
87
+
88
+ /** Image paths. Absolute when written to disk (`out`), else bare file names. */
89
+ export interface ImagePaths {
90
+ full: string;
91
+ sheet: string;
92
+ heatmap: string;
93
+ report: string;
94
+ }
95
+
96
+ /** Everything framesheet found out about one input: the content of `report.json`. */
97
+ export interface Report {
98
+ source: string;
99
+ kind: SourceKind;
100
+ viewport: [number, number];
101
+ device_scale_factor: number;
102
+ /** Drawing area in CSS px (viewBox for SVG documents/components, viewport for HTML). */
103
+ canvas: Rect;
104
+ duration: DurationInfo;
105
+ /** Sample times of the contact-sheet tiles in seconds. */
106
+ times: number[];
107
+ full_at: number;
108
+ images: ImagePaths;
109
+ findings: Finding[];
110
+ frames: FrameMetrics[];
111
+ elements: ElementTrack[];
112
+ loop: LoopInfo;
113
+ console_errors: string[];
114
+ }
115
+
116
+ /** PNG bytes of the three images (plus every sampled frame if requested). */
117
+ export interface ImageBuffers {
118
+ /** One full-resolution frame at `fullAt` (default t=0): layout, text, margins. */
119
+ full: Buffer;
120
+ /** Contact sheet: N labelled frames over one cycle. */
121
+ sheet: Buffer;
122
+ /** Motion heatmap: what moves at all, over a dimmed first frame. */
123
+ heatmap: Buffer;
124
+ /** Every contact-sheet frame (only with `keepFrames`). */
125
+ frames?: Buffer[];
126
+ }
127
+
128
+ export function asRect(values: ArrayLike<number>): Rect {
129
+ return [Number(values[0]), Number(values[1]), Number(values[2]), Number(values[3])];
130
+ }
package/src/pixels.ts ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Pixel math on decoded frames (pure JS, pngjs): diff stats, motion map, heat overlay.
3
+ * Same thresholds and colour ramp as compose.py.
4
+ */
5
+
6
+ import { PNG } from "pngjs";
7
+ import type { Rect } from "./models.js";
8
+ import { pyRound } from "./pyfmt.js";
9
+
10
+ /** Per-channel difference (0-255) below which a pixel counts as unchanged. */
11
+ export const DIFF_THRESHOLD = 8;
12
+
13
+ /** A decoded RGBA frame. */
14
+ export interface Frame {
15
+ width: number;
16
+ height: number;
17
+ data: Uint8Array;
18
+ }
19
+
20
+ /** Device-px bounding box `[x0, y0, x1, y1)` (exclusive right/bottom, like Pillow's getbbox). */
21
+ export type Box = [number, number, number, number];
22
+
23
+ export function decode(png: Buffer): Frame {
24
+ const img = PNG.sync.read(png);
25
+ return { width: img.width, height: img.height, data: img.data };
26
+ }
27
+
28
+ export function encode(frame: Frame): Buffer {
29
+ const png = new PNG({ width: frame.width, height: frame.height });
30
+ png.data = Buffer.from(frame.data.buffer, frame.data.byteOffset, frame.data.byteLength);
31
+ return PNG.sync.write(png, { colorType: 2, inputHasAlpha: true, deflateLevel: 6 });
32
+ }
33
+
34
+ function sameSize(a: Frame, b: Frame): void {
35
+ if (a.width !== b.width || a.height !== b.height) {
36
+ throw new Error(`Frame sizes differ: ${a.width}x${a.height} vs ${b.width}x${b.height}`);
37
+ }
38
+ }
39
+
40
+ /** Per-pixel max RGB channel difference between two frames. */
41
+ export function changeMask(a: Frame, b: Frame): Uint8Array {
42
+ sameSize(a, b);
43
+ const n = a.width * a.height;
44
+ const out = new Uint8Array(n);
45
+ const da = a.data;
46
+ const db = b.data;
47
+ for (let i = 0, p = 0; i < n; i++, p += 4) {
48
+ const r = Math.abs(da[p] - db[p]);
49
+ const g = Math.abs(da[p + 1] - db[p + 1]);
50
+ const bl = Math.abs(da[p + 2] - db[p + 2]);
51
+ out[i] = r > g ? (r > bl ? r : bl) : g > bl ? g : bl;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** Share of changed pixels and the bounding box (device px) of the change. */
57
+ export function diffStats(a: Frame, b: Frame): [number, Box | null] {
58
+ sameSize(a, b);
59
+ const da = a.data;
60
+ const db = b.data;
61
+ const w = a.width;
62
+ const n = a.width * a.height;
63
+ let count = 0;
64
+ let x0 = Infinity;
65
+ let y0 = Infinity;
66
+ let x1 = -1;
67
+ let y1 = -1;
68
+ for (let i = 0, p = 0; i < n; i++, p += 4) {
69
+ let m = Math.abs(da[p] - db[p]);
70
+ let d = Math.abs(da[p + 1] - db[p + 1]);
71
+ if (d > m) m = d;
72
+ d = Math.abs(da[p + 2] - db[p + 2]);
73
+ if (d > m) m = d;
74
+ if (m > DIFF_THRESHOLD) {
75
+ count++;
76
+ const x = i % w;
77
+ const y = (i - x) / w;
78
+ if (x < x0) x0 = x;
79
+ if (x > x1) x1 = x;
80
+ if (y < y0) y0 = y;
81
+ if (y > y1) y1 = y;
82
+ }
83
+ }
84
+ return [count / n, count ? [x0, y0, x1 + 1, y1 + 1] : null];
85
+ }
86
+
87
+ export function toCss(box: Box | null, scale: number): Rect | null {
88
+ if (box === null) return null;
89
+ const [x0, y0, x1, y1] = box;
90
+ return [pyRound(x0 / scale, 1), pyRound(y0 / scale, 1), pyRound((x1 - x0) / scale, 1), pyRound((y1 - y0) / scale, 1)];
91
+ }
92
+
93
+ export function union(a: Box, b: Box): Box {
94
+ return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])];
95
+ }
96
+
97
+ /**
98
+ * Incremental motion map: per-pixel max change between consecutive frames and vs. the
99
+ * first frame, plus the union of consecutive changed boxes. Frames are fed in time order,
100
+ * so they need not be kept in memory.
101
+ */
102
+ export class MotionAccumulator {
103
+ first: Frame | null = null;
104
+ private prev: Frame | null = null;
105
+ acc: Uint8Array | null = null;
106
+ box: Box | null = null;
107
+ count = 0;
108
+
109
+ add(frame: Frame): void {
110
+ this.count++;
111
+ if (!this.first) {
112
+ this.first = frame;
113
+ this.prev = frame;
114
+ this.acc = new Uint8Array(frame.width * frame.height);
115
+ return;
116
+ }
117
+ sameSize(this.first, frame);
118
+ const acc = this.acc!;
119
+ const a = this.prev!.data;
120
+ const f0 = this.first.data;
121
+ const c = frame.data;
122
+ const w = frame.width;
123
+ let x0 = Infinity;
124
+ let y0 = Infinity;
125
+ let x1 = -1;
126
+ let y1 = -1;
127
+ // Fused: max channel diff vs. the previous frame (step) and vs. the first frame.
128
+ for (let i = 0, p = 0; i < acc.length; i++, p += 4) {
129
+ const r = c[p];
130
+ const g = c[p + 1];
131
+ const b = c[p + 2];
132
+ let s = Math.abs(r - a[p]);
133
+ let d = Math.abs(g - a[p + 1]);
134
+ if (d > s) s = d;
135
+ d = Math.abs(b - a[p + 2]);
136
+ if (d > s) s = d;
137
+ let m = Math.abs(r - f0[p]);
138
+ d = Math.abs(g - f0[p + 1]);
139
+ if (d > m) m = d;
140
+ d = Math.abs(b - f0[p + 2]);
141
+ if (d > m) m = d;
142
+ if (s > m) m = s;
143
+ if (m > acc[i]) acc[i] = m;
144
+ if (s > DIFF_THRESHOLD) {
145
+ const x = i % w;
146
+ const y = (i - x) / w;
147
+ if (x < x0) x0 = x;
148
+ if (x > x1) x1 = x;
149
+ if (y < y0) y0 = y;
150
+ if (y > y1) y1 = y;
151
+ }
152
+ }
153
+ if (x1 >= 0) {
154
+ const b: Box = [x0, y0, x1 + 1, y1 + 1];
155
+ this.box = this.box ? union(this.box, b) : b;
156
+ }
157
+ this.prev = frame;
158
+ }
159
+ }
160
+
161
+ /** Colour ramp for change strength: violet (subtle) -> red -> orange -> yellow (strong). */
162
+ function heatLut(): { rgb: [number, number, number][]; alpha: number[] } {
163
+ const stops: [number, [number, number, number]][] = [
164
+ [0.0, [168, 85, 247]],
165
+ [0.4, [239, 68, 68]],
166
+ [0.7, [249, 115, 22]],
167
+ [1.0, [253, 230, 80]],
168
+ ];
169
+ const rgb: [number, number, number][] = [];
170
+ const alpha: number[] = [];
171
+ for (let v = 0; v < 256; v++) {
172
+ if (v <= DIFF_THRESHOLD) {
173
+ rgb.push([0, 0, 0]);
174
+ alpha.push(0);
175
+ continue;
176
+ }
177
+ const s = Math.min(1, (v - DIFF_THRESHOLD) / 120) ** 0.5;
178
+ let color: [number, number, number] = stops[stops.length - 1][1];
179
+ for (let k = 0; k < stops.length - 1; k++) {
180
+ const [p0, c0] = stops[k];
181
+ const [p1, c1] = stops[k + 1];
182
+ if (s <= p1) {
183
+ const f = (s - p0) / (p1 - p0);
184
+ color = [0, 1, 2].map((j) => pyRound(c0[j] + (c1[j] - c0[j]) * f)) as [number, number, number];
185
+ break;
186
+ }
187
+ }
188
+ rgb.push(color);
189
+ alpha.push(pyRound(170 + 85 * s));
190
+ }
191
+ return { rgb, alpha };
192
+ }
193
+
194
+ export const HEAT_LUT = heatLut();
195
+ const BASE_LUT = Array.from({ length: 256 }, (_, v) => pyRound(28 + v * 0.32));
196
+
197
+ /**
198
+ * Coloured motion overlay on a dimmed, desaturated first frame (full resolution), with
199
+ * `boxes` outlined. Returns an RGBA frame (opaque).
200
+ */
201
+ export function heatOverlay(first: Frame, motion: Uint8Array, boxes: Box[], boxColor: [number, number, number]): Frame {
202
+ const { width, height } = first;
203
+ const out = new Uint8Array(width * height * 4);
204
+ const src = first.data;
205
+ const { rgb, alpha } = HEAT_LUT;
206
+ for (let i = 0, p = 0; i < motion.length; i++, p += 4) {
207
+ // Pillow's "L" conversion (ITU-R 601-2 luma, fixed point), then the dim ramp.
208
+ const l = (src[p] * 19595 + src[p + 1] * 38470 + src[p + 2] * 7471 + 0x8000) >> 16;
209
+ const base = BASE_LUT[l];
210
+ const a = alpha[motion[i]];
211
+ if (a === 0) {
212
+ out[p] = out[p + 1] = out[p + 2] = base;
213
+ } else {
214
+ const c = rgb[motion[i]];
215
+ out[p] = Math.round((c[0] * a + base * (255 - a)) / 255);
216
+ out[p + 1] = Math.round((c[1] * a + base * (255 - a)) / 255);
217
+ out[p + 2] = Math.round((c[2] * a + base * (255 - a)) / 255);
218
+ }
219
+ out[p + 3] = 255;
220
+ }
221
+ const stroke = Math.max(2, pyRound(Math.max(width, height) / 300));
222
+ for (const [bx0, by0, bx1, by1] of boxes) outline(out, width, height, [bx0, by0, bx1, by1], stroke, boxColor);
223
+ return { width, height, data: out };
224
+ }
225
+
226
+ /** Pillow's `rectangle(box, outline=, width=)`: inclusive corners, stroke drawn inward. */
227
+ function outline(
228
+ data: Uint8Array,
229
+ width: number,
230
+ height: number,
231
+ [x0, y0, x1, y1]: Box,
232
+ stroke: number,
233
+ color: [number, number, number],
234
+ ): void {
235
+ const set = (x: number, y: number) => {
236
+ if (x < 0 || y < 0 || x >= width || y >= height) return;
237
+ const p = (y * width + x) * 4;
238
+ data[p] = color[0];
239
+ data[p + 1] = color[1];
240
+ data[p + 2] = color[2];
241
+ };
242
+ for (let y = y0; y <= y1; y++) {
243
+ for (let x = x0; x <= x1; x++) {
244
+ const edge = x - x0 < stroke || x1 - x < stroke || y - y0 < stroke || y1 - y < stroke;
245
+ if (edge) set(x, y);
246
+ }
247
+ }
248
+ }
package/src/pyfmt.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Number rounding/formatting with Python semantics, so reports and summaries match the
3
+ * Python implementation (`round(x, n)`, `f"{x:.2f}"`, `f"{x:g}"`, `f"{x:.1%}"`).
4
+ *
5
+ * Python rounds the exact binary value half-to-even; JavaScript's `toFixed` rounds ties
6
+ * away from zero. Ties only matter for exactly representable halves (0.125, 2.5, ...).
7
+ */
8
+
9
+ /** Exact decimal expansion digits after the point (enough for |x| >= 1e-30). */
10
+ function isExactTie(x: number, digits: number): boolean {
11
+ const s = Math.abs(x).toFixed(Math.min(100, digits + 60));
12
+ const frac = s.split(".")[1] ?? "";
13
+ const rest = frac.slice(digits);
14
+ return rest.length > 0 && rest[0] === "5" && /^50*$/.test(rest);
15
+ }
16
+
17
+ /** Python's `round(x, digits)` (half to even on the exact value). */
18
+ export function pyRound(x: number, digits = 0): number {
19
+ if (!Number.isFinite(x)) return x;
20
+ if (isExactTie(x, digits)) {
21
+ const factor = 10 ** digits;
22
+ const down = Math.trunc(Math.abs(x) * factor);
23
+ const even = down % 2 === 0 ? down : down + 1;
24
+ const out = (Math.sign(x) * even) / factor;
25
+ return Object.is(out, -0) ? 0 : out;
26
+ }
27
+ const out = Number(x.toFixed(digits));
28
+ return Object.is(out, -0) ? 0 : out;
29
+ }
30
+
31
+ /** Python's `f"{x:.{digits}f}"`. */
32
+ export function fixed(x: number, digits: number): string {
33
+ return pyRound(x, digits).toFixed(digits);
34
+ }
35
+
36
+ /** Python's `f"{x:g}"` (6 significant digits, trailing zeros stripped). */
37
+ export function g(x: number): string {
38
+ if (x === 0) return Object.is(x, -0) ? "-0" : "0";
39
+ if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf";
40
+ const precision = 6;
41
+ const [mantissa, expPart] = x.toExponential(precision - 1).split("e");
42
+ const exp = Number(expPart);
43
+ if (exp < -4 || exp >= precision) {
44
+ const m = mantissa.includes(".") ? mantissa.replace(/\.?0+$/, "") : mantissa;
45
+ const sign = exp < 0 ? "-" : "+";
46
+ return `${m}e${sign}${String(Math.abs(exp)).padStart(2, "0")}`;
47
+ }
48
+ const s = fixed(x, Math.max(0, precision - 1 - exp));
49
+ return s.includes(".") ? s.replace(/\.?0+$/, "") : s;
50
+ }
51
+
52
+ /** Python's `f"{x:.{digits}%}"`. */
53
+ export function pct(x: number, digits: number): string {
54
+ return `${fixed(x * 100, digits)}%`;
55
+ }
package/src/sources.ts ADDED
@@ -0,0 +1,131 @@
1
+ /** Input handling: files, markup strings and URLs (port of sources.py). */
2
+
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { extname, resolve as resolvePath } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import type { ParsedDocument } from "./checks.js";
7
+ import type { SourceKind } from "./models.js";
8
+ import { pyRound } from "./pyfmt.js";
9
+
10
+ export const DEFAULT_HTML_SIZE: [number, number] = [1280, 720];
11
+ export const DEFAULT_SVG_SIZE: [number, number] = [960, 540];
12
+ const LENGTH = /^\s*([0-9]*\.?[0-9]+)\s*(px)?\s*$/;
13
+ /** Markup strings are served from this virtual origin (page.route), never from disk. */
14
+ export const VIRTUAL_ORIGIN = "http://framesheet.invalid";
15
+
16
+ /** A resolved input. */
17
+ export interface Source {
18
+ /** What the caller passed (path, URL, or `<snippet>`). */
19
+ label: string;
20
+ kind: SourceKind;
21
+ /** What the browser navigates to. */
22
+ url: string;
23
+ /** Source text if available (static checks, size detection). */
24
+ text: string | null;
25
+ /** Markup served via page.route at `url` (markup-string inputs only). */
26
+ body?: string;
27
+ }
28
+
29
+ export function looksLikeSvg(text: string): boolean {
30
+ let head = text.slice(0, 4096).replace(/<!--[\s\S]*?-->/g, "").trimStart().toLowerCase();
31
+ if (head.startsWith("<?xml")) {
32
+ const i = head.indexOf("?>");
33
+ head = (i >= 0 ? head.slice(i + 2) : "").trimStart();
34
+ }
35
+ if (head.startsWith("<!doctype svg")) return true;
36
+ return head.startsWith("<svg");
37
+ }
38
+
39
+ /** Wrap an in-memory SVG/HTML snippet as a source (served from a virtual URL). */
40
+ export function snippet(markup: string, label = "<snippet>"): Source {
41
+ const kind: SourceKind = looksLikeSvg(markup) ? "svg" : "html";
42
+ let text = markup;
43
+ if (kind === "html" && !text.toLowerCase().includes("<html")) {
44
+ text = `<!DOCTYPE html>\n<html><head><meta charset='utf-8'></head><body>${text}</body></html>`;
45
+ }
46
+ return { label, kind, url: `${VIRTUAL_ORIGIN}/input.${kind}`, text, body: text };
47
+ }
48
+
49
+ /** Best-effort download of a URL's body (for static checks and SVG size detection). */
50
+ export async function fetchText(url: string, timeoutMs = 15_000): Promise<string | null> {
51
+ try {
52
+ const response = await fetch(url, {
53
+ headers: { "User-Agent": "framesheet" },
54
+ signal: AbortSignal.timeout(timeoutMs),
55
+ });
56
+ if (!response.ok) return null;
57
+ return await response.text();
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /** Turn a path, URL or markup string (starting with `<`) into a {@link Source}. */
64
+ export async function resolveSource(source: string): Promise<Source> {
65
+ if (source.trimStart().startsWith("<")) return snippet(source);
66
+ if (/^https?:\/\//.test(source)) {
67
+ const text = await fetchText(source);
68
+ const byName = source.split("?")[0].toLowerCase().endsWith(".svg");
69
+ const kind: SourceKind = byName || (text !== null && looksLikeSvg(text)) ? "svg" : "html";
70
+ return { label: source, kind, url: source, text };
71
+ }
72
+ const path = resolvePath(source.startsWith("file://") ? new URL(source).pathname : source);
73
+ let isFile = false;
74
+ try {
75
+ isFile = statSync(path).isFile();
76
+ } catch {
77
+ isFile = false;
78
+ }
79
+ if (!isFile) throw new Error(`Input not found: ${source}`);
80
+ const text = readFileSync(path, "utf8");
81
+ const ext = extname(path).toLowerCase();
82
+ let kind: SourceKind;
83
+ if (ext === ".svg") kind = "svg";
84
+ else if ([".html", ".htm", ".xhtml"].includes(ext)) kind = "html";
85
+ else kind = looksLikeSvg(text) ? "svg" : "html";
86
+ return { label: source, kind, url: pathToFileURL(path).href, text };
87
+ }
88
+
89
+ function length(value: string | undefined): number | null {
90
+ if (value == null) return null;
91
+ const m = LENGTH.exec(value);
92
+ return m ? parseFloat(m[1]) : null;
93
+ }
94
+
95
+ /** Intrinsic size of a parsed SVG: absolute width/height attributes, else the viewBox. */
96
+ export function svgSize(doc: ParsedDocument): [number, number] | null {
97
+ if (doc.error !== null || !doc.elements.length) return null;
98
+ const root = doc.elements[0];
99
+ const get = (name: string) => root.attrs.find(([local]) => local === name)?.[2];
100
+ let width = length(get("width"));
101
+ let height = length(get("height"));
102
+ const box = (get("viewBox") ?? "")
103
+ .trim()
104
+ .split(/[\s,]+/)
105
+ .filter(Boolean)
106
+ .map(Number);
107
+ if (box.length === 4 && box[2] > 0 && box[3] > 0) {
108
+ const [, , vbW, vbH] = box;
109
+ if (width && !height) height = (width * vbH) / vbW;
110
+ else if (height && !width) width = (height * vbW) / vbH;
111
+ width = width || vbW;
112
+ height = height || vbH;
113
+ }
114
+ if (width && height) return [Math.max(1, pyRound(width)), Math.max(1, pyRound(height))];
115
+ return null;
116
+ }
117
+
118
+ export function defaultSize(kind: SourceKind, parsed: ParsedDocument | null): [number, number] {
119
+ if (kind === "svg" && parsed) {
120
+ const size = svgSize(parsed);
121
+ if (size) return size;
122
+ }
123
+ return kind === "svg" ? DEFAULT_SVG_SIZE : DEFAULT_HTML_SIZE;
124
+ }
125
+
126
+ /** Parse `WxH` (e.g. `1280x720`). */
127
+ export function parseSize(value: string): [number, number] {
128
+ const m = /^\s*(\d+)\s*[xX*]\s*(\d+)\s*$/.exec(value);
129
+ if (!m) throw new Error(`Invalid size '${value}'; expected WIDTHxHEIGHT, e.g. 1280x720`);
130
+ return [Number(m[1]), Number(m[2])];
131
+ }
package/src/test.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * `framesheet/test`: visual regression of animations in a `@playwright/test` suite.
3
+ *
4
+ * ```ts
5
+ * import { test } from "@playwright/test";
6
+ * import { expectAnimation } from "framesheet/test";
7
+ *
8
+ * test("mind map opens smoothly", async ({ page }) => {
9
+ * await page.goto("/mindmap");
10
+ * await expectAnimation(page.locator("#mindmap"), "mindmap-open", { frames: 8 });
11
+ * });
12
+ * ```
13
+ */
14
+
15
+ import { expect, type Locator, type Page, test } from "@playwright/test";
16
+ import { type Inspection, type InspectPageOptions, inspectPage } from "./inspect.js";
17
+ import type { Finding, Severity } from "./models.js";
18
+
19
+ export { LAUNCH_ARGS, prepare } from "./inspect.js";
20
+
21
+ export interface ExpectAnimationOptions extends Omit<InspectPageOptions, "locator" | "out"> {
22
+ /** Allowed share of differing pixels in the sheet (Playwright `maxDiffPixelRatio`). */
23
+ maxDiffPixelRatio?: number;
24
+ /** Allowed number of differing pixels (Playwright `maxDiffPixels`). */
25
+ maxDiffPixels?: number;
26
+ /** Per-pixel colour distance threshold 0-1 (Playwright `threshold`, default 0.2). */
27
+ threshold?: number;
28
+ /** Also compare the motion heatmap against `<name>-heatmap.png`. Default false. */
29
+ heatmap?: boolean;
30
+ /**
31
+ * Fail on findings of this severity or worse: `"error"` (default), `"warning"`, or
32
+ * `false` to only compare images.
33
+ */
34
+ failOn?: Exclude<Severity, "info"> | false;
35
+ /** Finding codes to ignore for `failOn` (e.g. `["console-error"]`). */
36
+ ignore?: string[];
37
+ /** Attach sheet/heatmap/full/report to the test report. Default true. */
38
+ attach?: boolean;
39
+ /** Compare against the stored baseline. Default true; `false` only checks findings. */
40
+ snapshot?: boolean;
41
+ }
42
+
43
+ function isPage(target: Page | Locator): target is Page {
44
+ return typeof (target as Page).goto === "function";
45
+ }
46
+
47
+ function describe(findings: Finding[]): string {
48
+ return findings.map((f) => `${f.severity} ${f.code}: ${f.message}`).join("\n");
49
+ }
50
+
51
+ /**
52
+ * Build the contact sheet of an animation (whole page or one component) and compare it
53
+ * with the stored baseline `<name>.png` via Playwright's `toMatchSnapshot` (so
54
+ * `--update-snapshots`, per-platform snapshot names and diff images work as usual).
55
+ * Also fails on error findings unless `failOn: false`. Returns the inspection.
56
+ */
57
+ export async function expectAnimation(
58
+ target: Page | Locator,
59
+ name: string,
60
+ options: ExpectAnimationOptions = {},
61
+ ): Promise<Inspection> {
62
+ const page = isPage(target) ? target : target.page();
63
+ const locator = isPage(target) ? undefined : target;
64
+ const {
65
+ maxDiffPixelRatio,
66
+ maxDiffPixels,
67
+ threshold,
68
+ heatmap,
69
+ failOn = "error",
70
+ ignore = [],
71
+ attach = true,
72
+ snapshot = true,
73
+ ...rest
74
+ } = options;
75
+ const result = await inspectPage(page, { ...rest, locator, title: rest.title ?? name });
76
+ const base = name.replace(/\.png$/i, "");
77
+ if (attach) {
78
+ const info = test.info();
79
+ await info.attach(`${base}-sheet.png`, { body: result.images.sheet, contentType: "image/png" });
80
+ await info.attach(`${base}-heatmap.png`, { body: result.images.heatmap, contentType: "image/png" });
81
+ await info.attach(`${base}-full.png`, { body: result.images.full, contentType: "image/png" });
82
+ await info.attach(`${base}-report.json`, {
83
+ body: JSON.stringify(result.report, null, 2),
84
+ contentType: "application/json",
85
+ });
86
+ }
87
+ const compare = Object.fromEntries(
88
+ Object.entries({ maxDiffPixelRatio, maxDiffPixels, threshold }).filter(([, v]) => v !== undefined),
89
+ );
90
+ if (snapshot) {
91
+ expect(result.images.sheet).toMatchSnapshot(`${base}.png`, compare);
92
+ if (heatmap) expect(result.images.heatmap).toMatchSnapshot(`${base}-heatmap.png`, compare);
93
+ }
94
+ if (failOn) {
95
+ const worst = failOn === "warning" ? ["error", "warning"] : ["error"];
96
+ const bad = result.findings.filter((f) => worst.includes(f.severity) && !ignore.includes(f.code));
97
+ expect(bad, `framesheet findings for '${base}':\n${describe(bad)}\n\n${result.summary()}`).toEqual([]);
98
+ }
99
+ return result;
100
+ }