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
@@ -0,0 +1,416 @@
1
+ /**
2
+ * Render checks on per-frame geometry (port of analysis.py).
3
+ *
4
+ * Each check is a function `(Geometry) => Finding[]` registered in {@link CHECKS}.
5
+ * Keep the logic, thresholds and messages in step with analysis.py.
6
+ */
7
+
8
+ import type { AnimationTiming, ElementTrack, Finding, Rect } from "./models.js";
9
+ import { asRect } from "./models.js";
10
+ import { fixed } from "./pyfmt.js";
11
+
12
+ /** Pixels an element may poke out of its container/canvas before it is reported. */
13
+ export const TOLERANCE = 1.0;
14
+ export const MAX_TRACKS = 30;
15
+ export const MAX_REPORTED = 12;
16
+ export const SMALL_FRACTION = 0.2;
17
+ export const CONTAINERS = new Set(["g", "svg", "a", "switch", "div", "section", "main", "article", "span"]);
18
+
19
+ export interface Element {
20
+ index: number;
21
+ tag: string;
22
+ label: string;
23
+ svg: boolean;
24
+ parent: number;
25
+ }
26
+
27
+ /** `[index, clientRect, userRect | null, visible]` per rendered element (runtime `measure()`). */
28
+ export type GeometryEntry = [number, number[], number[] | null, boolean];
29
+
30
+ /** Everything captured at one sample time. */
31
+ export interface FrameGeometry {
32
+ t: number;
33
+ geometry: GeometryEntry[];
34
+ /** HTML text overflow `[index, dx, dy]`. */
35
+ overflow: [number, number, number][];
36
+ }
37
+
38
+ export interface Description {
39
+ i: number;
40
+ tag: string;
41
+ label: string;
42
+ svg: boolean;
43
+ parent: number;
44
+ }
45
+
46
+ /** Inputs shared by all render checks. */
47
+ export class Geometry {
48
+ constructor(
49
+ public elements: Map<number, Element>,
50
+ public times: number[],
51
+ /** Client rect (CSS px) per element per frame; `null` = not rendered/invisible. */
52
+ public client: Map<number, (Rect | null)[]>,
53
+ /** SVG user-space rect (outermost `<svg>`) per element per frame. */
54
+ public user: Map<number, (Rect | null)[]>,
55
+ public canvas: Rect,
56
+ public viewbox: Rect | null,
57
+ public targets: Map<number, string[]>,
58
+ public animations: AnimationTiming[],
59
+ public isSvgDoc: boolean,
60
+ /** `[index, dx, dy]` per frame. */
61
+ public htmlOverflow: [number, number, number][][],
62
+ ) {}
63
+
64
+ static build(
65
+ description: Description[],
66
+ snapshots: FrameGeometry[],
67
+ opts: {
68
+ canvas: Rect;
69
+ viewbox: Rect | null;
70
+ targets: Record<string, string[]>;
71
+ animations: AnimationTiming[];
72
+ isSvgDoc: boolean;
73
+ },
74
+ ): Geometry {
75
+ const elements = new Map<number, Element>();
76
+ for (const d of description) {
77
+ elements.set(d.i, { index: d.i, tag: d.tag, label: d.label, svg: d.svg, parent: d.parent });
78
+ }
79
+ const n = snapshots.length;
80
+ const client = new Map<number, (Rect | null)[]>();
81
+ const user = new Map<number, (Rect | null)[]>();
82
+ const slot = (m: Map<number, (Rect | null)[]>, i: number) => {
83
+ let v = m.get(i);
84
+ if (!v) {
85
+ v = new Array<Rect | null>(n).fill(null);
86
+ m.set(i, v);
87
+ }
88
+ return v;
89
+ };
90
+ snapshots.forEach((snap, k) => {
91
+ for (const [index, rect, userRect, visible] of snap.geometry) {
92
+ if (!visible) continue;
93
+ slot(client, index)[k] = asRect(rect);
94
+ if (userRect != null) slot(user, index)[k] = asRect(userRect);
95
+ }
96
+ });
97
+ const targets = new Map<number, string[]>();
98
+ for (const [k, v] of Object.entries(opts.targets)) targets.set(Number(k), v);
99
+ return new Geometry(
100
+ elements,
101
+ snapshots.map((s) => s.t),
102
+ client,
103
+ user,
104
+ opts.canvas,
105
+ opts.viewbox,
106
+ targets,
107
+ opts.animations,
108
+ opts.isSvgDoc,
109
+ snapshots.map((s) => s.overflow),
110
+ );
111
+ }
112
+
113
+ ancestors(index: number): number[] {
114
+ const out: number[] = [];
115
+ let parent = this.elements.get(index)?.parent ?? -1;
116
+ while (parent !== -1 && this.elements.has(parent)) {
117
+ out.push(parent);
118
+ parent = this.elements.get(parent)!.parent;
119
+ }
120
+ return out;
121
+ }
122
+
123
+ label(index: number): string {
124
+ return this.elements.get(index)?.label ?? `element ${index}`;
125
+ }
126
+
127
+ moved(): Set<number> {
128
+ const out = new Set<number>();
129
+ for (const [index, rects] of this.client) {
130
+ const present = rects.filter((r): r is Rect => r !== null);
131
+ if (present.length !== rects.length && present.length) {
132
+ out.add(index); // appears / disappears
133
+ continue;
134
+ }
135
+ if (present.length && present.slice(1).some((r) => differs(present[0], r))) out.add(index);
136
+ }
137
+ return out;
138
+ }
139
+ }
140
+
141
+ function differs(a: Rect, b: Rect, tol = 0.5): boolean {
142
+ return a.some((x, i) => Math.abs(x - b[i]) > tol);
143
+ }
144
+
145
+ /** Drop flagged elements that have a flagged descendant (report the innermost). */
146
+ function leaves(geo: Geometry, flagged: Set<number>): Set<number> {
147
+ const covered = new Set<number>();
148
+ for (const i of flagged) for (const a of geo.ancestors(i)) covered.add(a);
149
+ return new Set([...flagged].filter((i) => !covered.has(i)));
150
+ }
151
+
152
+ function timesAt(geo: Geometry, ks: number[]): number[] {
153
+ return ks.map((k) => geo.times[k]);
154
+ }
155
+
156
+ export function fmtTimes(times: number[]): string {
157
+ if (times.length > 4) {
158
+ return `t=${fixed(times[0], 2)}s..${fixed(times[times.length - 1], 2)}s (${times.length} frames)`;
159
+ }
160
+ return `t=${times.map((t) => `${fixed(t, 2)}s`).join(", ")}`;
161
+ }
162
+
163
+ function finding(code: string, message: string, element: string | null, times: number[] | null): Finding {
164
+ return { severity: "warning", code, message, check: "render", element, times };
165
+ }
166
+
167
+ const byNumber = (a: number, b: number) => a - b;
168
+
169
+ /** Per-frame boxes of animated elements (declared targets or anything that moved). */
170
+ export function tracks(geo: Geometry): ElementTrack[] {
171
+ const moved = geo.moved();
172
+ const targetSet = new Set(geo.targets.keys());
173
+ // A moving group moves all its children: keep the outermost mover. A group whose box
174
+ // only changes because an animated descendant moves is not reported on its own.
175
+ const explained = new Set<number>();
176
+ for (const i of targetSet) for (const a of geo.ancestors(i)) if (!targetSet.has(a)) explained.add(a);
177
+ const movers = new Set([...moved].filter((i) => !explained.has(i)));
178
+ const indices = new Set<number>(targetSet);
179
+ for (const i of movers) if (!geo.ancestors(i).some((a) => movers.has(a))) indices.add(i);
180
+ const out: ElementTrack[] = [];
181
+ for (const index of [...indices].sort(byNumber).slice(0, MAX_TRACKS)) {
182
+ const boxes = geo.user.get(index) ?? geo.client.get(index);
183
+ if (!boxes) continue;
184
+ const kinds = [...(geo.targets.get(index) ?? [])];
185
+ if (moved.has(index)) kinds.push("moved");
186
+ out.push({
187
+ element: geo.label(index),
188
+ animated_by: kinds,
189
+ units: geo.user.has(index) ? "viewBox" : "px",
190
+ boxes,
191
+ });
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /** Elements extending past the viewBox (SVG) or viewport (HTML). */
197
+ export function checkOutside(geo: Geometry): Finding[] {
198
+ const [cx, cy, cw, ch] = geo.canvas;
199
+ const hits = new Map<number, number[]>();
200
+ const amounts = new Map<number, Map<string, number>>();
201
+ for (const [index, rects] of geo.client) {
202
+ rects.forEach((rect, k) => {
203
+ if (rect === null) return;
204
+ const [x, y, w, h] = rect;
205
+ const over: [string, number][] = [
206
+ ["left", cx - x],
207
+ ["top", cy - y],
208
+ ["right", x + w - (cx + cw)],
209
+ ["bottom", y + h - (cy + ch)],
210
+ ];
211
+ const worst = over.filter(([, v]) => v > TOLERANCE);
212
+ if (worst.length) {
213
+ (hits.get(index) ?? hits.set(index, []).get(index)!).push(k);
214
+ const agg = amounts.get(index) ?? amounts.set(index, new Map()).get(index)!;
215
+ for (const [side, v] of worst) agg.set(side, Math.max(agg.get(side) ?? 0, v));
216
+ }
217
+ });
218
+ }
219
+ const keep = leaves(geo, new Set(hits.keys()));
220
+ const area = geo.isSvgDoc ? "viewBox" : "viewport";
221
+ const out: Finding[] = [];
222
+ const worstOf = (i: number) => Math.max(...amounts.get(i)!.values());
223
+ // Python sorts a set of small ints (ascending iteration order) by the worst amount.
224
+ const ordered = [...keep].sort(byNumber).sort((a, b) => worstOf(b) - worstOf(a));
225
+ for (const index of ordered.slice(0, MAX_REPORTED)) {
226
+ const ks = hits.get(index)!;
227
+ const sides = [...amounts.get(index)!.entries()].map(([side, v]) => `${fixed(v, 0)}px ${side}`).join(", ");
228
+ const when = ks.length === geo.times.length ? "at every frame" : `at ${fmtTimes(timesAt(geo, ks))}`;
229
+ out.push(
230
+ finding(
231
+ "outside-bounds",
232
+ `${geo.label(index)} extends outside the ${area} ${when} (up to ${sides}).`,
233
+ geo.label(index),
234
+ timesAt(geo, ks),
235
+ ),
236
+ );
237
+ }
238
+ if (ordered.length > MAX_REPORTED) {
239
+ out.push(
240
+ finding(
241
+ "outside-bounds",
242
+ `... and ${ordered.length - MAX_REPORTED} more element(s) outside the ${area}.`,
243
+ null,
244
+ null,
245
+ ),
246
+ );
247
+ }
248
+ return out;
249
+ }
250
+
251
+ /** Small SVG elements sitting on the user-space origin (0,0), e.g. before `begin`. */
252
+ export function checkParked(geo: Geometry): Finding[] {
253
+ if (geo.viewbox === null) return [];
254
+ const [, , vw, vh] = geo.viewbox;
255
+ const hits = new Map<number, number[]>();
256
+ for (const [index, rects] of geo.user) {
257
+ const element = geo.elements.get(index);
258
+ if (!element || CONTAINERS.has(element.tag)) continue;
259
+ rects.forEach((rect, k) => {
260
+ if (rect === null) return;
261
+ const [x, y, w, h] = rect;
262
+ const small = w < SMALL_FRACTION * vw && h < SMALL_FRACTION * vh;
263
+ const coversOrigin = x <= TOLERANCE && y <= TOLERANCE && x + w >= 0 && y + h >= 0;
264
+ if (small && coversOrigin) (hits.get(index) ?? hits.set(index, []).get(index)!).push(k);
265
+ });
266
+ }
267
+ return [...leaves(geo, new Set(hits.keys()))].sort(byNumber).map((index) => {
268
+ const times = timesAt(geo, hits.get(index)!);
269
+ return finding(
270
+ "parked-at-origin",
271
+ `${geo.label(index)} sits at the SVG origin (0,0) at ${fmtTimes(times)}; ` +
272
+ "typical cause: <animateMotion> with a positive begin, or a missing x/y/cx/cy.",
273
+ geo.label(index),
274
+ times,
275
+ );
276
+ });
277
+ }
278
+
279
+ const rectArea = (r: Rect) => r[2] * r[3];
280
+
281
+ function overlap(a: Rect, b: Rect): number {
282
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
283
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
284
+ return Math.max(0, w) * Math.max(0, h);
285
+ }
286
+
287
+ function excess(inner: Rect, outer: Rect): number {
288
+ return Math.max(
289
+ outer[0] - inner[0],
290
+ outer[1] - inner[1],
291
+ inner[0] + inner[2] - (outer[0] + outer[2]),
292
+ inner[1] + inner[3] - (outer[1] + outer[3]),
293
+ );
294
+ }
295
+
296
+ /** Smallest rect painted before `text` that covers at least 30% of it. */
297
+ function container(geo: Geometry, text: number, box: Rect, rects: number[], k: number): number | null {
298
+ let best: number | null = null;
299
+ let bestArea = Infinity;
300
+ for (const index of rects) {
301
+ if (index > text || !geo.client.has(index)) continue;
302
+ const rect = geo.client.get(index)![k];
303
+ if (rect === null || rectArea(box) === 0) continue;
304
+ if (overlap(box, rect) / rectArea(box) >= 0.3 && rectArea(rect) < bestArea) {
305
+ best = index;
306
+ bestArea = rectArea(rect);
307
+ }
308
+ }
309
+ return best;
310
+ }
311
+
312
+ /** SVG `<text>` poking out of the `<rect>` painted under it; HTML text overflow. */
313
+ export function checkTextOverflow(geo: Geometry): Finding[] {
314
+ const hits = new Map<string, number[]>();
315
+ const amounts = new Map<string, number>();
316
+ const rects = [...geo.elements.values()].filter((el) => el.tag === "rect").map((el) => el.index);
317
+ for (const [index, el] of geo.elements) {
318
+ if (el.tag !== "text" || !geo.client.has(index)) continue;
319
+ geo.client.get(index)!.forEach((textBox, k) => {
320
+ if (textBox === null) return;
321
+ const box = container(geo, index, textBox, rects, k);
322
+ if (box === null) return;
323
+ const containerBox = geo.client.get(box)![k];
324
+ if (containerBox === null) return;
325
+ const ex = excess(textBox, containerBox);
326
+ if (ex > TOLERANCE) {
327
+ const key = `${index},${box}`;
328
+ (hits.get(key) ?? hits.set(key, []).get(key)!).push(k);
329
+ amounts.set(key, Math.max(amounts.get(key) ?? 0, ex));
330
+ }
331
+ });
332
+ }
333
+ const keyed = [...hits.entries()]
334
+ .map(([key, ks]) => ({ key, ks, pair: key.split(",").map(Number) as [number, number] }))
335
+ .sort((a, b) => a.pair[0] - b.pair[0] || a.pair[1] - b.pair[1]);
336
+ const out: Finding[] = keyed.map(({ key, ks, pair: [text, box] }) =>
337
+ finding(
338
+ "text-overflow",
339
+ `${geo.label(text)} overflows its container ${geo.label(box)} by up to ` +
340
+ `${fixed(amounts.get(key)!, 0)}px at ${fmtTimes(timesAt(geo, ks))}.`,
341
+ geo.label(text),
342
+ timesAt(geo, ks),
343
+ ),
344
+ );
345
+ const htmlHits = new Map<number, number[]>();
346
+ const htmlAmount = new Map<number, [number, number]>();
347
+ geo.htmlOverflow.forEach((items, k) => {
348
+ for (const [index, dx, dy] of items) {
349
+ (htmlHits.get(index) ?? htmlHits.set(index, []).get(index)!).push(k);
350
+ const [ox, oy] = htmlAmount.get(index) ?? [0, 0];
351
+ htmlAmount.set(index, [Math.max(ox, dx), Math.max(oy, dy)]);
352
+ }
353
+ });
354
+ for (const index of [...htmlHits.keys()].sort(byNumber)) {
355
+ const ks = htmlHits.get(index)!;
356
+ const [dx, dy] = htmlAmount.get(index)!;
357
+ out.push(
358
+ finding(
359
+ "text-overflow",
360
+ `${geo.label(index)} content is larger than its box (${fixed(dx, 0)}px wider, ` +
361
+ `${fixed(dy, 0)}px taller) at ${fmtTimes(timesAt(geo, ks))}.`,
362
+ geo.label(index),
363
+ timesAt(geo, ks),
364
+ ),
365
+ );
366
+ }
367
+ return out;
368
+ }
369
+
370
+ /** CSS transform animations on SVG elements without `transform-box: fill-box`. */
371
+ export function checkTransformBox(geo: Geometry): Finding[] {
372
+ const out: Finding[] = [];
373
+ const seen = new Set<string>();
374
+ for (const anim of geo.animations) {
375
+ if (anim.transform_box !== "view-box" || !anim.target || seen.has(anim.target)) continue;
376
+ seen.add(anim.target);
377
+ out.push(
378
+ finding(
379
+ "svg-transform-box",
380
+ `CSS animation '${anim.name}' on ${anim.target} animates transform with ` +
381
+ "transform-box: view-box (the SVG default), so it rotates/scales around the " +
382
+ "SVG origin, not the element. Add transform-box: fill-box; " +
383
+ "transform-origin: center.",
384
+ anim.target,
385
+ null,
386
+ ),
387
+ );
388
+ }
389
+ return out;
390
+ }
391
+
392
+ /** Render checks run on every inspection, in order. Append to add a check. */
393
+ export const CHECKS: ((geo: Geometry) => Finding[])[] = [
394
+ checkParked,
395
+ checkOutside,
396
+ checkTextOverflow,
397
+ checkTransformBox,
398
+ ];
399
+
400
+ export function runChecks(geo: Geometry): Finding[] {
401
+ const findings = CHECKS.flatMap((check) => check(geo));
402
+ // An element parked at (0,0) usually pokes out of the top-left corner too: report once.
403
+ const parked = new Set<string>();
404
+ for (const f of findings) {
405
+ if (f.code === "parked-at-origin") for (const t of f.times ?? []) parked.add(`${f.element}@${t}`);
406
+ }
407
+ return findings.filter(
408
+ (f) =>
409
+ !(
410
+ f.code === "outside-bounds" &&
411
+ f.times &&
412
+ f.times.length &&
413
+ f.times.every((t) => parked.has(`${f.element}@${t}`))
414
+ ),
415
+ );
416
+ }
package/src/checks.ts ADDED
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Static (source-level) checks, port of checks.py.
3
+ *
4
+ * Python parses with `xml.etree` / `html.parser`; here the browser's `DOMParser` does the
5
+ * parsing (no extra dependencies) and returns a plain element list, and the check logic
6
+ * below runs in Node. Keep codes, severities and messages in step with checks.py.
7
+ */
8
+
9
+ import type { Page } from "playwright-core";
10
+ import type { Finding, Severity } from "./models.js";
11
+ import { fixed } from "./pyfmt.js";
12
+
13
+ export const SVG_NS = "http://www.w3.org/2000/svg";
14
+ export const LARGE_SVG_KB = 100;
15
+ const URL_REF = /url\(\s*['"]?#([^)'"]+)['"]?\s*\)/g;
16
+ const POSITIVE_CLOCK = /^([0-9]*\.?[0-9]+)(ms|s)?$/;
17
+ const KEYFRAMES = /@keyframes[^{]*\{((?:[^{}]*\{[^}]*\})*)[^}]*\}/g;
18
+ const SVG_REF_TAGS = new Set(["use", "mpath", "textpath", "lineargradient", "radialgradient", "pattern"]);
19
+
20
+ function urlRefs(value: string): string[] {
21
+ return [...value.matchAll(URL_REF)].map((m) => m[1]);
22
+ }
23
+
24
+ function finding(severity: Severity, code: string, message: string, element: string | null = null): Finding {
25
+ return { severity, code, message, check: "static", element, times: null };
26
+ }
27
+
28
+ /** One parsed element: local tag name, attributes as `[localName, qualifiedName, value]`. */
29
+ export interface ParsedElement {
30
+ tag: string;
31
+ attrs: [string, string, string][];
32
+ /** Text content of `<style>` elements, else null. */
33
+ text: string | null;
34
+ }
35
+
36
+ export interface ParsedDocument {
37
+ /** Parser error message (XML only), else null. */
38
+ error: string | null;
39
+ rootTag: string | null;
40
+ rootNs: string | null;
41
+ /** Document order, root first. */
42
+ elements: ParsedElement[];
43
+ }
44
+
45
+ /**
46
+ * Runs in the browser. Kept free of closures: Playwright serialises it.
47
+ * @internal
48
+ */
49
+ export function parseInPage([raw, mime]: [string, "image/svg+xml" | "text/html"]): ParsedDocument {
50
+ const XMLNS = "http://www.w3.org/2000/xmlns/";
51
+ const doc = new DOMParser().parseFromString(raw, mime);
52
+ if (mime !== "text/html") {
53
+ const err = doc.getElementsByTagName("parsererror")[0];
54
+ if (err) {
55
+ const detail = err.querySelector("div");
56
+ const text = (detail ? detail.textContent : err.textContent) || "parse error";
57
+ return { error: text.trim().replace(/\s+/g, " "), rootTag: null, rootNs: null, elements: [] };
58
+ }
59
+ }
60
+ const root = doc.documentElement;
61
+ const all = mime === "text/html" ? [...doc.querySelectorAll("*")] : [root, ...root.querySelectorAll("*")];
62
+ return {
63
+ error: null,
64
+ rootTag: root ? root.localName : null,
65
+ rootNs: root ? root.namespaceURI : null,
66
+ elements: all.map((el) => ({
67
+ tag: el.localName,
68
+ attrs: [...el.attributes]
69
+ .filter((a) => a.namespaceURI !== XMLNS)
70
+ .map((a) => [a.localName, a.name, a.value] as [string, string, string]),
71
+ text: el.localName === "style" ? el.textContent : null,
72
+ })),
73
+ };
74
+ }
75
+
76
+ /** Parse `raw` with the browser's DOMParser on `page` (any page, e.g. about:blank). */
77
+ export async function parseSource(page: Page, raw: string, kind: "svg" | "html"): Promise<ParsedDocument> {
78
+ return page.evaluate(parseInPage, [raw, kind === "svg" ? "image/svg+xml" : "text/html"] as [
79
+ string,
80
+ "image/svg+xml" | "text/html",
81
+ ]);
82
+ }
83
+
84
+ function keyframesTransform(css: string): boolean {
85
+ return [...css.matchAll(KEYFRAMES)].some((m) => /\b(transform|rotate|scale|translate)\s*:/.test(m[1]));
86
+ }
87
+
88
+ /** Checks on the concatenated text of all `<style>` blocks. */
89
+ export function checkCss(cssText: string, { svg }: { svg: boolean }): Finding[] {
90
+ const out: Finding[] = [];
91
+ const css = cssText.replace(/\/\*[\s\S]*?\*\//g, "");
92
+ if (!css.trim()) return out;
93
+ if (/@import\s+url\(|https?:\/\//.test(css)) {
94
+ out.push(
95
+ finding(
96
+ "warning",
97
+ "css-external",
98
+ "CSS references an external URL/font (blocked when the SVG is used as <img>).",
99
+ ),
100
+ );
101
+ }
102
+ const animated = /\banimation(-name)?\s*:/.test(css);
103
+ if (animated && !css.includes("prefers-reduced-motion")) {
104
+ out.push(
105
+ finding(
106
+ "warning",
107
+ "no-reduced-motion",
108
+ "CSS animations present without @media (prefers-reduced-motion: reduce).",
109
+ ),
110
+ );
111
+ }
112
+ if (svg && !css.includes("transform-box")) {
113
+ const hasTransform = /\btransform\s*:/.test(css);
114
+ if (hasTransform && css.includes("transform-origin")) {
115
+ out.push(
116
+ finding(
117
+ "warning",
118
+ "transform-origin-without-box",
119
+ "CSS transform-origin used without transform-box: fill-box; may pivot " +
120
+ "unexpectedly across SVG renderers.",
121
+ ),
122
+ );
123
+ } else if (animated && keyframesTransform(css)) {
124
+ out.push(
125
+ finding(
126
+ "warning",
127
+ "transform-without-box",
128
+ "CSS @keyframes animate transform/rotate/scale but no transform-box is set; " +
129
+ "SVG elements then rotate/scale around the SVG origin (0,0). Add " +
130
+ "transform-box: fill-box; transform-origin: center.",
131
+ ),
132
+ );
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ function idFindings(ids: Map<string, number>, refs: Set<string>): Finding[] {
139
+ const out: Finding[] = [];
140
+ for (const [id, count] of ids) {
141
+ if (count > 1) out.push(finding("error", "duplicate-id", `Duplicate id='${id}' (${count} occurrences).`));
142
+ }
143
+ for (const ref of [...refs].sort()) {
144
+ if (!ids.has(ref)) out.push(finding("error", "broken-ref", `Broken internal reference '#${ref}' (no matching id).`));
145
+ }
146
+ return out;
147
+ }
148
+
149
+ const attr = (el: ParsedElement, name: string) => el.attrs.find(([local]) => local === name)?.[2];
150
+ const labelOf = (el: ParsedElement) => {
151
+ const id = attr(el, "id");
152
+ return id ? `${el.tag}#${id}` : el.tag;
153
+ };
154
+
155
+ /** Static checks for a standalone SVG document (portability, references, pitfalls). */
156
+ export function checkSvgParsed(raw: string, doc: ParsedDocument): Finding[] {
157
+ const out: Finding[] = [];
158
+ const sizeKb = Buffer.byteLength(raw, "utf8") / 1024;
159
+ if (sizeKb > LARGE_SVG_KB) {
160
+ out.push(
161
+ finding("warning", "large-file", `Large SVG (${fixed(sizeKb, 1)} KB); consider simplifying paths or defs.`),
162
+ );
163
+ }
164
+ if (doc.error !== null) return [...out, finding("error", "malformed-xml", `Malformed XML: ${doc.error}`)];
165
+ const root = doc.elements[0];
166
+ if (doc.rootTag !== "svg") {
167
+ out.push(finding("error", "not-svg", `Root element is <${doc.rootTag}>, expected <svg>.`));
168
+ }
169
+ if (doc.rootNs !== SVG_NS) {
170
+ out.push(finding("error", "missing-xmlns", 'Missing xmlns="http://www.w3.org/2000/svg".'));
171
+ }
172
+ if (!attr(root, "viewBox")) out.push(finding("error", "missing-viewbox", "Missing viewBox attribute on <svg>."));
173
+ const hasTitle = doc.elements.some((el) => el.tag === "title");
174
+ if (!(attr(root, "aria-label") || hasTitle)) {
175
+ out.push(finding("warning", "missing-title", "Missing aria-label or <title> for accessibility."));
176
+ }
177
+ const ids = new Map<string, number>();
178
+ const refs = new Set<string>();
179
+ const cssBlocks: string[] = [];
180
+ for (const el of doc.elements) {
181
+ const { tag } = el;
182
+ const id = attr(el, "id");
183
+ if (id) ids.set(id, (ids.get(id) ?? 0) + 1);
184
+ if (tag === "script") {
185
+ out.push(finding("error", "script", "Contains <script>, which is stripped by GitHub and blocked in <img>."));
186
+ }
187
+ if (tag === "foreignObject") {
188
+ out.push(
189
+ finding("warning", "foreign-object", "Contains <foreignObject>, which breaks in many <img>/SVG viewers."),
190
+ );
191
+ }
192
+ for (const [name, , value] of el.attrs) {
193
+ if (name.startsWith("on")) {
194
+ out.push(
195
+ finding("error", "event-handler", `Inline event handler '${name}' on <${tag}> (stripped in <img>).`, labelOf(el)),
196
+ );
197
+ }
198
+ if (/https?:\/\//.test(value) && name !== "xmlns") {
199
+ out.push(
200
+ finding(
201
+ "warning",
202
+ "external-url",
203
+ `External URL in ${name}='${value}' on <${tag}> (blocked in GitHub <img>).`,
204
+ labelOf(el),
205
+ ),
206
+ );
207
+ }
208
+ for (const ref of urlRefs(value)) refs.add(ref);
209
+ if (name === "href" && value.startsWith("#")) refs.add(value.slice(1));
210
+ }
211
+ if (tag === "animateMotion") {
212
+ const begin = (attr(el, "begin") ?? "").trim();
213
+ const m = POSITIVE_CLOCK.exec(begin);
214
+ if (m && parseFloat(m[1]) > 0) {
215
+ out.push(
216
+ finding(
217
+ "warning",
218
+ "positive-begin",
219
+ `<animateMotion begin='${begin}'> uses a positive delay; the parent ` +
220
+ "shape may park at (0,0) before start. Use a negative begin offset.",
221
+ ),
222
+ );
223
+ }
224
+ }
225
+ if (tag === "style" && el.text) cssBlocks.push(el.text);
226
+ }
227
+ const css = cssBlocks.join("\n");
228
+ for (const ref of urlRefs(css)) refs.add(ref);
229
+ out.push(...idFindings(ids, refs), ...checkCss(css, { svg: true }));
230
+ return out;
231
+ }
232
+
233
+ /** Static checks for an HTML document: ids, internal references, reduced motion. */
234
+ export function checkHtmlParsed(raw: string, doc: ParsedDocument): Finding[] {
235
+ const ids = new Map<string, number>();
236
+ const refs = new Set<string>();
237
+ const css: string[] = [];
238
+ for (const el of doc.elements) {
239
+ const tag = el.tag.toLowerCase();
240
+ for (const [, qualified, value] of el.attrs) {
241
+ const name = qualified.toLowerCase();
242
+ if (name === "id") ids.set(value, (ids.get(value) ?? 0) + 1);
243
+ for (const ref of urlRefs(value)) refs.add(ref);
244
+ // Only SVG-style fragment references; HTML <a href="#top"> is navigation.
245
+ if ((name === "xlink:href" || name === "href") && value.startsWith("#") && SVG_REF_TAGS.has(tag)) {
246
+ refs.add(value.slice(1));
247
+ }
248
+ }
249
+ if (tag === "style" && el.text) css.push(el.text);
250
+ }
251
+ const cssText = css.join("\n");
252
+ for (const ref of urlRefs(cssText)) refs.add(ref);
253
+ return [...idFindings(ids, refs), ...checkCss(cssText, { svg: raw.toLowerCase().includes("<svg") })];
254
+ }
255
+
256
+ /** All static findings for one source text (parsed on `page`). */
257
+ export async function staticFindings(page: Page, kind: "svg" | "html", text: string | null): Promise<Finding[]> {
258
+ if (!text) return [];
259
+ const doc = await parseSource(page, text, kind);
260
+ return kind === "svg" ? checkSvgParsed(text, doc) : checkHtmlParsed(text, doc);
261
+ }