@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,1042 @@
1
+ // The recorder. It walks the page once into a tape, then keeps the tape in step: the
2
+ // MutationObserver only notes what changed, and the page is read at rest, at most every
3
+ // `rate` ms. What the visitor does (pointer, taps, scroll, focus, size) is written at once,
4
+ // with its own tick, never sampled with the DOM.
5
+ //
6
+ // Masking is decided here, for every node, before any module sees it: a module serializes
7
+ // through `kit.ser`, which applies the same rule.
8
+ import { End, FNV_START, fnv, Op, type Tape, VERSION } from "../format/index";
9
+ import { type Natives, natives } from "./natives";
10
+
11
+ export type Mask = "inputs" | "text" | "none";
12
+ /** 0 clear, 1 masked, 2 blocked */
13
+ export type Zone = 0 | 1 | 2;
14
+
15
+ export interface Options {
16
+ /** What is hidden: `inputs` (what is typed, the default), `text` (every text too), `none`. */
17
+ readonly mask?: Mask;
18
+ /** Text and attributes under an element with this attribute are recorded as stars. */
19
+ readonly maskAttr?: string;
20
+ /** An element with this attribute is recorded as an empty box of its size. */
21
+ readonly blockAttr?: string;
22
+ /** A field under this attribute is recorded in clear (never a password or a card number). */
23
+ readonly unmaskAttr?: string;
24
+ /** The page is read at most once per this many milliseconds. */
25
+ readonly rate?: number;
26
+ /** Bytes of tape, roughly, a page view may take before recording stops. */
27
+ readonly budget?: number;
28
+ /** Milliseconds between two fingerprints of the page (PRINT); 0: none. */
29
+ readonly printEvery?: number;
30
+ /** Milliseconds a read of the mutations may take before it hands back to the page. */
31
+ readonly slice?: number;
32
+ readonly modules?: ReadonlyArray<Module>;
33
+ }
34
+
35
+ export interface Kit {
36
+ readonly w: Window;
37
+ readonly d: Document;
38
+ readonly native: Natives;
39
+ /** Serializes a node under a zone, through the masking rule. */
40
+ readonly ser: (n: Node, zone: Zone) => void;
41
+ readonly push: (...tokens: Tape) => void;
42
+ /** Puts a tick on the tape when time went by. */
43
+ readonly stamp: () => void;
44
+ readonly id: (n: Node) => number | undefined;
45
+ /** Numbers a root (a shadow root, a frame's document) and ties it to its host. */
46
+ readonly take: (root: Node, host: Element) => number;
47
+ readonly zone: (n: Node) => Zone;
48
+ /** The number of a stylesheet, given once per sheet and page view. */
49
+ readonly sheet: (s: CSSStyleSheet) => number;
50
+ readonly sheetKnown: (s: CSSStyleSheet) => boolean;
51
+ readonly observe: (root: Node) => void;
52
+ readonly listen: (root: Document | ShadowRoot) => void;
53
+ /** Records an element again from scratch, at the next read. */
54
+ readonly redo: (el: Element) => void;
55
+ /** Asks for a read at rest. */
56
+ readonly dirty: () => void;
57
+ readonly masked: (s: string) => string;
58
+ }
59
+
60
+ export interface Module {
61
+ readonly name: string;
62
+ /** Once, as the recorder starts. */
63
+ setup?(kit: Kit): void;
64
+ /** On each element, once its attributes are on the tape and before its children. */
65
+ onElement?(el: Element, zone: Zone): void;
66
+ /** The tree an element holds besides its children: a shadow root, a frame's document. */
67
+ inner?(n: Node): Node | null | undefined;
68
+ /** At the end of each read at rest. */
69
+ onSync?(): void;
70
+ /** At the end of each snapshot. */
71
+ onSnap?(): void;
72
+ onStop?(): void;
73
+ }
74
+
75
+ export interface Snapshot {
76
+ readonly tape: Tape;
77
+ /** Where the tape can be cut into pieces that stay the same from one visitor to the next. */
78
+ readonly cuts: ReadonlyArray<number>;
79
+ readonly base: number;
80
+ readonly startedAt: number;
81
+ readonly endedAt: number;
82
+ }
83
+
84
+ export interface Drained {
85
+ readonly tape: Tape;
86
+ /** The number the first node made in this tape takes. */
87
+ readonly base: number;
88
+ readonly startedAt: number;
89
+ readonly endedAt: number;
90
+ }
91
+
92
+ export interface Recorder {
93
+ /** Records the page as it is and starts numbering nodes again. */
94
+ snap(): Snapshot;
95
+ /** What happened since the last call. */
96
+ drain(): Drained;
97
+ /** Stops; `reason` is written on the tape, for the next drain. */
98
+ stop(reason?: End): void;
99
+ readonly stopped: boolean;
100
+ /** True when the next thing to send must be a new snapshot: a module failed mid-way, or the page came back from the back/forward cache. */
101
+ readonly needsSnap: boolean;
102
+ }
103
+
104
+ const HTML = "http://www.w3.org/1999/xhtml";
105
+ const SVG = "http://www.w3.org/2000/svg";
106
+ const MATHML = "http://www.w3.org/1998/Math/MathML";
107
+ const STARS = "******";
108
+ const NOT_TYPED = /^(button|submit|reset|image)$/;
109
+ const TOGGLE = /^(checkbox|radio)$/;
110
+ const SENSITIVE_AUTOCOMPLETE = /cc-|one-time-code|password/i;
111
+ /** Attributes that stay in clear in a masked zone: they say nothing about the visitor. */
112
+ const PLAIN =
113
+ /^(class|id|style|type|role|width|height|src|srcset|sizes|href|rel|media|dir|lang|hidden|disabled|checked|selected|open|colspan|rowspan|for|name|contenteditable|tabindex|viewbox|d|fill|stroke|x|y|cx|cy|r|rx|ry|points|transform|xmlns|slot|part|draggable|loading|decoding|crossorigin|referrerpolicy|async|defer|multiple|readonly|required|min|max|step|autocomplete|inputmode|popover)$/i;
114
+
115
+ /** The recorder starts on Safari 15.4, Chrome 92, Firefox 90 and later: `Array.prototype.at`. */
116
+ export function supported(w: Window): boolean {
117
+ const W = w as Window & typeof globalThis;
118
+ return (
119
+ typeof W.Array?.prototype.at === "function" &&
120
+ typeof W.MutationObserver === "function" &&
121
+ typeof W.WeakMap === "function"
122
+ );
123
+ }
124
+
125
+ export function record(w: Window, o: Options = {}): Recorder | null {
126
+ if (!supported(w)) return null;
127
+ const d = w.document;
128
+ const N = natives(w);
129
+ const mode: Mask = o.mask || "inputs";
130
+ const maskAttr = o.maskAttr || "data-va-mask";
131
+ const blockAttr = o.blockAttr || "data-va-block";
132
+ const unmaskAttr = o.unmaskAttr || "data-va-unmask";
133
+ const rate = o.rate ?? 50;
134
+ const budget = o.budget ?? 8_000_000;
135
+ const printEvery = o.printEvery ?? 30_000;
136
+ const slice = o.slice ?? 8;
137
+ const modules = [...(o.modules || [])];
138
+ const now = () => Math.round(w.performance.now());
139
+
140
+ let ids = new WeakMap<Node, number>();
141
+ let seq = 0;
142
+ let tape: Tape = [];
143
+ /** The number the first node made since the last drain takes. */
144
+ let base = 1;
145
+ let last = now();
146
+ let t0 = Date.now() - last;
147
+ let firstAt = 0;
148
+ let cuts: Array<number> | undefined;
149
+ let scanned = 0;
150
+ let bytes = 0;
151
+ let cutAt = 0;
152
+ let spent = 0;
153
+ let timer: ReturnType<typeof setTimeout> | 0 = 0;
154
+ let lastPrint = 0;
155
+ let stopped = false;
156
+ let ended: End | 0 = 0;
157
+
158
+ let dels: Array<number> = [];
159
+ let sheetQueue: Array<Element> = [];
160
+ let sheetIds = new WeakMap<CSSStyleSheet, number>();
161
+ let sheetSeq = 0;
162
+ const dAttr = new Map<Element, Set<string>>();
163
+ const dText = new Set<Node>();
164
+ const dKids = new Map<Node, Set<Node>>();
165
+ /** Nodes taken out of their parent and still in the page, with the number they had. */
166
+ const left = new Map<Node, number>();
167
+ /**
168
+ * Nodes forgotten with an ancestor during this read, with the number they had. Forgetting
169
+ * walks the page as it is now, so it takes along nodes moved into that ancestor since the last
170
+ * read, which the copy still holds where they were: their own removal says where.
171
+ */
172
+ const gone = new Map<Node, number>();
173
+ /** Roots (template content, shadow roots, frame documents) and what holds them. */
174
+ const owner = new WeakMap<Node, Element>();
175
+ /** Form controls, dialogs and popovers, and the value last written for each. */
176
+ const fields = new Set<Element>();
177
+ const written = new WeakMap<Element, string | number>();
178
+ /** The zone each node was recorded under: a node moved to another zone is recorded again. */
179
+ const recordedIn = new WeakMap<Node, Zone>();
180
+
181
+ const stars = (s: string) => s.replace(/\S/g, "*");
182
+ const isEl = (n: Node): n is Element => n.nodeType === 1;
183
+ const has = (el: Element, name: string) => N.has(el, name);
184
+
185
+ // --- Zones and masking -------------------------------------------------------------
186
+
187
+ function up(n: Node): Node | null {
188
+ const p = N.parent(n);
189
+ if (p) return p;
190
+ if (n.nodeType === 11) return owner.get(n) || (n as ShadowRoot).host || null;
191
+ if (n.nodeType === 9) return owner.get(n) || null;
192
+ return null;
193
+ }
194
+
195
+ /** Whether an element makes its subtree masked, by itself. */
196
+ function masksSelf(el: Element): boolean {
197
+ if (has(el, maskAttr)) return true;
198
+ if (mode === "none") return false;
199
+ const editable = N.get(el, "contenteditable");
200
+ return (
201
+ editable !== null && editable.toLowerCase() !== "false" && !has(el, unmaskAttr)
202
+ );
203
+ }
204
+
205
+ function zoneOf(n: Node): Zone {
206
+ let z: Zone = mode === "text" ? 1 : 0;
207
+ for (let p: Node | null = n; p; p = up(p))
208
+ if (isEl(p)) {
209
+ if (has(p, blockAttr)) return 2;
210
+ if (z === 0 && masksSelf(p)) z = 1;
211
+ }
212
+ return z;
213
+ }
214
+
215
+ function unmasked(el: Element): boolean {
216
+ for (let p: Node | null = el; p; p = up(p))
217
+ if (isEl(p) && has(p, unmaskAttr)) return true;
218
+ return false;
219
+ }
220
+
221
+ // biome-ignore lint/suspicious/noExplicitAny: form controls, read by duck typing.
222
+ function sensitive(el: any): boolean {
223
+ const type = String(el.type || "").toLowerCase();
224
+ return (
225
+ type === "password" ||
226
+ type === "hidden" ||
227
+ SENSITIVE_AUTOCOMPLETE.test(N.get(el, "autocomplete") || "")
228
+ );
229
+ }
230
+
231
+ /** Whether what a field holds is hidden. */
232
+ function fieldMasked(el: Element, zone: Zone): boolean {
233
+ if (sensitive(el)) return true;
234
+ if (mode === "none") return zone !== 0;
235
+ return !unmasked(el);
236
+ }
237
+
238
+ const value = (v: string, hidden: boolean) => (hidden ? (v ? STARS : "") : v);
239
+
240
+ /** An attribute as it goes on the tape; undefined: left out. */
241
+ function attr(el: Element, tag: string, name: string, v: string, zone: Zone) {
242
+ if (/^on/i.test(name)) return undefined;
243
+ if (name === "value" && (tag === "input" || tag === "textarea")) {
244
+ const type = String((el as HTMLInputElement).type || "").toLowerCase();
245
+ if (type === "hidden") return undefined;
246
+ if (!NOT_TYPED.test(type) && !TOGGLE.test(type))
247
+ return value(v, fieldMasked(el, zone));
248
+ }
249
+ if (zone === 1 && !PLAIN.test(name)) return stars(v);
250
+ return v;
251
+ }
252
+
253
+ /** What a text node shows, as it goes on the tape. */
254
+ function text(n: Node, data: string, zone: Zone): string {
255
+ const p = N.parent(n);
256
+ const tag = p && isEl(p) ? N.local(p) : "";
257
+ if (tag === "style") return data;
258
+ if (tag === "textarea") return value(data, fieldMasked(p as Element, zone));
259
+ return zone === 1 ? stars(data) : data;
260
+ }
261
+
262
+ /** The select an option belongs to, through an optgroup. */
263
+ function selectOf(option: Element): HTMLSelectElement | null {
264
+ for (let p = N.parent(option), k = 0; p && k < 2; p = N.parent(p), k++)
265
+ if (isEl(p) && N.local(p) === "select") return p as HTMLSelectElement;
266
+ return null;
267
+ }
268
+ /**
269
+ * The options the markup alone selects: what a masked select shows, so that nothing the
270
+ * visitor chose leaves the page, and the copy does not keep a choice of its own.
271
+ */
272
+ let picks = new Map<HTMLSelectElement, Set<Element>>();
273
+ function defaults(select: HTMLSelectElement): Set<Element> {
274
+ let set = picks.get(select);
275
+ if (set) return set;
276
+ set = new Set();
277
+ const options = Array.from(select.options);
278
+ if (select.multiple || select.size > 1) {
279
+ for (const o of options) if (has(o, "selected")) set.add(o);
280
+ } else {
281
+ let pick: Element | undefined;
282
+ for (const o of options) if (has(o, "selected")) pick = o;
283
+ pick ||= options.find((o) => !o.disabled);
284
+ if (pick) set.add(pick);
285
+ }
286
+ picks.set(select, set);
287
+ return set;
288
+ }
289
+
290
+ /** A field's current state, as VAL writes it. */
291
+ // biome-ignore lint/suspicious/noExplicitAny: form controls, read by duck typing.
292
+ function state(el: any, zone: Zone): string | number | undefined {
293
+ const tag = N.local(el);
294
+ if (tag === "option") {
295
+ const select = selectOf(el);
296
+ if (select && (zone === 2 || fieldMasked(select, zoneOf(select)))) return defaults(select).has(el) ? 1 : 0;
297
+ return el.selected ? 1 : 0;
298
+ }
299
+ if (tag === "dialog") return undefined;
300
+ const type = String(el.type || "").toLowerCase();
301
+ if (type === "hidden" || type === "file") return undefined;
302
+ if (TOGGLE.test(type)) return el.checked ? 1 : 0;
303
+ if (NOT_TYPED.test(type)) return undefined;
304
+ return value(String(el.value ?? ""), fieldMasked(el, zone));
305
+ }
306
+
307
+ /** The state a field has from its markup alone, before anyone touches it. */
308
+ // biome-ignore lint/suspicious/noExplicitAny: form controls, read by duck typing.
309
+ function initial(el: any, zone: Zone): string | number | undefined {
310
+ const tag = N.local(el);
311
+ if (tag === "option") return has(el, "selected") ? 1 : 0;
312
+ const type = String(el.type || "").toLowerCase();
313
+ if (TOGGLE.test(type)) return has(el, "checked") ? 1 : 0;
314
+ if (tag === "textarea")
315
+ return value(String(el.defaultValue ?? ""), fieldMasked(el, zone));
316
+ return value(N.get(el, "value") || "", fieldMasked(el, zone));
317
+ }
318
+
319
+ function openState(el: Element): number {
320
+ let s = 0;
321
+ try {
322
+ if (el.matches(":modal")) return 2;
323
+ } catch {}
324
+ if (N.local(el) === "dialog") s = has(el, "open") ? 1 : 0;
325
+ try {
326
+ if (el.matches(":popover-open")) s = 1;
327
+ } catch {}
328
+ return s;
329
+ }
330
+
331
+ // --- Serialization -----------------------------------------------------------------
332
+
333
+ function cut(mark: number, name: string) {
334
+ if (!cuts) return;
335
+ for (; scanned < tape.length; scanned++) {
336
+ const t = tape[scanned];
337
+ bytes += typeof t === "string" ? Math.min(t.length, 64) + 3 : 3;
338
+ }
339
+ const size = bytes - cutAt;
340
+ if (size < 512) return;
341
+ let h = fnv(FNV_START, tape.length - mark);
342
+ for (let i = 0; i < name.length; i++) h = fnv(h, name.charCodeAt(i));
343
+ if ((h & 63) === 0 || size >= 16_384) {
344
+ cuts.push(tape.length);
345
+ cutAt = bytes;
346
+ }
347
+ }
348
+
349
+ function ser(n: Node, zone: Zone) {
350
+ const known = ids.get(n);
351
+ if (known) {
352
+ if (recordedIn.get(n) === zone) {
353
+ tape.push(Op.R, known);
354
+ if (isEl(n) && N.local(n) === "option") {
355
+ const select = selectOf(n);
356
+ if (select) for (const o of Array.from(select.options)) written.delete(o);
357
+ }
358
+ return;
359
+ }
360
+ tape.push(Op.DEL, known);
361
+ forget(n);
362
+ }
363
+ recordedIn.set(n, zone);
364
+ const type = n.nodeType;
365
+ if (type === 3) {
366
+ ids.set(n, ++seq);
367
+ tape.push(Op.T, text(n, (n as Text).data, zone));
368
+ return;
369
+ }
370
+ if (type === 10) {
371
+ const t = n as DocumentType;
372
+ ids.set(n, ++seq);
373
+ tape.push(Op.D, t.name, t.publicId, t.systemId);
374
+ return;
375
+ }
376
+ if (type !== 1) return;
377
+ const el = n as Element;
378
+ const tag = N.local(el);
379
+ const ns = N.ns(el);
380
+ if (tag === "script" || (tag === "noscript" && ns === HTML)) return;
381
+ const name =
382
+ ns === HTML || ns === null
383
+ ? tag
384
+ : `${ns === SVG ? "s" : ns === MATHML ? "m" : ns} ${tag}`;
385
+ if (zone !== 2 && has(el, blockAttr)) zone = 2;
386
+ ids.set(n, ++seq);
387
+ if (tag === "option" && ns === HTML) {
388
+ // An option inserted makes the browser pick again, in the copy too: every option of its
389
+ // select is sent again.
390
+ const select = selectOf(el);
391
+ if (select) for (const o of Array.from(select.options)) written.delete(o);
392
+ fields.add(el);
393
+ }
394
+ if (zone === 2) {
395
+ const box = N.rect(el);
396
+ tape.push(Op.B, name, Math.round(box.width), Math.round(box.height));
397
+ return;
398
+ }
399
+ if (zone === 0 && masksSelf(el)) zone = 1;
400
+ const mark = tape.length;
401
+ tape.push(Op.E, name, 0);
402
+ const list = N.attributes(el);
403
+ let count = 0;
404
+ for (let i = 0; i < list.length; i++) {
405
+ const a = list[i] as Attr;
406
+ const v = attr(el, tag, a.name, a.value, zone);
407
+ if (v === undefined) continue;
408
+ tape.push(a.name, v);
409
+ count++;
410
+ }
411
+ tape[mark + 2] = count;
412
+ if (ns === HTML) {
413
+ if (tag === "input" || tag === "textarea" || tag === "option") {
414
+ fields.add(el);
415
+ // A textarea's text may lie in several nodes, each masked alone: its value is always sent.
416
+ const v = tag === "input" ? initial(el, zone) : undefined;
417
+ if (v === undefined) written.delete(el);
418
+ else written.set(el, v);
419
+ } else if (tag === "dialog" || has(el, "popover")) {
420
+ fields.add(el);
421
+ written.set(el, tag === "dialog" && has(el, "open") ? 1 : 0);
422
+ } else if (
423
+ tag === "style" ||
424
+ (tag === "link" && /stylesheet/i.test(N.get(el, "rel") || ""))
425
+ )
426
+ sheetQueue.push(el);
427
+ }
428
+ for (const m of modules) if (m.onElement) guard(m, () => m.onElement?.(el, zone));
429
+ if (tag === "template" && ns === HTML) {
430
+ const content = N.content(el as HTMLTemplateElement);
431
+ ids.set(content, ++seq);
432
+ owner.set(content, el);
433
+ observe(content);
434
+ tape.push(Op.TPL);
435
+ for (let c = N.first(content); c; c = N.next(c)) ser(c, zone);
436
+ tape.push(Op.X);
437
+ }
438
+ for (let c = N.first(el); c; c = N.next(c)) ser(c, zone);
439
+ tape.push(Op.X);
440
+ cut(mark, name);
441
+ }
442
+
443
+ function forget(n: Node, inner?: 1) {
444
+ const id = ids.get(n);
445
+ if (!id) return;
446
+ ids.delete(n);
447
+ if (inner) {
448
+ gone.set(n, id);
449
+ // Moved here in a read cut short: the copy still holds it where it was.
450
+ const p = N.parent(n);
451
+ if (p && dKids.get(p)?.has(n)) dels.push(id);
452
+ }
453
+ if (isEl(n)) {
454
+ fields.delete(n);
455
+ if (N.local(n) === "template") forget(N.content(n as HTMLTemplateElement), 1);
456
+ }
457
+ for (let c = N.first(n); c; c = N.next(c)) forget(c, 1);
458
+ for (const m of modules) {
459
+ const tree = m.inner ? safe(m, () => m.inner?.(n)) : null;
460
+ if (tree) forget(tree, 1);
461
+ }
462
+ }
463
+
464
+ // --- Modules -----------------------------------------------------------------------
465
+
466
+ const off = new Set<Module>();
467
+ /** Set when a module failed halfway through numbering nodes: only a new snapshot is safe. */
468
+ let resnap = false;
469
+ function guard(m: Module, f: () => void) {
470
+ if (off.has(m)) return;
471
+ const mark = tape.length;
472
+ const numbered = seq;
473
+ try {
474
+ f();
475
+ } catch {
476
+ off.add(m);
477
+ tape.length = mark;
478
+ if (seq !== numbered) {
479
+ seq = numbered;
480
+ resnap = true;
481
+ }
482
+ tape.push(Op.ERR, 1, m.name);
483
+ }
484
+ }
485
+ function safe<T>(m: Module, f: () => T): T | undefined {
486
+ let out: T | undefined;
487
+ guard(m, () => {
488
+ out = f();
489
+ });
490
+ return out;
491
+ }
492
+
493
+ // --- Time and gestures ---------------------------------------------------------------
494
+
495
+ function stamp() {
496
+ const t = now();
497
+ if (!firstAt) firstAt = t;
498
+ if (t > last) {
499
+ tape.push(Op.TICK, t - last);
500
+ last = t;
501
+ }
502
+ }
503
+
504
+ /** The nearest recorded node at or above `n`. */
505
+ function nearest(n: Node | null): number {
506
+ for (let p = n; p; p = up(p)) {
507
+ const id = ids.get(p);
508
+ if (id) return id;
509
+ }
510
+ return 0;
511
+ }
512
+
513
+ let moveAt = 0;
514
+ let moveTimer: ReturnType<typeof setTimeout> | 0 = 0;
515
+ let px = 0;
516
+ let py = 0;
517
+ let movePending = false;
518
+ function move() {
519
+ moveTimer = 0;
520
+ if (!movePending || stopped) return;
521
+ movePending = false;
522
+ moveAt = now();
523
+ stamp();
524
+ tape.push(Op.MOVE, px, py);
525
+ }
526
+
527
+ const scrolled = new Set<Node>();
528
+ let scrollTimer: ReturnType<typeof setTimeout> | 0 = 0;
529
+ function scrolls() {
530
+ scrollTimer = 0;
531
+ if (stopped) return;
532
+ stamp();
533
+ scrolled.forEach((n) => {
534
+ const id = ids.get(n);
535
+ const el = (n.nodeType === 9 ? (n as Document).scrollingElement : n) as Element | null;
536
+ if (id && el) tape.push(Op.SCROLL, n === d ? 1 : id, Math.round(el.scrollLeft), Math.round(el.scrollTop));
537
+ });
538
+ scrolled.clear();
539
+ }
540
+
541
+ let sizeTimer: ReturnType<typeof setTimeout> | 0 = 0;
542
+ function size() {
543
+ sizeTimer = 0;
544
+ if (stopped) return;
545
+ stamp();
546
+ tape.push(Op.SIZE, w.innerWidth, w.innerHeight);
547
+ }
548
+
549
+ /** An event's position, in the top page's coordinates. */
550
+ function point(e: MouseEvent): [number, number] {
551
+ let x = e.clientX;
552
+ let y = e.clientY;
553
+ let view = (e.view || (e.target as Node)?.ownerDocument?.defaultView) as Window | null;
554
+ while (view && view !== w) {
555
+ const frame = view.frameElement;
556
+ if (!frame) break;
557
+ const r = frame.getBoundingClientRect();
558
+ x += r.left + frame.clientLeft;
559
+ y += r.top + frame.clientTop;
560
+ view = frame.ownerDocument.defaultView;
561
+ }
562
+ return [Math.round(x), Math.round(y)];
563
+ }
564
+
565
+ const stops: Array<() => void> = [];
566
+ function listen(root: Document | ShadowRoot) {
567
+ const on = (type: string, f: (e: never) => void) => {
568
+ const listener = f as EventListener;
569
+ root.addEventListener(type, listener, { capture: true, passive: true });
570
+ stops.push(() => root.removeEventListener(type, listener, true));
571
+ };
572
+ const target = (e: Event) =>
573
+ ((e.composedPath ? e.composedPath()[0] : e.target) || null) as Node | null;
574
+ on("pointermove", (e: PointerEvent) => {
575
+ [px, py] = point(e);
576
+ movePending = true;
577
+ const wait = 20 - (now() - moveAt);
578
+ if (wait <= 0) move();
579
+ else if (!moveTimer) moveTimer = setTimeout(move, wait);
580
+ });
581
+ const tap = (kind: number) => (e: MouseEvent) => {
582
+ if (movePending) move();
583
+ const [x, y] = point(e);
584
+ stamp();
585
+ tape.push(Op.TAP, kind, nearest(target(e)), x, y);
586
+ };
587
+ on("pointerdown", tap(1));
588
+ on("pointerup", tap(2));
589
+ on("click", tap(3));
590
+ on("scroll", (e: Event) => {
591
+ const t = target(e);
592
+ if (!t) return;
593
+ scrolled.add(t.nodeType === 9 || t === d.documentElement ? d : t);
594
+ if (!scrollTimer) scrollTimer = setTimeout(scrolls, 16);
595
+ });
596
+ on("focusin", (e: FocusEvent) => {
597
+ stamp();
598
+ tape.push(Op.FOCUS, nearest(target(e)));
599
+ });
600
+ on("focusout", (e: FocusEvent) => {
601
+ if (e.relatedTarget) return;
602
+ stamp();
603
+ tape.push(Op.FOCUS, 0);
604
+ });
605
+ const typed = () => kick();
606
+ on("input", typed);
607
+ on("change", typed);
608
+ }
609
+
610
+ // --- Mutations -------------------------------------------------------------------------
611
+
612
+ function kick() {
613
+ if (timer || stopped) return;
614
+ // biome-ignore lint/suspicious/noExplicitAny: requestIdleCallback is missing on Safari.
615
+ const idle = (w as any).requestIdleCallback as
616
+ | ((f: () => void, o: { timeout: number }) => void)
617
+ | undefined;
618
+ timer = setTimeout(() => (idle ? idle(() => sync(), { timeout: 100 }) : sync()), rate);
619
+ }
620
+
621
+ /** Out of the page, a node is no longer observed: it leaves now, and comes back as a new one. */
622
+ function drop(n: Node) {
623
+ const id = ids.get(n) || gone.get(n);
624
+ if (id) {
625
+ dels.push(id);
626
+ forget(n);
627
+ return;
628
+ }
629
+ for (let c = N.first(n); c; c = N.next(c)) drop(c);
630
+ for (const m of modules) {
631
+ const tree = m.inner ? safe(m, () => m.inner?.(n)) : null;
632
+ if (tree) drop(tree);
633
+ }
634
+ }
635
+
636
+ /** True when the children of `n` are recorded. */
637
+ const open = (n: Node | null) => !!n && ids.has(n) && !(isEl(n) && has(n, blockAttr));
638
+
639
+ function touch(parent: Node, n: Node) {
640
+ let set = dKids.get(parent);
641
+ if (!set) dKids.set(parent, (set = new Set()));
642
+ set.add(n);
643
+ }
644
+
645
+ function redo(el: Element) {
646
+ if (!ids.has(el)) return;
647
+ const p = N.parent(el) || owner.get(el) || null;
648
+ drop(el);
649
+ if (p && open(p)) touch(p, el);
650
+ kick();
651
+ }
652
+
653
+ const ZONE_ATTRS = new Set([blockAttr, maskAttr, unmaskAttr, "contenteditable"]);
654
+
655
+ function seen(records: Array<MutationRecord>) {
656
+ if (!records.length) return;
657
+ for (const r of records) {
658
+ const target = r.target;
659
+ if (r.type === "childList") {
660
+ const removed = r.removedNodes;
661
+ for (let i = 0; i < removed.length; i++) {
662
+ const n = removed[i] as Node;
663
+ if (!n.isConnected) drop(n);
664
+ else {
665
+ const id = ids.get(n) || gone.get(n);
666
+ if (id) left.set(n, id);
667
+ }
668
+ }
669
+ if (open(target)) {
670
+ r.addedNodes.forEach((n) => touch(target, n));
671
+ removed.forEach((n) => touch(target, n));
672
+ }
673
+ } else if (ids.has(target)) {
674
+ if (r.type === "attributes") {
675
+ const name = r.attributeName as string;
676
+ if (ZONE_ATTRS.has(name)) {
677
+ redo(target as Element);
678
+ continue;
679
+ }
680
+ let names = dAttr.get(target as Element);
681
+ if (!names) dAttr.set(target as Element, (names = new Set()));
682
+ names.add(name);
683
+ } else dText.add(target);
684
+ }
685
+ }
686
+ kick();
687
+ }
688
+
689
+ const observer = new N.Observer(seen);
690
+ const observe = (root: Node) =>
691
+ observer.observe(root, {
692
+ childList: true,
693
+ attributes: true,
694
+ characterData: true,
695
+ subtree: true,
696
+ });
697
+
698
+ /** Comes back for the rest of a read cut short, as soon as the page had its turn. */
699
+ function resume() {
700
+ // biome-ignore lint/suspicious/noExplicitAny: scheduler.yield is not everywhere yet.
701
+ const s = (w as any).scheduler;
702
+ if (s?.yield) s.yield().then(() => sync());
703
+ else timer = setTimeout(() => sync(), 0);
704
+ }
705
+
706
+ /** Reads what changed. Cut after `slice` ms, between two parents, unless `whole`. */
707
+ function sync(whole?: boolean) {
708
+ timer = 0;
709
+ if (stopped) return;
710
+ const began = w.performance.now();
711
+ let cut = false;
712
+ seen(observer.takeRecords());
713
+ timer = 0;
714
+ const before = tape.length;
715
+ const lastBefore = last;
716
+ stamp();
717
+ const start = tape.length;
718
+
719
+ for (const id of dels) tape.push(Op.DEL, id);
720
+ dels = [];
721
+
722
+ // Nodes numbered from here on are recorded as they are now: nothing more to say about
723
+ // them in this read.
724
+ const fresh = seq + 1;
725
+ const zones = new Map<Node, Zone>();
726
+ const zone = (n: Node) => {
727
+ let z = zones.get(n);
728
+ if (z === undefined) zones.set(n, (z = zoneOf(n)));
729
+ return z;
730
+ };
731
+ for (const [parent, touched] of dKids) {
732
+ // The rest waits for the next slice: the parents left are read as they are then.
733
+ if (cut) break;
734
+ dKids.delete(parent);
735
+ const pid = ids.get(parent);
736
+ if (!pid || pid >= fresh) continue;
737
+ const z = zone(parent);
738
+ touched.forEach((t) => {
739
+ if (N.parent(t) !== parent) return;
740
+ // A run of touched siblings starts after an untouched recorded one (or at the start)
741
+ // and goes before the next one. Nodes never recorded (comments, scripts) are seen through.
742
+ let s = t.previousSibling;
743
+ while (s && !touched.has(s) && !ids.has(s)) s = s.previousSibling;
744
+ if (s && touched.has(s)) return;
745
+ const run: Array<Node> = [];
746
+ let n: Node | null = t;
747
+ for (; n; n = N.next(n))
748
+ if (touched.has(n)) run.push(n);
749
+ else if (ids.has(n)) break;
750
+ const mark = tape.length;
751
+ tape.push(Op.INS, pid, n ? (ids.get(n) as number) : 0);
752
+ for (const node of run) ser(node, z);
753
+ if (tape.length === mark + 3) tape.length = mark;
754
+ else tape.push(Op.X);
755
+ });
756
+ if (!whole && w.performance.now() - began >= slice) cut = true;
757
+ }
758
+ // Parents numbered in this read were recorded whole: what touched them is said.
759
+ dKids.forEach((_, parent) => {
760
+ const pid = ids.get(parent);
761
+ if (!pid || pid >= fresh) dKids.delete(parent);
762
+ });
763
+ if (!dKids.size) cut = false;
764
+ // A moved node the copy still holds where it was: forgotten since with what held it, or
765
+ // now where nothing is recorded (a blocked element).
766
+ left.forEach((id, n) => {
767
+ if (ids.get(n) !== id) tape.push(Op.DEL, id);
768
+ else if (!(n.isConnected && open(N.parent(n) || owner.get(n) || null))) {
769
+ tape.push(Op.DEL, id);
770
+ forget(n);
771
+ }
772
+ });
773
+ left.clear();
774
+ gone.clear();
775
+
776
+ dAttr.forEach((names, el) => {
777
+ const id = ids.get(el);
778
+ if (!id || id >= fresh) return;
779
+ const z = zone(el);
780
+ if (z === 2) return;
781
+ const tag = N.local(el);
782
+ names.forEach((name) => {
783
+ const v = N.get(el, name);
784
+ const out = v === null ? null : attr(el, tag, name, v, z);
785
+ if (out !== undefined) tape.push(Op.ATTR, id, name, out);
786
+ // A field changed by script keeps its value when its default changes; the copy's does not.
787
+ if (name === "value" || name === "checked" || name === "selected") written.delete(el);
788
+ // The browser picks again in the copy: every option of the select is sent again.
789
+ if (name === "selected" && tag === "option") {
790
+ const select = selectOf(el);
791
+ if (select) for (const o of Array.from(select.options)) written.delete(o);
792
+ }
793
+ });
794
+ });
795
+ dAttr.clear();
796
+ dText.forEach((n) => {
797
+ const id = ids.get(n);
798
+ if (id && id < fresh) tape.push(Op.TEXT, id, text(n, (n as Text).data, zone(n)));
799
+ });
800
+ dText.clear();
801
+
802
+ picks = new Map();
803
+ fields.forEach((el) => {
804
+ const id = ids.get(el);
805
+ if (!id) return;
806
+ const tag = N.local(el);
807
+ let v: string | number | undefined;
808
+ let op: Op = Op.VAL;
809
+ if (tag === "dialog" || has(el, "popover")) {
810
+ v = openState(el);
811
+ op = Op.OPEN;
812
+ } else v = state(el, zone(el));
813
+ if (v === undefined || written.get(el) === v) return;
814
+ written.set(el, v);
815
+ tape.push(op, id, v);
816
+ });
817
+
818
+ readSheets();
819
+ for (const m of modules) if (m.onSync) guard(m, () => m.onSync?.());
820
+
821
+ // The copy is behind by the parents left: no fingerprint until it caught up.
822
+ if (cut) resume();
823
+ else if (printEvery && last - lastPrint >= printEvery) {
824
+ lastPrint = last;
825
+ const [count, hash] = fingerprintOf(d);
826
+ tape.push(Op.PRINT, count, hash);
827
+ }
828
+
829
+ if (tape.length === start) {
830
+ tape.length = before;
831
+ last = lastBefore;
832
+ }
833
+ }
834
+
835
+ function readSheets() {
836
+ for (const el of sheetQueue.splice(0)) {
837
+ const id = ids.get(el);
838
+ if (!id) continue;
839
+ try {
840
+ const sheet = (el as HTMLLinkElement).sheet;
841
+ if (!sheet) {
842
+ el.addEventListener(
843
+ "load",
844
+ () => {
845
+ sheetQueue.push(el);
846
+ kick();
847
+ },
848
+ { once: true },
849
+ );
850
+ continue;
851
+ }
852
+ // The rules of a <style> are in its text, unless a script put them there (CSS-in-JS).
853
+ if (N.local(el) === "style" && (!sheet.cssRules.length || (el.textContent || "").trim()))
854
+ continue;
855
+ let css = "";
856
+ for (const rule of Array.from(sheet.cssRules)) css += rule.cssText;
857
+ tape.push(Op.SHEET, id, kit.sheet(sheet), css);
858
+ } catch {
859
+ // A stylesheet from another origin: the player loads it from its address.
860
+ }
861
+ }
862
+ }
863
+
864
+ /** Nodes and a hash of the page's shape, as the player computes it of its copy. */
865
+ function fingerprintOf(root: Node): [number, number] {
866
+ let count = 0;
867
+ let h = FNV_START;
868
+ const walk = (n: Node) => {
869
+ for (let c = N.first(n); c; c = N.next(c)) {
870
+ if (!ids.has(c)) continue;
871
+ count++;
872
+ h = fnv(h, c.nodeType);
873
+ if (isEl(c)) {
874
+ const tag = N.local(c);
875
+ h = fnv(h, tag.length);
876
+ h = fnv(h, tag.charCodeAt(0));
877
+ if (has(c, blockAttr)) continue;
878
+ if (tag === "template") walk(N.content(c as HTMLTemplateElement));
879
+ walk(c);
880
+ }
881
+ }
882
+ };
883
+ walk(root);
884
+ return [count, h];
885
+ }
886
+
887
+ // --- The kit and the recorder ------------------------------------------------------------
888
+
889
+ const kit: Kit = {
890
+ w,
891
+ d,
892
+ native: N,
893
+ ser,
894
+ push: (...tokens) => {
895
+ tape.push(...tokens);
896
+ },
897
+ stamp,
898
+ id: (n) => ids.get(n),
899
+ take: (root, host) => {
900
+ ids.set(root, ++seq);
901
+ owner.set(root, host);
902
+ return seq;
903
+ },
904
+ zone: zoneOf,
905
+ sheet: (s) => {
906
+ let k = sheetIds.get(s);
907
+ if (k === undefined) sheetIds.set(s, (k = ++sheetSeq));
908
+ return k;
909
+ },
910
+ sheetKnown: (s) => sheetIds.has(s),
911
+ observe,
912
+ listen,
913
+ redo,
914
+ dirty: kick,
915
+ masked: stars,
916
+ };
917
+
918
+ const onResize = () => {
919
+ if (!sizeTimer) sizeTimer = setTimeout(size, 100);
920
+ };
921
+ const onHide = () => {
922
+ stamp();
923
+ tape.push(Op.HIDE, d.hidden ? 1 : 0);
924
+ };
925
+ // Back from the cache: the beacon on the way out may not have held all the tape.
926
+ const onShow = (e: PageTransitionEvent) => {
927
+ if (e.persisted) resnap = true;
928
+ };
929
+ w.addEventListener("resize", onResize);
930
+ w.addEventListener("pageshow", onShow);
931
+ d.addEventListener("visibilitychange", onHide);
932
+ listen(d);
933
+ observe(d);
934
+ const poll = setInterval(() => {
935
+ if (fields.size) kick();
936
+ }, 500);
937
+ for (const m of modules) if (m.setup) guard(m, () => m.setup?.(kit));
938
+
939
+ function weigh(t: Tape) {
940
+ for (const token of t) spent += typeof token === "string" ? token.length + 3 : 3;
941
+ if (spent > budget && !stopped) stop(End.Budget);
942
+ }
943
+
944
+ function stop(reason?: End) {
945
+ if (stopped) return;
946
+ stopped = true;
947
+ if (reason) ended = reason;
948
+ observer.disconnect();
949
+ clearTimeout(timer as number);
950
+ clearTimeout(moveTimer as number);
951
+ clearTimeout(scrollTimer as number);
952
+ clearTimeout(sizeTimer as number);
953
+ clearInterval(poll);
954
+ w.removeEventListener("resize", onResize);
955
+ w.removeEventListener("pageshow", onShow);
956
+ d.removeEventListener("visibilitychange", onHide);
957
+ for (const f of stops) f();
958
+ for (const m of modules) if (m.onStop) guard(m, () => m.onStop?.());
959
+ }
960
+
961
+ return {
962
+ snap() {
963
+ ids = new WeakMap();
964
+ sheetIds = new WeakMap();
965
+ sheetSeq = 0;
966
+ seq = 1;
967
+ ids.set(d, 1);
968
+ dels = [];
969
+ sheetQueue = [];
970
+ dAttr.clear();
971
+ dText.clear();
972
+ dKids.clear();
973
+ left.clear();
974
+ gone.clear();
975
+ fields.clear();
976
+ observer.takeRecords();
977
+ last = now();
978
+ t0 = Date.now() - last;
979
+ lastPrint = last;
980
+ // What was on the tape before belongs to the page as it was: dropped.
981
+ tape = [
982
+ Op.META,
983
+ VERSION,
984
+ d.URL,
985
+ t0 + last,
986
+ w.innerWidth,
987
+ w.innerHeight,
988
+ d.compatMode === "BackCompat" ? 1 : 0,
989
+ ];
990
+ cuts = [tape.length];
991
+ scanned = bytes = cutAt = 0;
992
+ for (let c = N.first(d); c; c = N.next(c)) ser(c, mode === "text" ? 1 : 0);
993
+ const wasOff = [...off];
994
+ for (const m of modules) if (m.onSnap) guard(m, () => m.onSnap?.());
995
+ // A snapshot starts the copy again: it says again which modules are off, one cut at setup included.
996
+ for (const m of wasOff) tape.push(Op.ERR, 1, m.name);
997
+ resnap = false;
998
+ const out: Snapshot = {
999
+ tape,
1000
+ cuts: cuts.filter((c) => c < tape.length),
1001
+ base: 1,
1002
+ startedAt: t0 + last,
1003
+ endedAt: t0 + last,
1004
+ };
1005
+ cuts = undefined;
1006
+ tape = [];
1007
+ base = seq + 1;
1008
+ firstAt = 0;
1009
+ // The page's scroll forces a layout: read at the first read at rest, not here.
1010
+ scrolled.add(d);
1011
+ if (!scrollTimer) scrollTimer = setTimeout(scrolls, 16);
1012
+ kick();
1013
+ weigh(out.tape);
1014
+ return out;
1015
+ },
1016
+ drain() {
1017
+ if (!stopped) sync(true);
1018
+ if (ended) {
1019
+ tape.push(Op.END, ended);
1020
+ ended = 0;
1021
+ }
1022
+ const out: Drained = {
1023
+ tape,
1024
+ base,
1025
+ startedAt: t0 + (firstAt || last),
1026
+ endedAt: t0 + last,
1027
+ };
1028
+ tape = [];
1029
+ base = seq + 1;
1030
+ firstAt = 0;
1031
+ weigh(out.tape);
1032
+ return out;
1033
+ },
1034
+ stop,
1035
+ get stopped() {
1036
+ return stopped;
1037
+ },
1038
+ get needsSnap() {
1039
+ return resnap;
1040
+ },
1041
+ };
1042
+ }