@voila.dev/replay 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,767 @@
1
+ // Rebuilds the recorded page in a document and keeps it in step with the tape, through the DOM
2
+ // API only: nothing goes through the HTML parser, so its repairs (a table without tbody, an <a>
3
+ // in an <a>, HTML inside SVG) cannot change what is built.
4
+ //
5
+ // The tape comes from a browser nobody controls and is shown in a back office: nothing in the
6
+ // copy may run, submit or leave the page.
7
+ import { FNV_START, fnv, length, Op, type Tape } from "../format/index";
8
+
9
+ export interface MirrorHooks {
10
+ readonly pointer?: (x: number, y: number) => void;
11
+ readonly tap?: (kind: number, x: number, y: number) => void;
12
+ readonly size?: (width: number, height: number) => void;
13
+ readonly focus?: (el: Element | null) => void;
14
+ readonly print?: (ok: boolean, at: number, detail: string) => void;
15
+ }
16
+
17
+ export interface Mirror {
18
+ /** Runs the tape from `from`, up to the tick that would pass `until`. Returns where it stopped. */
19
+ run(tape: Tape, from?: number, until?: number): number;
20
+ /** Recorded time of the last tick run, ms since epoch. */
21
+ readonly time: number;
22
+ /** The number the next node made takes. */
23
+ readonly next: number;
24
+ readonly url: string;
25
+ readonly nodes: ReadonlyArray<Node | undefined>;
26
+ /** True between batches, where a checkpoint may be taken. */
27
+ readonly rest: boolean;
28
+ /** A copy of the rebuilt page and of what numbers it, to come back to without the tape. */
29
+ save(): Checkpoint;
30
+ /** Puts the page back as it was saved; the tape then runs on from where the save was. */
31
+ restore(cp: Checkpoint): void;
32
+ }
33
+
34
+ /**
35
+ * What a copy of the document does not carry is kept beside it: the rules of constructed sheets,
36
+ * which roots adopt them, the frames' documents, canvas pixels, modal dialogs and open popovers,
37
+ * scroll positions, and the last size and pointer.
38
+ */
39
+ export interface Checkpoint {
40
+ readonly holder: Document;
41
+ readonly nodes: ReadonlyArray<Node | undefined>;
42
+ readonly frames: ReadonlyMap<Element, Node>;
43
+ readonly sheets: ReadonlyArray<string | undefined>;
44
+ readonly adopted: ReadonlyArray<readonly [Node, ReadonlyArray<number>]>;
45
+ readonly pixels: ReadonlyArray<readonly [Node, HTMLCanvasElement]>;
46
+ readonly shown: ReadonlyArray<readonly [Node, number]>;
47
+ readonly scrolls: ReadonlyArray<readonly [Node, number, number]>;
48
+ readonly seq: number;
49
+ readonly base: string;
50
+ readonly now: number;
51
+ readonly mode: number;
52
+ readonly size: readonly [number, number] | null;
53
+ readonly pointer: readonly [number, number] | null;
54
+ }
55
+
56
+ const SVG = "http://www.w3.org/2000/svg";
57
+ const MATHML = "http://www.w3.org/1998/Math/MathML";
58
+ const XLINK = "http://www.w3.org/1999/xlink";
59
+ const XML = "http://www.w3.org/XML/1998/namespace";
60
+ const ADDRESS = /^(src|href|poster|action|formaction|data|xlink:href|cite|background)$/i;
61
+ const CSS_URL = /url\(\s*(['"]?)(?!data:|#|blob:)([^'")]+)\1\s*\)/g;
62
+ const SAFE_URL = /^(https?:|data:image\/|blob:|#|mailto:|tel:)/i;
63
+ /** Elements that would act inside the copy: built inert, under another name, so numbering holds. */
64
+ const INERT = /^(script|base|object|embed|portal)$/i;
65
+
66
+ const NODE = Node.prototype;
67
+ const firstChild = Object.getOwnPropertyDescriptor(NODE, "firstChild")?.get as (this: Node) => Node | null;
68
+ const nextSibling = Object.getOwnPropertyDescriptor(NODE, "nextSibling")?.get as (this: Node) => Node | null;
69
+ const localName = Object.getOwnPropertyDescriptor(Element.prototype, "localName")?.get as (this: Element) => string;
70
+ // Called through the prototype: a form holding a field named `setAttribute` hides the method.
71
+ const EL = Element.prototype;
72
+ const setAttr = (el: Element, name: string, value: string) => EL.setAttribute.call(el, name, value);
73
+ const setAttrNS = (el: Element, ns: string | null, name: string, value: string) =>
74
+ EL.setAttributeNS.call(el, ns, name, value);
75
+ const getAttr = (el: Element, name: string) => EL.getAttribute.call(el, name);
76
+ const hasAttr = (el: Element, name: string) => EL.hasAttribute.call(el, name);
77
+ const removeAttr = (el: Element, name: string) => EL.removeAttribute.call(el, name);
78
+ /** Text nodes the player adds on its own (the rules of a <style> filled by script). */
79
+ const added = new WeakSet<Node>();
80
+
81
+ export function mirror(doc: Document, hooks: MirrorHooks = {}): Mirror {
82
+ let nodes: Array<Node | undefined> = [];
83
+ let sheets: Array<CSSStyleSheet | undefined> = [];
84
+ let stack: Array<{ p: Node; a: Node | null }> = [];
85
+ let seq = 0;
86
+ let base = "";
87
+ let now = 0;
88
+ let size: [number, number] | null = null;
89
+ let pointer: [number, number] | null = null;
90
+ // What a copy of the tree would lose, noted as the tape does it, for a checkpoint to keep.
91
+ let drawn = new Set<Node>();
92
+ let scrolled = new Set<Node>();
93
+ let opened = new Set<Node>();
94
+ let adopting = new Set<Node>();
95
+ const win = () => doc.defaultView as (Window & typeof globalThis) | null;
96
+
97
+ const absolute = (url: string, from = base) => {
98
+ try {
99
+ return new URL(url, from).href;
100
+ } catch {
101
+ return url;
102
+ }
103
+ };
104
+ const css = (text: string, from = base) =>
105
+ text.replace(CSS_URL, (_m, _q, url: string) => `url("${absolute(url, from)}")`);
106
+ const local = (el: Element) => localName.call(el);
107
+
108
+ function add(n: Node) {
109
+ const top = stack[stack.length - 1];
110
+ if (!top) return;
111
+ try {
112
+ top.p.insertBefore(n, top.a && top.a.parentNode === top.p ? top.a : null);
113
+ } catch {
114
+ try {
115
+ top.p.appendChild(n);
116
+ } catch {
117
+ // A node the browser refuses there (a second doctype): kept out of the tree.
118
+ }
119
+ }
120
+ }
121
+
122
+ function set(el: Element, name: string, value: string) {
123
+ if (/^on/i.test(name) || name.toLowerCase() === "http-equiv") return;
124
+ const tag = local(el);
125
+ if (tag === "iframe" && (name === "src" || name === "srcdoc")) return;
126
+ if (ADDRESS.test(name)) {
127
+ value = absolute(value);
128
+ if (!SAFE_URL.test(value)) value = "about:blank";
129
+ } else if (name === "srcset")
130
+ value = value
131
+ .split(",")
132
+ .map((part) => {
133
+ const [url, ...rest] = part.trim().split(/\s+/);
134
+ return [absolute(url || ""), ...rest].join(" ");
135
+ })
136
+ .join(", ");
137
+ else if (name === "style") value = css(value);
138
+ else if (tag === "a" && name === "target") return;
139
+ try {
140
+ if (name.startsWith("xlink:")) setAttrNS(el, XLINK, name, value);
141
+ else if (name.startsWith("xml:")) setAttrNS(el, XML, name, value);
142
+ else setAttr(el, name, value);
143
+ } catch {
144
+ // A name the DOM refuses (`@click`, `:class`): kept aside, never shown.
145
+ try {
146
+ setAttrNS(el, null, name, value);
147
+ } catch {}
148
+ }
149
+ }
150
+
151
+ function element(name: string): Element {
152
+ const space = name.indexOf(" ");
153
+ try {
154
+ if (space < 0) {
155
+ if (INERT.test(name)) return doc.createElement(`replay-${name}`);
156
+ return doc.createElement(name);
157
+ }
158
+ const ns = name.slice(0, space);
159
+ const tag = name.slice(space + 1);
160
+ return doc.createElementNS(ns === "s" ? SVG : ns === "m" ? MATHML : ns, tag);
161
+ } catch {
162
+ return doc.createElement("replay-unknown");
163
+ }
164
+ }
165
+
166
+ function open(p: Node) {
167
+ stack.push({ p, a: null });
168
+ }
169
+
170
+ function sheetText(node: Node | undefined, text: string): void {
171
+ if (!node || node.nodeType !== 1) return;
172
+ const el = node as Element;
173
+ if (local(el) === "link") {
174
+ const from = absolute(getAttr(el, "href") || "");
175
+ const blob = URL.createObjectURL(new Blob([css(text, from)], { type: "text/css" }));
176
+ setAttr(el, "href", blob);
177
+ return;
178
+ }
179
+ // A <style> filled by script: its text is put in a text node of its own.
180
+ let t: Node | null = null;
181
+ for (let c = el.firstChild; c; c = c.nextSibling) if (c.nodeType === 3) t = c;
182
+ if (t) (t as Text).data = css(text);
183
+ else {
184
+ const node = doc.createTextNode(css(text));
185
+ added.add(node);
186
+ el.appendChild(node);
187
+ }
188
+ }
189
+
190
+ function constructed(k: number, text: string) {
191
+ const W = win();
192
+ if (!W?.CSSStyleSheet) return;
193
+ let s = sheets[k];
194
+ if (!s) {
195
+ try {
196
+ s = new W.CSSStyleSheet();
197
+ } catch {
198
+ return;
199
+ }
200
+ sheets[k] = s;
201
+ }
202
+ try {
203
+ s.replaceSync(css(text));
204
+ } catch {}
205
+ }
206
+
207
+ function reset(mode: number) {
208
+ // The mode of a document is set when it is parsed: written first, then emptied.
209
+ doc.open();
210
+ doc.write(mode === 1 ? "" : "<!DOCTYPE html>");
211
+ doc.close();
212
+ while (doc.firstChild) doc.removeChild(doc.firstChild);
213
+ nodes = [undefined, doc];
214
+ sheets = [];
215
+ drawn = new Set();
216
+ scrolled = new Set();
217
+ opened = new Set();
218
+ adopting = new Set();
219
+ seq = 1;
220
+ stack = [{ p: doc, a: null }];
221
+ }
222
+
223
+ function run(tape: Tape, from = 0, until = Number.POSITIVE_INFINITY) {
224
+ let i = from;
225
+ while (i < tape.length) {
226
+ const at = i;
227
+ const n = length(tape, i);
228
+ if (n < 0) throw new Error(`replay: bad op at ${i}`);
229
+ const op = tape[i] as number;
230
+ const a = (k: number) => tape[at + k] as never;
231
+ if (op === Op.TICK && now + (a(1) as number) > until) return at;
232
+ i += n;
233
+ switch (op) {
234
+ case Op.X:
235
+ stack.pop();
236
+ break;
237
+ case Op.E: {
238
+ const el = element(a(1));
239
+ for (let k = 3; k < n; k += 2) set(el, a(k), a(k + 1));
240
+ nodes[++seq] = el;
241
+ add(el);
242
+ open(el);
243
+ break;
244
+ }
245
+ case Op.T: {
246
+ const top = stack[stack.length - 1]?.p as Element | undefined;
247
+ const data: string = a(1);
248
+ const inStyle = top?.nodeType === 1 && local(top) === "style";
249
+ const t = doc.createTextNode(inStyle ? css(data) : data);
250
+ nodes[++seq] = t;
251
+ add(t);
252
+ break;
253
+ }
254
+ case Op.D: {
255
+ let t: Node;
256
+ try {
257
+ t = doc.implementation.createDocumentType(a(1), a(2), a(3));
258
+ } catch {
259
+ t = doc.createComment("doctype");
260
+ }
261
+ nodes[++seq] = t;
262
+ add(t);
263
+ break;
264
+ }
265
+ case Op.B: {
266
+ const el = element(a(1)) as HTMLElement;
267
+ setAttr(
268
+ el,
269
+ "style",
270
+ `display:inline-block;width:${+a(2) || 0}px;height:${+a(3) || 0}px;background:repeating-linear-gradient(45deg,#0001 0 8px,#0002 8px 16px)`,
271
+ );
272
+ setAttr(el, "data-replay-blocked", "");
273
+ nodes[++seq] = el;
274
+ add(el);
275
+ break;
276
+ }
277
+ case Op.TPL: {
278
+ const top = stack[stack.length - 1]?.p as HTMLTemplateElement | undefined;
279
+ const content = top && "content" in top ? top.content : doc.createDocumentFragment();
280
+ nodes[++seq] = content;
281
+ open(content);
282
+ break;
283
+ }
284
+ case Op.SHADOW: {
285
+ const host = stack[stack.length - 1]?.p as Element | undefined;
286
+ let root: Node;
287
+ try {
288
+ root = (host as Element).shadowRoot || (host as Element).attachShadow({ mode: "open" });
289
+ while (root.firstChild) root.removeChild(root.firstChild);
290
+ } catch {
291
+ root = doc.createDocumentFragment();
292
+ }
293
+ nodes[++seq] = root;
294
+ open(root);
295
+ break;
296
+ }
297
+ case Op.FRAME: {
298
+ const frame = stack[stack.length - 1]?.p as HTMLIFrameElement | undefined;
299
+ let inner: Node | null = null;
300
+ try {
301
+ inner = frame?.contentDocument || null;
302
+ if (inner) while (inner.firstChild) inner.removeChild(inner.firstChild);
303
+ } catch {}
304
+ const node = inner || doc.createDocumentFragment();
305
+ nodes[++seq] = node;
306
+ open(node);
307
+ break;
308
+ }
309
+ case Op.R: {
310
+ const node = nodes[a(1)];
311
+ if (node) add(node);
312
+ break;
313
+ }
314
+ case Op.INS: {
315
+ const p = nodes[a(1)];
316
+ const anchor = a(2) ? nodes[a(2)] : null;
317
+ // A missing parent still takes its children, out of the page.
318
+ stack.push({ p: p || doc.createDocumentFragment(), a: anchor || null });
319
+ break;
320
+ }
321
+ case Op.DEL: {
322
+ const node = nodes[a(1)];
323
+ node?.parentNode?.removeChild(node);
324
+ break;
325
+ }
326
+ case Op.ATTR: {
327
+ const el = nodes[a(1)] as Element | undefined;
328
+ const name: string = a(2);
329
+ const value: string | null = a(3);
330
+ if (!el || el.nodeType !== 1) break;
331
+ if (value === null) {
332
+ try {
333
+ removeAttr(el, name);
334
+ } catch {}
335
+ } else set(el, name, value);
336
+ break;
337
+ }
338
+ case Op.TEXT: {
339
+ const t = nodes[a(1)] as Text | undefined;
340
+ if (!t || t.nodeType !== 3) break;
341
+ const data: string = a(2);
342
+ t.data = t.parentElement && local(t.parentElement) === "style" ? css(data) : data;
343
+ break;
344
+ }
345
+ case Op.VAL: {
346
+ const el = nodes[a(1)] as HTMLInputElement & HTMLOptionElement;
347
+ const v: string | number = a(2);
348
+ if (!el || el.nodeType !== 1) break;
349
+ try {
350
+ if (local(el) === "option") {
351
+ const select = el.parentElement?.closest("select") as HTMLSelectElement | null;
352
+ // Unselecting the one option of a single select would select the first one again.
353
+ if (!v && el.selected && select && !select.multiple) select.selectedIndex = -1;
354
+ else el.selected = !!v;
355
+ }
356
+ else if (typeof v === "number") el.checked = !!v;
357
+ else el.value = v;
358
+ } catch {}
359
+ break;
360
+ }
361
+ case Op.OPEN: {
362
+ const el = nodes[a(1)] as HTMLDialogElement | undefined;
363
+ const state: number = a(2);
364
+ if (!el || el.nodeType !== 1) break;
365
+ opened.add(el);
366
+ try {
367
+ if (local(el) === "dialog") {
368
+ if (el.open) el.close();
369
+ if (state === 2 && el.isConnected) el.showModal();
370
+ else if (state === 1) el.show();
371
+ } else if ("showPopover" in el) {
372
+ const p = el as unknown as { showPopover(): void; hidePopover(): void };
373
+ state ? p.showPopover() : p.hidePopover();
374
+ }
375
+ } catch {}
376
+ break;
377
+ }
378
+ case Op.SHEET: {
379
+ const id: number = a(1);
380
+ if (id) sheetText(nodes[id], a(3));
381
+ else constructed(a(2), a(3));
382
+ break;
383
+ }
384
+ case Op.RULE: {
385
+ const s = sheets[a(1) as number];
386
+ const path = String(a(2)).split(".").map(Number);
387
+ const text: string | null = a(3);
388
+ try {
389
+ // biome-ignore lint/suspicious/noExplicitAny: grouping rules hold rules too.
390
+ let list: any = s;
391
+ for (const k of path.slice(0, -1)) list = list?.cssRules[k];
392
+ const last = path[path.length - 1] as number;
393
+ if (text === null) list?.deleteRule(last);
394
+ else list?.insertRule(css(text), last);
395
+ } catch {}
396
+ break;
397
+ }
398
+ case Op.ADOPT: {
399
+ const root = nodes[a(1)] as Document | ShadowRoot | undefined;
400
+ const list: Array<CSSStyleSheet> = [];
401
+ for (let k = 3; k < n; k++) {
402
+ const s = sheets[a(k) as number];
403
+ if (s) list.push(s);
404
+ }
405
+ try {
406
+ if (root && "adoptedStyleSheets" in root) {
407
+ root.adoptedStyleSheets = list;
408
+ adopting.add(root);
409
+ }
410
+ } catch {}
411
+ break;
412
+ }
413
+ case Op.TICK:
414
+ now += a(1) as number;
415
+ break;
416
+ case Op.MOVE:
417
+ pointer = [a(1), a(2)];
418
+ hooks.pointer?.(a(1), a(2));
419
+ break;
420
+ case Op.TAP:
421
+ hooks.tap?.(a(1), a(3), a(4));
422
+ break;
423
+ case Op.SCROLL: {
424
+ const id: number = a(1);
425
+ const x: number = a(2);
426
+ const y: number = a(3);
427
+ try {
428
+ if (nodes[id]) scrolled.add(nodes[id] as Node);
429
+ if (id === 1) win()?.scrollTo(x, y);
430
+ else {
431
+ const el = nodes[id] as Element | undefined;
432
+ if (el?.nodeType === 9) (el as unknown as Document).defaultView?.scrollTo(x, y);
433
+ else if (el?.nodeType === 1) {
434
+ el.scrollLeft = x;
435
+ el.scrollTop = y;
436
+ }
437
+ }
438
+ } catch {}
439
+ break;
440
+ }
441
+ case Op.SIZE:
442
+ size = [a(1), a(2)];
443
+ hooks.size?.(a(1), a(2));
444
+ break;
445
+ case Op.FOCUS: {
446
+ const el = a(1) ? (nodes[a(1)] as Element | undefined) : undefined;
447
+ hooks.focus?.(el?.nodeType === 1 ? el : null);
448
+ break;
449
+ }
450
+ case Op.META:
451
+ base = a(2);
452
+ now = a(3);
453
+ reset(a(6));
454
+ size = [a(4), a(5)];
455
+ hooks.size?.(a(4), a(5));
456
+ break;
457
+ case Op.PRINT: {
458
+ const [count, hash] = fingerprint(doc);
459
+ hooks.print?.(count === a(1) && hash === a(2), now, `${a(1)} nœuds enregistrés, ${count} rejoués`);
460
+ break;
461
+ }
462
+ case Op.SHOT: {
463
+ const el = nodes[a(2)] as HTMLCanvasElement | undefined;
464
+ const shot: string = a(3);
465
+ if (!el || typeof el.getContext !== "function" || !/^data:image\//.test(shot)) break;
466
+ drawn.add(el);
467
+ const image = new Image();
468
+ image.onload = () => {
469
+ const c = el.getContext("2d");
470
+ c?.clearRect(0, 0, el.width, el.height);
471
+ c?.drawImage(image, 0, 0, el.width, el.height);
472
+ };
473
+ image.src = shot;
474
+ break;
475
+ }
476
+ // HIDE, END, ERR and the framed ops this player does not know: nothing to build.
477
+ }
478
+ }
479
+ return i;
480
+ }
481
+
482
+ function save(): Checkpoint {
483
+ const holder = blank(doc);
484
+ const { map, frames } = copy(nodes, doc, holder, (f) => (f as HTMLIFrameElement).contentDocument);
485
+ const adopted: Array<readonly [Node, ReadonlyArray<number>]> = [];
486
+ const pixels: Array<readonly [Node, HTMLCanvasElement]> = [];
487
+ const shown: Array<readonly [Node, number]> = [];
488
+ const scrolls: Array<readonly [Node, number, number]> = [];
489
+ for (const n of adopting) {
490
+ const at = map.get(n);
491
+ const list = (n as Document | ShadowRoot).adoptedStyleSheets;
492
+ if (at && list?.length) adopted.push([at, list.map((x) => sheets.indexOf(x))]);
493
+ }
494
+ for (const n of scrolled) {
495
+ const c = map.get(n);
496
+ if (!c) continue;
497
+ if (n.nodeType === 9) {
498
+ const w = (n as Document).defaultView;
499
+ if (w) scrolls.push([c, w.scrollX, w.scrollY]);
500
+ } else if (n.nodeType === 1) scrolls.push([c, (n as Element).scrollLeft, (n as Element).scrollTop]);
501
+ }
502
+ for (const n of opened) {
503
+ const c = map.get(n);
504
+ try {
505
+ if (c && local(n as Element) === "dialog" && (n as Element).matches(":modal")) shown.push([c, 2]);
506
+ else if (c && (n as Element).matches(":popover-open")) shown.push([c, 1]);
507
+ } catch {}
508
+ }
509
+ for (const n of drawn) {
510
+ const c = map.get(n);
511
+ const from = n as HTMLCanvasElement;
512
+ if (!c || !from.width || !from.height) continue;
513
+ const pixel = doc.createElement("canvas");
514
+ pixel.width = from.width;
515
+ pixel.height = from.height;
516
+ try {
517
+ pixel.getContext("2d")?.drawImage(from, 0, 0);
518
+ pixels.push([c, pixel]);
519
+ } catch {}
520
+ }
521
+ return {
522
+ holder,
523
+ nodes: nodes.map((n) => n && map.get(n)),
524
+ frames,
525
+ sheets: sheets.map((s) => s && rulesOf(s)),
526
+ adopted,
527
+ pixels,
528
+ shown,
529
+ scrolls,
530
+ seq,
531
+ base,
532
+ now,
533
+ mode: doc.compatMode === "BackCompat" ? 1 : 0,
534
+ size,
535
+ pointer,
536
+ };
537
+ }
538
+
539
+ function restore(cp: Checkpoint) {
540
+ reset(cp.mode);
541
+ const { map } = copy(cp.nodes, cp.holder, doc, (f) => cp.frames.get(f) || null);
542
+ nodes = cp.nodes.map((n) => n && map.get(n));
543
+ seq = cp.seq;
544
+ base = cp.base;
545
+ now = cp.now;
546
+ cp.sheets.forEach((text, k) => {
547
+ if (text !== undefined) constructed(k, text);
548
+ });
549
+ for (const [root, list] of cp.adopted) {
550
+ const r = map.get(root) as Document | ShadowRoot | undefined;
551
+ try {
552
+ if (r && "adoptedStyleSheets" in r) {
553
+ r.adoptedStyleSheets = list.map((k) => sheets[k]).filter(Boolean) as Array<CSSStyleSheet>;
554
+ adopting.add(r);
555
+ }
556
+ } catch {}
557
+ }
558
+ for (const [node, pixel] of cp.pixels) {
559
+ const el = map.get(node) as HTMLCanvasElement | undefined;
560
+ try {
561
+ if (!el) continue;
562
+ el.getContext("2d")?.drawImage(pixel, 0, 0);
563
+ drawn.add(el);
564
+ } catch {}
565
+ }
566
+ for (const [node, state] of cp.shown) {
567
+ const el = map.get(node) as (HTMLDialogElement & { showPopover(): void }) | undefined;
568
+ try {
569
+ if (!el?.isConnected) continue;
570
+ opened.add(el);
571
+ if (state === 2) {
572
+ if (el.open) el.close();
573
+ el.showModal();
574
+ } else el.showPopover();
575
+ } catch {}
576
+ }
577
+ for (const [node, x, y] of cp.scrolls) {
578
+ const n = map.get(node);
579
+ if (n) scrolled.add(n);
580
+ try {
581
+ if (n?.nodeType === 9) (n as Document).defaultView?.scrollTo(x, y);
582
+ else if (n?.nodeType === 1) {
583
+ (n as Element).scrollLeft = x;
584
+ (n as Element).scrollTop = y;
585
+ }
586
+ } catch {}
587
+ }
588
+ size = cp.size && [cp.size[0], cp.size[1]];
589
+ pointer = cp.pointer && [cp.pointer[0], cp.pointer[1]];
590
+ if (size) hooks.size?.(size[0], size[1]);
591
+ if (pointer) hooks.pointer?.(pointer[0], pointer[1]);
592
+ }
593
+
594
+ return {
595
+ run,
596
+ save,
597
+ restore,
598
+ get rest() {
599
+ return stack.length === 1;
600
+ },
601
+ get time() {
602
+ return now;
603
+ },
604
+ get next() {
605
+ return seq + 1;
606
+ },
607
+ get url() {
608
+ return base;
609
+ },
610
+ get nodes() {
611
+ return nodes;
612
+ },
613
+ };
614
+ }
615
+
616
+ /** An empty document of no window: what it holds neither loads nor runs. */
617
+ function blank(from: Document): Document {
618
+ const d = from.implementation.createHTMLDocument("");
619
+ while (d.firstChild) d.removeChild(d.firstChild);
620
+ return d;
621
+ }
622
+
623
+ function rulesOf(sheet: CSSStyleSheet): string {
624
+ let text = "";
625
+ try {
626
+ for (const rule of Array.from(sheet.cssRules)) text += rule.cssText;
627
+ } catch {}
628
+ return text;
629
+ }
630
+
631
+ /**
632
+ * Copies every numbered node of `from` into `into`, the trees whole and the detached ones too,
633
+ * and returns which copy is which. Shadow roots, template contents and frames' documents are
634
+ * walked by hand, since cloning skips them; field state is set where cloning loses it. Nodes are
635
+ * put in place before their children, so a frame in a live document has its document to fill.
636
+ */
637
+ function copy(
638
+ from: ReadonlyArray<Node | undefined>,
639
+ root: Document,
640
+ into: Document,
641
+ inner: (frame: Element) => Node | null,
642
+ ): { map: Map<Node, Node>; frames: Map<Element, Node> } {
643
+ const map = new Map<Node, Node>();
644
+ const frames = new Map<Element, Node>();
645
+ const owner = new Map<Node, Node>();
646
+ for (const n of from)
647
+ if (n?.nodeType === 1 && localName.call(n as Element) === "template")
648
+ owner.set((n as HTMLTemplateElement).content, n);
649
+
650
+ const children = (s: Node, d: Node) => {
651
+ for (let c = firstChild.call(s); c; c = nextSibling.call(c)) node(c, d);
652
+ };
653
+ function node(s: Node, parent: Node | null): void {
654
+ let c: Node;
655
+ try {
656
+ // WebKit refuses to import a doctype.
657
+ const t = s as DocumentType;
658
+ c =
659
+ s.nodeType === 10
660
+ ? into.implementation.createDocumentType(t.name, t.publicId, t.systemId)
661
+ : into.importNode(s, false);
662
+ } catch {
663
+ return;
664
+ }
665
+ map.set(s, c);
666
+ if (added.has(s)) added.add(c);
667
+ if (parent)
668
+ try {
669
+ parent.appendChild(c);
670
+ } catch {}
671
+ if (s.nodeType !== 1) return;
672
+ const el = s as Element;
673
+ const to = c as Element;
674
+ const tag = localName.call(el);
675
+ if (tag === "template" && "content" in el) {
676
+ const content = (to as HTMLTemplateElement).content;
677
+ map.set((el as HTMLTemplateElement).content, content);
678
+ children((el as HTMLTemplateElement).content, content);
679
+ }
680
+ const shadow = el.shadowRoot;
681
+ if (shadow)
682
+ try {
683
+ const r = to.shadowRoot || to.attachShadow({ mode: "open" });
684
+ map.set(shadow, r);
685
+ children(shadow, r);
686
+ } catch {}
687
+ if (tag === "iframe") {
688
+ const i = inner(el);
689
+ if (i) {
690
+ let d: Node | null = null;
691
+ try {
692
+ d = (to as HTMLIFrameElement).contentDocument;
693
+ } catch {}
694
+ if (d) while (d.firstChild) d.removeChild(d.firstChild);
695
+ else d = blank(into);
696
+ map.set(i, d);
697
+ frames.set(to, d);
698
+ children(i, d);
699
+ }
700
+ }
701
+ children(el, to);
702
+ // biome-ignore lint/suspicious/noExplicitAny: form controls.
703
+ const a = el as any;
704
+ // biome-ignore lint/suspicious/noExplicitAny: form controls.
705
+ const b = to as any;
706
+ try {
707
+ if (tag === "input" || tag === "textarea") {
708
+ if (b.value !== a.value && a.type !== "file") b.value = a.value;
709
+ if (b.checked !== a.checked) b.checked = a.checked;
710
+ } else if (tag === "select") {
711
+ if (a.multiple || a.size > 1) {
712
+ for (let k = 0; k < a.options.length; k++)
713
+ if (b.options[k] && b.options[k].selected !== a.options[k].selected) b.options[k].selected = a.options[k].selected;
714
+ } else if (b.selectedIndex !== a.selectedIndex) b.selectedIndex = a.selectedIndex;
715
+ } else if (tag === "option" && !el.parentElement?.closest("select") && b.selected !== a.selected)
716
+ b.selected = a.selected;
717
+ } catch {}
718
+ }
719
+
720
+ map.set(root, into);
721
+ children(root, into);
722
+ // The nodes out of the page: each tree from its top, through shadow hosts and templates.
723
+ for (const n of from) {
724
+ if (!n || map.has(n)) continue;
725
+ let top = n;
726
+ for (;;) {
727
+ // `host` only on a shadow root: on a link it is the address's host.
728
+ const up: Node | null | undefined =
729
+ top.parentNode || (top.nodeType === 11 ? (top as ShadowRoot).host : null) || owner.get(top);
730
+ if (!up) break;
731
+ top = up;
732
+ }
733
+ if (map.has(top)) continue;
734
+ if (top.nodeType === 9 || top.nodeType === 11) {
735
+ const d = top.nodeType === 9 ? blank(into) : into.createDocumentFragment();
736
+ map.set(top, d);
737
+ children(top, d);
738
+ } else node(top, null);
739
+ }
740
+ return { map, frames };
741
+ }
742
+
743
+ /** The PRINT of a rebuilt document, as the recorder computes it of the page. */
744
+ export function fingerprint(root: Node): [number, number] {
745
+ let count = 0;
746
+ let h = FNV_START;
747
+ const walk = (n: Node) => {
748
+ for (let c = firstChild.call(n); c; c = nextSibling.call(c)) {
749
+ const type = c.nodeType;
750
+ if ((type !== 1 && type !== 3 && type !== 10) || added.has(c)) continue;
751
+ count++;
752
+ h = fnv(h, type);
753
+ if (type === 1) {
754
+ const el = c as Element;
755
+ let tag = localName.call(el);
756
+ if (tag.startsWith("replay-") && tag !== "replay-unknown") tag = tag.slice(7);
757
+ h = fnv(h, tag.length);
758
+ h = fnv(h, tag.charCodeAt(0));
759
+ if (hasAttr(el, "data-replay-blocked")) continue;
760
+ if (tag === "template" && "content" in el) walk((el as HTMLTemplateElement).content);
761
+ walk(el);
762
+ }
763
+ }
764
+ };
765
+ walk(root);
766
+ return [count, h];
767
+ }