@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,100 @@
1
+ // The DOM accessors the recorder reads through. The recorder loads after the page's own code,
2
+ // which may have wrapped them (zone.js and the like): when any of them is not native, they are
3
+ // all taken from a fresh realm, a blank iframe of the same origin, and called with `.call`.
4
+
5
+ export interface Natives {
6
+ readonly first: (n: Node) => Node | null;
7
+ readonly next: (n: Node) => Node | null;
8
+ readonly parent: (n: Node) => Node | null;
9
+ readonly attributes: (el: Element) => NamedNodeMap;
10
+ readonly get: (el: Element, name: string) => string | null;
11
+ readonly has: (el: Element, name: string) => boolean;
12
+ readonly local: (el: Element) => string;
13
+ readonly ns: (el: Element) => string | null;
14
+ readonly rect: (el: Element) => DOMRect;
15
+ readonly shadow: (el: Element) => ShadowRoot | null;
16
+ readonly host: (root: ShadowRoot) => Element;
17
+ readonly content: (template: HTMLTemplateElement) => DocumentFragment;
18
+ readonly Observer: typeof MutationObserver;
19
+ }
20
+
21
+ type Realm = Window & typeof globalThis;
22
+
23
+ const NATIVE = /\{\s*\[native code\]\s*\}\s*$/;
24
+
25
+ function described(proto: object, name: string): PropertyDescriptor | undefined {
26
+ for (let p: object | null = proto; p; p = Object.getPrototypeOf(p)) {
27
+ const d = Object.getOwnPropertyDescriptor(p, name);
28
+ if (d) return d;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ function pieces(w: Realm) {
34
+ const N = w.Node.prototype;
35
+ const E = w.Element.prototype;
36
+ const g = (proto: object, name: string) =>
37
+ described(proto, name)?.get as (this: unknown) => unknown;
38
+ const m = (proto: object, name: string) =>
39
+ described(proto, name)?.value as (this: unknown, ...a: Array<unknown>) => unknown;
40
+ return {
41
+ first: g(N, "firstChild"),
42
+ next: g(N, "nextSibling"),
43
+ parent: g(N, "parentNode"),
44
+ attributes: g(E, "attributes"),
45
+ get: m(E, "getAttribute"),
46
+ has: m(E, "hasAttribute"),
47
+ local: g(E, "localName"),
48
+ ns: g(E, "namespaceURI"),
49
+ rect: m(E, "getBoundingClientRect"),
50
+ shadow: g(E, "shadowRoot"),
51
+ host: w.ShadowRoot ? g(w.ShadowRoot.prototype, "host") : undefined,
52
+ content: w.HTMLTemplateElement
53
+ ? g(w.HTMLTemplateElement.prototype, "content")
54
+ : undefined,
55
+ Observer: w.MutationObserver,
56
+ };
57
+ }
58
+
59
+ function untouched(p: ReturnType<typeof pieces>): boolean {
60
+ const toString = Function.prototype.toString;
61
+ for (const f of Object.values(p))
62
+ if (typeof f === "function" && !NATIVE.test(toString.call(f))) return false;
63
+ return true;
64
+ }
65
+
66
+ export function natives(w: Window): Natives {
67
+ let p = pieces(w as Realm);
68
+ if (!untouched(p)) {
69
+ const d = w.document;
70
+ const frame = d.createElement("iframe");
71
+ frame.setAttribute("aria-hidden", "true");
72
+ frame.style.display = "none";
73
+ try {
74
+ (d.body || d.documentElement).appendChild(frame);
75
+ const fresh = frame.contentWindow as Realm | null;
76
+ if (fresh) p = pieces(fresh);
77
+ } catch {
78
+ // No fresh realm: the page's own accessors, as they are.
79
+ }
80
+ frame.remove();
81
+ }
82
+ const { first, next, parent, attributes, get, has, local, ns, rect, shadow } = p;
83
+ const host = p.host;
84
+ const content = p.content;
85
+ return {
86
+ first: (n) => first.call(n) as Node | null,
87
+ next: (n) => next.call(n) as Node | null,
88
+ parent: (n) => parent.call(n) as Node | null,
89
+ attributes: (el) => attributes.call(el) as NamedNodeMap,
90
+ get: (el, name) => get.call(el, name) as string | null,
91
+ has: (el, name) => has.call(el, name) as boolean,
92
+ local: (el) => local.call(el) as string,
93
+ ns: (el) => ns.call(el) as string | null,
94
+ rect: (el) => rect.call(el) as DOMRect,
95
+ shadow: (el) => (shadow ? (shadow.call(el) as ShadowRoot | null) : null),
96
+ host: (root) => (host ? (host.call(root) as Element) : root.host),
97
+ content: (t) => (content ? (content.call(t) as DocumentFragment) : t.content),
98
+ Observer: p.Observer,
99
+ };
100
+ }
@@ -0,0 +1,339 @@
1
+ // Sends a page view's tapes, in order. What the server may already hold goes as its hash: the
2
+ // pieces of a snapshot and long strings (stylesheets, pictures). The server answers with the
3
+ // hashes it wants (`need`), and with `snap` when it saw a hole: the caller then takes a new
4
+ // snapshot. On the way out, one beacon carries what is left, as much as fits.
5
+ import type { Tape, WireTape } from "../format/index";
6
+
7
+ /** Strings longer than this are sent by hash. */
8
+ const LONG = 256;
9
+ /** `sendBeacon` and `fetch` with `keepalive` refuse more than 64 KiB. */
10
+ const BEACON_BYTES = 60_000;
11
+ const RETRIES = [1000, 4000, 16000];
12
+
13
+ export interface Head {
14
+ readonly property?: string;
15
+ readonly visitor?: string;
16
+ readonly url: string;
17
+ readonly pv: string;
18
+ }
19
+
20
+ export interface Answer {
21
+ readonly need?: ReadonlyArray<string>;
22
+ readonly snap?: boolean;
23
+ }
24
+
25
+ export interface Envelope extends Head {
26
+ readonly v: 2;
27
+ readonly seq?: number;
28
+ readonly base?: number;
29
+ readonly startedAt?: number;
30
+ readonly endedAt?: number;
31
+ readonly tape?: WireTape;
32
+ readonly blobs?: Readonly<Record<string, string>>;
33
+ readonly last?: true;
34
+ }
35
+
36
+ export interface Piece {
37
+ readonly tape: Tape;
38
+ readonly base: number;
39
+ readonly startedAt: number;
40
+ readonly endedAt: number;
41
+ /** For a snapshot: where it may be cut into pieces hashed one by one. */
42
+ readonly cuts?: ReadonlyArray<number>;
43
+ }
44
+
45
+ export interface ConnectOptions {
46
+ readonly endpoint: string;
47
+ /** The page view this goes with; undefined while it has no id yet (a prerendered page). */
48
+ readonly head: () => Head | undefined;
49
+ /** Posts a body and reads the answer; `fetch` by default. */
50
+ readonly post?: (endpoint: string, body: string) => Promise<Answer | undefined>;
51
+ /** Sends a body that must outlive the page; `navigator.sendBeacon` by default. */
52
+ readonly beacon?: (endpoint: string, body: string) => boolean;
53
+ /** The server saw a hole: take a new snapshot and send it. */
54
+ readonly onSnap?: () => void;
55
+ /** Sending failed for good: nothing more goes for this page view. */
56
+ readonly onFail?: () => void;
57
+ /** Waits between two tries; `setTimeout` by default. */
58
+ readonly wait?: (ms: number) => Promise<void>;
59
+ }
60
+
61
+ export interface Link {
62
+ send(piece: Piece): Promise<void>;
63
+ /** The page is going away: one beacon with what is left. */
64
+ leave(piece?: Piece): void;
65
+ /** Settles once everything queued has been sent, or given up. */
66
+ idle(): Promise<void>;
67
+ readonly failed: boolean;
68
+ }
69
+
70
+ const encoder = new TextEncoder();
71
+
72
+ /** 16 bytes of SHA-256, base64url. Null where `crypto.subtle` is missing (a page in `http`). */
73
+ export async function hash(text: string): Promise<string | null> {
74
+ const subtle = globalThis.crypto?.subtle;
75
+ if (!subtle) return null;
76
+ const digest = await subtle.digest("SHA-256", encoder.encode(text));
77
+ let s = "";
78
+ for (const byte of new Uint8Array(digest, 0, 16)) s += String.fromCharCode(byte);
79
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
80
+ }
81
+
82
+ /** Replaces long strings and, for a snapshot, each piece by its hash. `kept` gets what was replaced. */
83
+ export async function pack(
84
+ tape: Tape,
85
+ cuts: ReadonlyArray<number> | undefined,
86
+ kept: Map<string, string>,
87
+ ): Promise<WireTape> {
88
+ const strings = async (from: number, to: number) => {
89
+ const out: WireTape = [];
90
+ for (let i = from; i < to; i++) {
91
+ const token = tape[i] as Tape[0];
92
+ if (typeof token === "string" && token.length > LONG) {
93
+ const h = await hash(token);
94
+ if (h === null) {
95
+ out.push(token);
96
+ continue;
97
+ }
98
+ kept.set(h, token);
99
+ out.push([h]);
100
+ } else out.push(token);
101
+ }
102
+ return out;
103
+ };
104
+ if (!cuts?.length) return strings(0, tape.length);
105
+ const out = await strings(0, cuts[0] as number);
106
+ for (let c = 0; c < cuts.length; c++) {
107
+ const from = cuts[c] as number;
108
+ const to = c + 1 < cuts.length ? (cuts[c + 1] as number) : tape.length;
109
+ if (to <= from) continue;
110
+ const part = await strings(from, to);
111
+ const text = JSON.stringify(part);
112
+ const h = await hash(text);
113
+ if (h === null) {
114
+ for (const t of part) out.push(t);
115
+ continue;
116
+ }
117
+ kept.set(h, text);
118
+ out.push([h, 1]);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ const bytesOf = (s: string) => encoder.encode(s).length;
124
+
125
+ export function connect(o: ConnectOptions): Link {
126
+ const post =
127
+ o.post ||
128
+ (async (endpoint: string, body: string) => {
129
+ const W = globalThis as typeof globalThis & { CompressionStream?: typeof CompressionStream };
130
+ let payload: BodyInit = body;
131
+ if (W.CompressionStream)
132
+ payload = await new Response(
133
+ new Blob([body]).stream().pipeThrough(new W.CompressionStream("gzip")),
134
+ ).blob();
135
+ const response = await fetch(endpoint, {
136
+ method: "POST",
137
+ body: payload,
138
+ headers: { "content-type": "text/plain" },
139
+ });
140
+ if (!response.ok) throw new Error(`replay: ${response.status}`);
141
+ const text = await response.text();
142
+ return text ? (JSON.parse(text) as Answer) : undefined;
143
+ });
144
+ const beacon =
145
+ o.beacon ||
146
+ ((endpoint: string, body: string) => {
147
+ try {
148
+ if (navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain" }))) return true;
149
+ } catch {}
150
+ try {
151
+ fetch(endpoint, {
152
+ method: "POST",
153
+ body,
154
+ keepalive: true,
155
+ headers: { "content-type": "text/plain" },
156
+ }).catch(() => {});
157
+ return true;
158
+ } catch {
159
+ return false;
160
+ }
161
+ });
162
+ const wait = o.wait || ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
163
+
164
+ let queue: Promise<void> = Promise.resolve();
165
+ let pv: string | undefined;
166
+ let seq = 0;
167
+ let failed = false;
168
+ /** What was replaced by a hash and not yet known to be on the server. */
169
+ const kept = new Map<string, string>();
170
+ /** What the server asked for and has not received yet. */
171
+ const wanted = new Set<string>();
172
+ /** Pieces waiting for the page view to have an id. */
173
+ let held: Array<Piece> = [];
174
+
175
+ function envelope(head: Head, rest: Partial<Envelope>): Envelope {
176
+ return {
177
+ v: 2,
178
+ ...(head.property === undefined ? {} : { property: head.property }),
179
+ ...(head.visitor === undefined ? {} : { visitor: String(head.visitor).slice(0, 64) }),
180
+ url: head.url,
181
+ pv: head.pv,
182
+ ...rest,
183
+ };
184
+ }
185
+
186
+ async function attempt(body: string): Promise<Answer | undefined> {
187
+ for (let k = 0; ; k++) {
188
+ try {
189
+ return await post(o.endpoint, body);
190
+ } catch (e) {
191
+ const delay = RETRIES[k];
192
+ if (delay === undefined) throw e;
193
+ await wait(delay);
194
+ }
195
+ }
196
+ }
197
+
198
+ interface Entry {
199
+ readonly head: Head;
200
+ readonly piece: Piece;
201
+ readonly seq: number;
202
+ cancelled: boolean;
203
+ }
204
+ /** Queued and not started: a beacon may still take them along. */
205
+ const pending: Array<Entry> = [];
206
+
207
+ async function deliver(entry: Entry) {
208
+ const { head, piece } = entry;
209
+ const local = new Map<string, string>();
210
+ const tape = await pack(piece.tape, piece.cuts, local);
211
+ for (const [h, v] of local) kept.set(h, v);
212
+ const body = JSON.stringify(
213
+ envelope(head, {
214
+ seq: entry.seq,
215
+ base: piece.base,
216
+ startedAt: piece.startedAt,
217
+ endedAt: piece.endedAt,
218
+ tape,
219
+ }),
220
+ );
221
+ let answer = await attempt(body);
222
+ // A piece may itself refer to long strings: the server asks again once it read the piece,
223
+ // so what this chunk refers to is kept until the server stops asking.
224
+ for (let round = 0; round < 3; round++) {
225
+ if (answer?.snap) o.onSnap?.();
226
+ const need = (answer?.need || []).filter((h) => kept.has(h));
227
+ if (!need.length) break;
228
+ for (const h of need) wanted.add(h);
229
+ const blobs: Record<string, string> = {};
230
+ for (const h of need) blobs[h] = kept.get(h) as string;
231
+ answer = await attempt(JSON.stringify(envelope(head, { blobs })));
232
+ for (const h of need) {
233
+ wanted.delete(h);
234
+ kept.delete(h);
235
+ }
236
+ }
237
+ for (const h of local.keys()) kept.delete(h);
238
+ }
239
+
240
+ /** The head of the page view, numbering again from 0 when it changed. */
241
+ function current(): Head | undefined {
242
+ const head = o.head();
243
+ if (head && head.pv !== pv) {
244
+ pv = head.pv;
245
+ seq = 0;
246
+ }
247
+ return head;
248
+ }
249
+
250
+ function send(piece: Piece): Promise<void> {
251
+ if (failed) return queue;
252
+ const head = current();
253
+ if (!head) {
254
+ held.push(piece);
255
+ return queue;
256
+ }
257
+ const pieces = [...held, piece];
258
+ held = [];
259
+ for (const p of pieces) {
260
+ if (!p.tape.length) continue;
261
+ const entry: Entry = { head, piece: p, seq: seq++, cancelled: false };
262
+ pending.push(entry);
263
+ queue = queue
264
+ .then(() => {
265
+ const k = pending.indexOf(entry);
266
+ if (k >= 0) pending.splice(k, 1);
267
+ if (failed || entry.cancelled) return;
268
+ return deliver(entry);
269
+ })
270
+ .catch(() => {
271
+ failed = true;
272
+ o.onFail?.();
273
+ });
274
+ }
275
+ return queue;
276
+ }
277
+
278
+ function leave(piece?: Piece) {
279
+ if (failed) return;
280
+ const head = current();
281
+ if (!head) return;
282
+ // What is queued and not started goes with the beacon, under the first number it held.
283
+ const queued = pending.filter((e) => e.head.pv === head.pv && !e.cancelled);
284
+ const pieces = [
285
+ ...queued.map((e) => e.piece),
286
+ ...held,
287
+ ...(piece && piece.tape.length ? [piece] : []),
288
+ ];
289
+ held = [];
290
+ // No time to hash: the tape goes as it is, then what the server still lacks, while it fits.
291
+ const tape: Tape = [];
292
+ for (const p of pieces) for (const t of p.tape) tape.push(t);
293
+ const first = pieces[0];
294
+ const lastPiece = pieces[pieces.length - 1];
295
+ const empty = JSON.stringify(envelope(head, { last: true }));
296
+ let body = empty;
297
+ if (first && lastPiece) {
298
+ const number = queued[0] ? queued[0].seq : seq;
299
+ const withTape = JSON.stringify(
300
+ envelope(head, {
301
+ seq: number,
302
+ base: first.base,
303
+ startedAt: first.startedAt,
304
+ endedAt: lastPiece.endedAt,
305
+ tape,
306
+ last: true,
307
+ }),
308
+ );
309
+ if (bytesOf(withTape) <= BEACON_BYTES) {
310
+ body = withTape;
311
+ for (const e of queued) e.cancelled = true;
312
+ seq = number + 1;
313
+ }
314
+ }
315
+ const blobs: Record<string, string> = {};
316
+ let size = bytesOf(body);
317
+ const order = [...wanted, ...[...kept.keys()].filter((h) => !wanted.has(h))];
318
+ for (const h of order) {
319
+ const v = kept.get(h);
320
+ if (v === undefined) continue;
321
+ const extra = bytesOf(JSON.stringify(h)) + bytesOf(JSON.stringify(v)) + 2;
322
+ if (size + extra + 12 > BEACON_BYTES) continue;
323
+ blobs[h] = v;
324
+ size += extra;
325
+ }
326
+ if (Object.keys(blobs).length) body = JSON.stringify({ ...(JSON.parse(body) as Envelope), blobs });
327
+ if (body === empty) return;
328
+ beacon(o.endpoint, body);
329
+ }
330
+
331
+ return {
332
+ send,
333
+ leave,
334
+ idle: () => queue,
335
+ get failed() {
336
+ return failed;
337
+ },
338
+ };
339
+ }