@usero/sdk 0.3.1 → 0.3.4
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.
- package/dist/plugins/session-replay.cjs +324 -67
- package/dist/plugins/session-replay.cjs.map +1 -1
- package/dist/plugins/session-replay.d.cts +33 -11
- package/dist/plugins/session-replay.d.ts +33 -11
- package/dist/plugins/session-replay.js +324 -68
- package/dist/plugins/session-replay.js.map +1 -1
- package/dist/plugins/user-test.cjs +528 -0
- package/dist/plugins/user-test.cjs.map +1 -0
- package/dist/plugins/user-test.d.cts +63 -0
- package/dist/plugins/user-test.d.ts +63 -0
- package/dist/plugins/user-test.js +525 -0
- package/dist/plugins/user-test.js.map +1 -0
- package/dist/react.cjs +12 -0
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +2 -0
- package/dist/react.d.ts +2 -0
- package/dist/react.js +12 -0
- package/dist/react.js.map +1 -1
- package/dist/usero.iife.js +27 -27
- package/dist/usero.iife.js.map +1 -1
- package/dist/vanilla.cjs +12 -0
- package/dist/vanilla.cjs.map +1 -1
- package/dist/vanilla.d.cts +2 -0
- package/dist/vanilla.d.ts +2 -0
- package/dist/vanilla.js +12 -0
- package/dist/vanilla.js.map +1 -1
- package/package.json +6 -1
|
@@ -1,43 +1,135 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
// src/plugins/session-replay.ts
|
|
4
|
-
var
|
|
5
|
-
bufferSeconds: 30,
|
|
4
|
+
var DEFAULTS = {
|
|
6
5
|
startAfterMs: 0,
|
|
7
6
|
sampleRate: 1,
|
|
8
7
|
sampling: { mousemove: 50, scroll: 100 },
|
|
9
8
|
maskAllInputs: true,
|
|
10
9
|
maskTextSelector: "[data-usero-mask]",
|
|
11
10
|
inlineStylesheet: true,
|
|
12
|
-
blockSelector: "[data-usero-block]"
|
|
11
|
+
blockSelector: "[data-usero-block]",
|
|
12
|
+
chunkSeconds: 10,
|
|
13
|
+
chunkMaxEvents: 5e3,
|
|
14
|
+
chunkMaxAttempts: 5,
|
|
15
|
+
apiUrl: ""
|
|
13
16
|
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const cutoff = now - bufferSeconds * 1e3;
|
|
17
|
-
let dropCount = 0;
|
|
18
|
-
for (const e of events) {
|
|
19
|
-
if (e.timestamp >= cutoff) break;
|
|
20
|
-
dropCount++;
|
|
21
|
-
}
|
|
22
|
-
if (dropCount > 0) events.splice(0, dropCount);
|
|
23
|
-
}
|
|
17
|
+
var SDK_SESSION_STORAGE_KEY = "usero:session-replay:sdk-session-id";
|
|
18
|
+
var HARD_CHUNK_BYTE_CAP = 4 * 1024 * 1024;
|
|
24
19
|
function uint8ToBase64(bytes) {
|
|
25
20
|
let binary = "";
|
|
26
21
|
const chunkSize = 32768;
|
|
27
22
|
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
28
|
-
const
|
|
29
|
-
binary += String.fromCharCode.apply(null, Array.from(
|
|
23
|
+
const slice = bytes.subarray(i, i + chunkSize);
|
|
24
|
+
binary += String.fromCharCode.apply(null, Array.from(slice));
|
|
30
25
|
}
|
|
31
26
|
return typeof btoa === "function" ? btoa(binary) : "";
|
|
32
27
|
}
|
|
33
|
-
async function
|
|
28
|
+
async function gzipBytes(input) {
|
|
34
29
|
if (typeof CompressionStream === "undefined") {
|
|
35
|
-
|
|
36
|
-
return uint8ToBase64(bytes);
|
|
30
|
+
return new TextEncoder().encode(input);
|
|
37
31
|
}
|
|
38
32
|
const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
39
|
-
const
|
|
40
|
-
return
|
|
33
|
+
const buf = await new Response(stream).arrayBuffer();
|
|
34
|
+
return new Uint8Array(buf);
|
|
35
|
+
}
|
|
36
|
+
function generateRandomId() {
|
|
37
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
38
|
+
return crypto.randomUUID();
|
|
39
|
+
}
|
|
40
|
+
const bytes = new Uint8Array(16);
|
|
41
|
+
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
42
|
+
crypto.getRandomValues(bytes);
|
|
43
|
+
} else {
|
|
44
|
+
for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
|
45
|
+
}
|
|
46
|
+
let out = "";
|
|
47
|
+
for (const b of bytes) out += b.toString(16).padStart(2, "0");
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function mintSdkSessionId() {
|
|
51
|
+
try {
|
|
52
|
+
const existing = window.sessionStorage?.getItem(SDK_SESSION_STORAGE_KEY);
|
|
53
|
+
if (existing && /^[a-z0-9-]{8,}$/i.test(existing)) return existing;
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
const id = generateRandomId();
|
|
57
|
+
try {
|
|
58
|
+
window.sessionStorage?.setItem(SDK_SESSION_STORAGE_KEY, id);
|
|
59
|
+
} catch {
|
|
60
|
+
}
|
|
61
|
+
return id;
|
|
62
|
+
}
|
|
63
|
+
function joinUrl(apiUrl, path) {
|
|
64
|
+
return `${apiUrl.replace(/\/$/, "")}${path}`;
|
|
65
|
+
}
|
|
66
|
+
async function createSession(apiUrl, clientId, sdkSessionId) {
|
|
67
|
+
try {
|
|
68
|
+
const startUrl = typeof window !== "undefined" && window.location ? window.location.href : void 0;
|
|
69
|
+
const userAgent = typeof navigator !== "undefined" && navigator.userAgent ? navigator.userAgent : void 0;
|
|
70
|
+
const res = await fetch(joinUrl(apiUrl, "/api/replay-sessions"), {
|
|
71
|
+
method: "POST",
|
|
72
|
+
headers: { "Content-Type": "application/json" },
|
|
73
|
+
body: JSON.stringify({
|
|
74
|
+
clientId,
|
|
75
|
+
sdkSessionId,
|
|
76
|
+
startUrl,
|
|
77
|
+
userAgent,
|
|
78
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
79
|
+
})
|
|
80
|
+
});
|
|
81
|
+
if (!res.ok) return null;
|
|
82
|
+
const json = await res.json();
|
|
83
|
+
if (typeof json.accepted !== "boolean") return null;
|
|
84
|
+
const result = { accepted: json.accepted };
|
|
85
|
+
if (typeof json.sessionReplayId === "string") result.sessionReplayId = json.sessionReplayId;
|
|
86
|
+
if (typeof json.dropReason === "string") result.dropReason = json.dropReason;
|
|
87
|
+
return result;
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function uploadChunk(apiUrl, sessionReplayId, clientId, seq, bytes, eventCount, durationMs, logger, maxAttempts) {
|
|
93
|
+
const url = joinUrl(
|
|
94
|
+
apiUrl,
|
|
95
|
+
`/api/replay-sessions/${encodeURIComponent(sessionReplayId)}/chunks/${seq}`
|
|
96
|
+
);
|
|
97
|
+
let attempt = 0;
|
|
98
|
+
while (attempt < maxAttempts) {
|
|
99
|
+
try {
|
|
100
|
+
const buffer = bytes.buffer.slice(
|
|
101
|
+
bytes.byteOffset,
|
|
102
|
+
bytes.byteOffset + bytes.byteLength
|
|
103
|
+
);
|
|
104
|
+
const blob = new Blob([buffer], { type: "application/octet-stream" });
|
|
105
|
+
const res = await fetch(url, {
|
|
106
|
+
method: "PUT",
|
|
107
|
+
body: blob,
|
|
108
|
+
headers: {
|
|
109
|
+
"Content-Type": "application/octet-stream",
|
|
110
|
+
"X-Usero-Client-Id": clientId,
|
|
111
|
+
"X-Usero-Event-Count": String(eventCount),
|
|
112
|
+
"X-Usero-Duration-Ms": String(Math.max(0, Math.round(durationMs)))
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
if (res.ok) return { ok: true, stopSession: false };
|
|
116
|
+
if (res.status === 409) {
|
|
117
|
+
logger.warn(`chunk ${seq} rejected with 409, stopping session`);
|
|
118
|
+
return { ok: false, stopSession: true };
|
|
119
|
+
}
|
|
120
|
+
if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) {
|
|
121
|
+
logger.error(`chunk ${seq} rejected with ${res.status}`);
|
|
122
|
+
return { ok: false, stopSession: false };
|
|
123
|
+
}
|
|
124
|
+
} catch (err) {
|
|
125
|
+
logger.warn(`chunk ${seq} attempt ${attempt + 1} failed`, err);
|
|
126
|
+
}
|
|
127
|
+
attempt += 1;
|
|
128
|
+
const backoff = Math.min(15e3, 500 * 2 ** attempt) + Math.floor(Math.random() * 250);
|
|
129
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
130
|
+
}
|
|
131
|
+
logger.error(`chunk ${seq} dropped after ${maxAttempts} attempts`);
|
|
132
|
+
return { ok: false, stopSession: false };
|
|
41
133
|
}
|
|
42
134
|
async function loadRrwebRecord() {
|
|
43
135
|
try {
|
|
@@ -53,20 +145,95 @@ async function loadRrwebRecord() {
|
|
|
53
145
|
return null;
|
|
54
146
|
}
|
|
55
147
|
}
|
|
148
|
+
function scheduleChunkUpload(store, ctx) {
|
|
149
|
+
if (!store.sessionReplayId) return;
|
|
150
|
+
if (store.pendingEvents.length === 0) return;
|
|
151
|
+
const events = store.pendingEvents;
|
|
152
|
+
const eventCount = events.length;
|
|
153
|
+
const firstTs = store.pendingFirstTs ?? 0;
|
|
154
|
+
const lastTs = store.pendingLastTs ?? firstTs;
|
|
155
|
+
const durationMs = Math.max(0, lastTs - firstTs);
|
|
156
|
+
const seq = store.nextChunkSeq;
|
|
157
|
+
store.nextChunkSeq += 1;
|
|
158
|
+
store.pendingEvents = [];
|
|
159
|
+
store.pendingFirstTs = null;
|
|
160
|
+
store.pendingLastTs = null;
|
|
161
|
+
const sessionReplayId = store.sessionReplayId;
|
|
162
|
+
const apiUrl = store.options.apiUrl;
|
|
163
|
+
const clientId = store.clientId;
|
|
164
|
+
const maxAttempts = store.options.chunkMaxAttempts;
|
|
165
|
+
store.pendingUploads += 1;
|
|
166
|
+
store.uploadQueue = store.uploadQueue.then(async () => {
|
|
167
|
+
try {
|
|
168
|
+
if (store.cancelled) return;
|
|
169
|
+
const json = JSON.stringify(events);
|
|
170
|
+
const bytes = await gzipBytes(json);
|
|
171
|
+
if (bytes.byteLength > HARD_CHUNK_BYTE_CAP) {
|
|
172
|
+
ctx.logger.error(
|
|
173
|
+
`chunk ${seq} exceeds 4MB hard cap (${bytes.byteLength} bytes), dropping`
|
|
174
|
+
);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const result = await uploadChunk(
|
|
178
|
+
apiUrl,
|
|
179
|
+
sessionReplayId,
|
|
180
|
+
clientId,
|
|
181
|
+
seq,
|
|
182
|
+
bytes,
|
|
183
|
+
eventCount,
|
|
184
|
+
durationMs,
|
|
185
|
+
ctx.logger,
|
|
186
|
+
maxAttempts
|
|
187
|
+
);
|
|
188
|
+
if (result.stopSession) {
|
|
189
|
+
store.stopped = true;
|
|
190
|
+
stopRrweb(store);
|
|
191
|
+
}
|
|
192
|
+
} catch (err) {
|
|
193
|
+
ctx.logger.error(`chunk ${seq} encode failed`, err);
|
|
194
|
+
} finally {
|
|
195
|
+
store.pendingUploads -= 1;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function flushPendingChunk(store, ctx) {
|
|
200
|
+
if (store.stopped || store.cancelled) return;
|
|
201
|
+
if (store.pendingEvents.length === 0) return;
|
|
202
|
+
scheduleChunkUpload(store, ctx);
|
|
203
|
+
}
|
|
204
|
+
function stopRrweb(store) {
|
|
205
|
+
if (store.stopRecording) {
|
|
206
|
+
try {
|
|
207
|
+
store.stopRecording();
|
|
208
|
+
} catch {
|
|
209
|
+
}
|
|
210
|
+
store.stopRecording = null;
|
|
211
|
+
}
|
|
212
|
+
if (store.chunkFlushTimer) {
|
|
213
|
+
clearInterval(store.chunkFlushTimer);
|
|
214
|
+
store.chunkFlushTimer = null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
56
217
|
function startRecording(store, ctx) {
|
|
57
|
-
if (store.cancelled || store.stopRecording || store.loadInProgress) return;
|
|
218
|
+
if (store.cancelled || store.stopped || store.stopRecording || store.loadInProgress) return;
|
|
58
219
|
store.loadInProgress = true;
|
|
59
220
|
void loadRrwebRecord().then((record) => {
|
|
60
221
|
store.loadInProgress = false;
|
|
61
|
-
if (store.cancelled || !record) {
|
|
222
|
+
if (store.cancelled || store.stopped || !record) {
|
|
62
223
|
if (!record) ctx.logger.warn("rrweb failed to load, replay disabled");
|
|
63
224
|
return;
|
|
64
225
|
}
|
|
65
226
|
try {
|
|
66
227
|
const stop = record({
|
|
67
228
|
emit: (event) => {
|
|
68
|
-
store.
|
|
69
|
-
|
|
229
|
+
if (store.stopped || store.cancelled) return;
|
|
230
|
+
if (store.recordingStartedAt === null) store.recordingStartedAt = event.timestamp;
|
|
231
|
+
store.pendingEvents.push(event);
|
|
232
|
+
if (store.pendingFirstTs === null) store.pendingFirstTs = event.timestamp;
|
|
233
|
+
store.pendingLastTs = event.timestamp;
|
|
234
|
+
if (store.pendingEvents.length >= store.options.chunkMaxEvents) {
|
|
235
|
+
scheduleChunkUpload(store, ctx);
|
|
236
|
+
}
|
|
70
237
|
},
|
|
71
238
|
maskAllInputs: store.options.maskAllInputs,
|
|
72
239
|
maskTextSelector: store.options.maskTextSelector || void 0,
|
|
@@ -75,45 +242,124 @@ function startRecording(store, ctx) {
|
|
|
75
242
|
sampling: store.options.sampling
|
|
76
243
|
});
|
|
77
244
|
store.stopRecording = stop;
|
|
245
|
+
store.record = record;
|
|
246
|
+
scheduleShadowSnapshot(store, ctx);
|
|
247
|
+
store.chunkFlushTimer = setInterval(
|
|
248
|
+
() => flushPendingChunk(store, ctx),
|
|
249
|
+
store.options.chunkSeconds * 1e3
|
|
250
|
+
);
|
|
78
251
|
} catch (err) {
|
|
79
252
|
ctx.logger.error("rrweb record() threw", err);
|
|
80
253
|
}
|
|
81
254
|
});
|
|
82
255
|
}
|
|
256
|
+
function scheduleShadowSnapshot(store, ctx) {
|
|
257
|
+
if (store.cancelled || store.stopped || !store.record || !store.stopRecording) return;
|
|
258
|
+
const fn = store.record.takeFullSnapshot;
|
|
259
|
+
if (typeof fn !== "function") return;
|
|
260
|
+
try {
|
|
261
|
+
fn(true);
|
|
262
|
+
} catch (err) {
|
|
263
|
+
ctx.logger.warn("takeFullSnapshot threw", err);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function finalise(store, ctx, opts) {
|
|
267
|
+
if (!store.sessionReplayId) return;
|
|
268
|
+
if (store.pendingEvents.length > 0) flushPendingChunk(store, ctx);
|
|
269
|
+
const url = joinUrl(
|
|
270
|
+
store.options.apiUrl,
|
|
271
|
+
`/api/replay-sessions/${encodeURIComponent(store.sessionReplayId)}/finalise`
|
|
272
|
+
);
|
|
273
|
+
const body = JSON.stringify({ clientId: store.clientId, endedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
274
|
+
if (opts.useBeacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
|
|
275
|
+
try {
|
|
276
|
+
const blob = new Blob([body], { type: "application/json" });
|
|
277
|
+
navigator.sendBeacon(url, blob);
|
|
278
|
+
return;
|
|
279
|
+
} catch (err) {
|
|
280
|
+
ctx.logger.warn("finalise sendBeacon threw", err);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
void fetch(url, {
|
|
284
|
+
method: "POST",
|
|
285
|
+
body,
|
|
286
|
+
headers: { "Content-Type": "application/json" },
|
|
287
|
+
keepalive: true
|
|
288
|
+
}).catch((err) => ctx.logger.warn("finalise fetch failed", err));
|
|
289
|
+
}
|
|
83
290
|
function sessionReplay(options = {}) {
|
|
84
291
|
const merged = {
|
|
85
|
-
...
|
|
292
|
+
...DEFAULTS,
|
|
86
293
|
...options,
|
|
87
|
-
sampling: { ...
|
|
294
|
+
sampling: { ...DEFAULTS.sampling, ...options.sampling ?? {} }
|
|
88
295
|
};
|
|
89
296
|
return {
|
|
90
297
|
name: "session-replay",
|
|
91
298
|
onInit(ctx) {
|
|
299
|
+
if (typeof window === "undefined") return;
|
|
92
300
|
if (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {
|
|
93
301
|
ctx.logger.debug("skipped by sampleRate");
|
|
94
302
|
return;
|
|
95
303
|
}
|
|
96
|
-
|
|
304
|
+
const apiUrl = merged.apiUrl || ctx.baseUrl;
|
|
305
|
+
if (!apiUrl) {
|
|
306
|
+
ctx.logger.error("session-replay needs an apiUrl (via options or PluginContext)");
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const sdkSessionId = mintSdkSessionId();
|
|
97
310
|
const store = {
|
|
98
|
-
|
|
99
|
-
|
|
311
|
+
options: { ...merged, apiUrl },
|
|
312
|
+
clientId: ctx.clientId,
|
|
313
|
+
sdkSessionId,
|
|
314
|
+
sessionReplayId: null,
|
|
315
|
+
recordingStartedAt: null,
|
|
316
|
+
pendingEvents: [],
|
|
317
|
+
pendingFirstTs: null,
|
|
318
|
+
pendingLastTs: null,
|
|
319
|
+
nextChunkSeq: 0,
|
|
320
|
+
uploadQueue: Promise.resolve(),
|
|
321
|
+
pendingUploads: 0,
|
|
322
|
+
chunkFlushTimer: null,
|
|
100
323
|
startTimer: null,
|
|
101
324
|
pageHideHandler: null,
|
|
325
|
+
shadowUpdateHandler: null,
|
|
326
|
+
record: null,
|
|
327
|
+
stopRecording: null,
|
|
102
328
|
loadInProgress: false,
|
|
103
329
|
cancelled: false,
|
|
104
|
-
|
|
330
|
+
stopped: false
|
|
105
331
|
};
|
|
106
332
|
ctx.setStore(store);
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
333
|
+
const onShadowUpdate = () => scheduleShadowSnapshot(store, ctx);
|
|
334
|
+
store.shadowUpdateHandler = onShadowUpdate;
|
|
335
|
+
window.addEventListener("usero:shadow-update", onShadowUpdate);
|
|
336
|
+
const onPageHide = () => {
|
|
337
|
+
finalise(store, ctx, { useBeacon: true });
|
|
338
|
+
store.stopped = true;
|
|
339
|
+
stopRrweb(store);
|
|
340
|
+
};
|
|
341
|
+
store.pageHideHandler = onPageHide;
|
|
342
|
+
window.addEventListener("pagehide", onPageHide);
|
|
343
|
+
const begin = async () => {
|
|
344
|
+
if (store.cancelled) return;
|
|
345
|
+
const created = await createSession(apiUrl, ctx.clientId, sdkSessionId);
|
|
346
|
+
if (!created) {
|
|
347
|
+
ctx.logger.warn("session create failed, replay disabled");
|
|
348
|
+
store.stopped = true;
|
|
349
|
+
return;
|
|
111
350
|
}
|
|
112
|
-
if (
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
351
|
+
if (!created.accepted) {
|
|
352
|
+
ctx.logger.info(`session-replay declined: ${created.dropReason ?? "unknown"}`);
|
|
353
|
+
store.stopped = true;
|
|
354
|
+
return;
|
|
116
355
|
}
|
|
356
|
+
if (!created.sessionReplayId) {
|
|
357
|
+
ctx.logger.error("server accepted but returned no sessionReplayId");
|
|
358
|
+
store.stopped = true;
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
store.sessionReplayId = created.sessionReplayId;
|
|
362
|
+
store.recordingStartedAt = Date.now();
|
|
117
363
|
startRecording(store, ctx);
|
|
118
364
|
};
|
|
119
365
|
if (merged.startAfterMs > 0) {
|
|
@@ -123,56 +369,67 @@ function sessionReplay(options = {}) {
|
|
|
123
369
|
clearTimeout(store.startTimer);
|
|
124
370
|
store.startTimer = null;
|
|
125
371
|
}
|
|
126
|
-
if (store.pageHideHandler) {
|
|
127
|
-
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
128
|
-
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
129
|
-
store.pageHideHandler = null;
|
|
130
|
-
}
|
|
131
372
|
};
|
|
132
|
-
store.pageHideHandler = cancelOnExit;
|
|
133
373
|
window.addEventListener("pagehide", cancelOnExit, { once: true });
|
|
134
374
|
window.addEventListener("beforeunload", cancelOnExit, { once: true });
|
|
135
|
-
store.startTimer = setTimeout(
|
|
375
|
+
store.startTimer = setTimeout(() => {
|
|
376
|
+
void begin();
|
|
377
|
+
}, merged.startAfterMs);
|
|
136
378
|
} else {
|
|
137
|
-
begin();
|
|
379
|
+
void begin();
|
|
138
380
|
}
|
|
139
381
|
},
|
|
140
|
-
|
|
382
|
+
onFeedbackSubmit(ctx) {
|
|
141
383
|
const store = ctx.getStore();
|
|
142
|
-
if (!store || store.cancelled || store.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const replayEvents = await gzipString(json);
|
|
147
|
-
return { replayEvents };
|
|
148
|
-
} catch (err) {
|
|
149
|
-
ctx.logger.error("failed to encode replay buffer", err);
|
|
150
|
-
return void 0;
|
|
151
|
-
}
|
|
384
|
+
if (!store || store.cancelled || store.stopped) return void 0;
|
|
385
|
+
if (!store.sessionReplayId) return void 0;
|
|
386
|
+
const offsetMs = store.recordingStartedAt !== null ? Math.max(0, Date.now() - store.recordingStartedAt) : 0;
|
|
387
|
+
return { sessionReplayId: store.sessionReplayId, replayOffsetMs: offsetMs };
|
|
152
388
|
},
|
|
153
389
|
onDestroy(ctx) {
|
|
154
390
|
const store = ctx.getStore();
|
|
155
391
|
if (!store) return;
|
|
156
392
|
store.cancelled = true;
|
|
157
|
-
if (store.startTimer)
|
|
393
|
+
if (store.startTimer) {
|
|
394
|
+
clearTimeout(store.startTimer);
|
|
395
|
+
store.startTimer = null;
|
|
396
|
+
}
|
|
158
397
|
if (store.pageHideHandler) {
|
|
159
398
|
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
160
|
-
|
|
399
|
+
store.pageHideHandler = null;
|
|
161
400
|
}
|
|
162
|
-
if (store.
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
401
|
+
if (store.shadowUpdateHandler) {
|
|
402
|
+
window.removeEventListener("usero:shadow-update", store.shadowUpdateHandler);
|
|
403
|
+
store.shadowUpdateHandler = null;
|
|
404
|
+
}
|
|
405
|
+
if (store.sessionReplayId && !store.stopped) {
|
|
406
|
+
finalise(store, ctx, { useBeacon: false });
|
|
168
407
|
}
|
|
169
|
-
store.
|
|
408
|
+
store.stopped = true;
|
|
409
|
+
stopRrweb(store);
|
|
410
|
+
store.pendingEvents.length = 0;
|
|
170
411
|
}
|
|
171
412
|
};
|
|
172
413
|
}
|
|
173
|
-
|
|
414
|
+
function getCurrentSession(ctx) {
|
|
415
|
+
const store = ctx.getStore();
|
|
416
|
+
if (!store || store.cancelled || store.stopped || !store.sessionReplayId) return null;
|
|
417
|
+
const offsetMs = store.recordingStartedAt !== null ? Math.max(0, Date.now() - store.recordingStartedAt) : 0;
|
|
418
|
+
return { id: store.sessionReplayId, offsetMs };
|
|
419
|
+
}
|
|
420
|
+
var __test__ = {
|
|
421
|
+
uint8ToBase64,
|
|
422
|
+
gzipBytes,
|
|
423
|
+
mintSdkSessionId,
|
|
424
|
+
uploadChunk,
|
|
425
|
+
createSession,
|
|
426
|
+
joinUrl,
|
|
427
|
+
HARD_CHUNK_BYTE_CAP,
|
|
428
|
+
SDK_SESSION_STORAGE_KEY
|
|
429
|
+
};
|
|
174
430
|
|
|
175
431
|
exports.__test__ = __test__;
|
|
432
|
+
exports.getCurrentSession = getCurrentSession;
|
|
176
433
|
exports.sessionReplay = sessionReplay;
|
|
177
434
|
//# sourceMappingURL=session-replay.cjs.map
|
|
178
435
|
//# sourceMappingURL=session-replay.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/session-replay.ts"],"names":[],"mappings":";;;AA4FA,IAAM,eAAA,GAEF;AAAA,EACH,aAAA,EAAe,EAAA;AAAA,EACf,YAAA,EAAc,CAAA;AAAA,EACd,UAAA,EAAY,CAAA;AAAA,EACZ,QAAA,EAAU,EAAE,SAAA,EAAW,EAAA,EAAI,QAAQ,GAAA,EAAI;AAAA,EACvC,aAAA,EAAe,IAAA;AAAA,EACf,gBAAA,EAAkB,mBAAA;AAAA,EAClB,gBAAA,EAAkB,IAAA;AAAA,EAClB,aAAA,EAAe;AAChB,CAAA;AAEA,SAAS,cAAA,CAAe,MAAA,EAAsB,aAAA,EAAuB,GAAA,EAAmB;AACvF,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACzB,EAAA,MAAM,MAAA,GAAS,MAA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A,CAAO,IAAA,CAAK,kBAAA,EAAoB,GAAG,CAAA;AAAA,QACxC;AAAA,MACD;AACA,MAAA,KAAA,CAAM,OAAO,MAAA,GAAS,CAAA;AAAA,IACvB;AAAA,GACD;AACD;AAGO,IAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,UAAA,EAAY,aAAA","file":"session-replay.cjs","sourcesContent":["// Session replay plugin for the Usero widget.\n//\n// Lazy-loads rrweb the first time it's actually needed and keeps a rolling\n// in-memory buffer of the last `bufferSeconds` of events. On feedback\n// submit, the buffer is gzipped via the native CompressionStream API and\n// attached as `replayEvents` (base64 string) on the outgoing payload.\n//\n// Bundle hygiene is the whole point of this plugin existing as its own\n// subpath export. Importing this module pulls in the small wrapper below;\n// the heavy rrweb dependency only loads at runtime via dynamic `import()`.\n//\n// Privacy defaults err on the side of safety: all <input>/<textarea> values\n// are masked, anything tagged `data-usero-mask` is masked too, and inline\n// styles are inlined so we never leak external stylesheet URLs.\n\nimport type { UseroPlugin, PluginContext } from '../plugin'\nimport type { FeedbackSubmission } from '../types'\n\n// We deliberately avoid importing rrweb's types at the top level — that\n// would force consumers to install rrweb as a peer dep and would also pull\n// the type declarations into our published .d.ts files. Plugin internals\n// use a minimal local shape and rely on rrweb's runtime API only.\n\n// rrweb event sample-rate map. Keys match rrweb's `sampling` option. See\n// https://github.com/rrweb-io/rrweb/blob/master/guide.md#options for the\n// full list. We expose the two that matter most (mousemove, scroll).\nexport interface ReplaySampling {\n\t// Capture a mousemove event at most every N ms (default 50).\n\tmousemove?: number\n\t// Capture a scroll event at most every N ms (default 100).\n\tscroll?: number\n\t// Capture a media-interaction event at most every N ms.\n\tmedia?: number\n\t// Capture an input event at most every N ms, or 'last' to keep only the\n\t// final input value per element.\n\tinput?: number | 'last'\n}\n\nexport interface SessionReplayOptions {\n\t// Length of the rolling buffer in seconds. Older events are evicted as\n\t// new ones arrive. Default 30.\n\tbufferSeconds?: number\n\t// Wait this many ms after page load before loading rrweb and starting\n\t// to record. If the user navigates away before this elapses, rrweb is\n\t// never loaded. Default 0 (start immediately).\n\tstartAfterMs?: number\n\t// Probability (0..1) that this session records at all. Decided once at\n\t// init via Math.random(). Sessions that lose the dice roll never load\n\t// rrweb. Default 1 (always record).\n\tsampleRate?: number\n\t// rrweb sampling rates per event type. See ReplaySampling above.\n\tsampling?: ReplaySampling\n\t// Mask all <input>/<textarea> values in the recording. Default true.\n\tmaskAllInputs?: boolean\n\t// CSS selector for nodes whose text content should be masked. Default\n\t// `[data-usero-mask]`. Pass an empty string to disable selector masking.\n\tmaskTextSelector?: string\n\t// Inline external stylesheets into the recording so the replay viewer\n\t// renders correctly without network access. Default true.\n\tinlineStylesheet?: boolean\n\t// Block (entirely skip) DOM subtrees matching this selector. Default\n\t// `[data-usero-block]`.\n\tblockSelector?: string\n}\n\ninterface RrwebEvent {\n\ttype: number\n\tdata: unknown\n\ttimestamp: number\n}\n\ninterface RrwebRecordOptions {\n\temit: (event: RrwebEvent) => void\n\tmaskAllInputs?: boolean\n\tmaskTextSelector?: string\n\tinlineStylesheet?: boolean\n\tblockSelector?: string\n\tsampling?: ReplaySampling\n}\n\ntype RrwebRecord = (opts: RrwebRecordOptions) => () => void\n\ninterface ReplayStore {\n\tevents: RrwebEvent[]\n\tstopRecording: (() => void) | null\n\tstartTimer: ReturnType<typeof setTimeout> | null\n\tpageHideHandler: (() => void) | null\n\tloadInProgress: boolean\n\tcancelled: boolean\n\toptions: Required<Omit<SessionReplayOptions, 'sampling'>> & { sampling: ReplaySampling }\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<SessionReplayOptions, 'sampling'>> & {\n\tsampling: ReplaySampling\n} = {\n\tbufferSeconds: 30,\n\tstartAfterMs: 0,\n\tsampleRate: 1,\n\tsampling: { mousemove: 50, scroll: 100 },\n\tmaskAllInputs: true,\n\tmaskTextSelector: '[data-usero-mask]',\n\tinlineStylesheet: true,\n\tblockSelector: '[data-usero-block]',\n}\n\nfunction evictOldEvents(events: RrwebEvent[], bufferSeconds: number, now: number): void {\n\tif (events.length === 0) return\n\tconst cutoff = now - bufferSeconds * 1000\n\t// Events are appended in chronological order; find the first event\n\t// inside the window with a linear scan from the head and splice once.\n\tlet dropCount = 0\n\tfor (const e of events) {\n\t\tif (e.timestamp >= cutoff) break\n\t\tdropCount++\n\t}\n\tif (dropCount > 0) events.splice(0, dropCount)\n}\n\n// Convert a Uint8Array to base64 without bringing in a dependency. Chunked\n// to avoid blowing the call stack on large buffers.\nfunction uint8ToBase64(bytes: Uint8Array): string {\n\tlet binary = ''\n\tconst chunkSize = 0x8000\n\tfor (let i = 0; i < bytes.length; i += chunkSize) {\n\t\tconst chunk = bytes.subarray(i, i + chunkSize)\n\t\tbinary += String.fromCharCode.apply(null, Array.from(chunk))\n\t}\n\treturn typeof btoa === 'function' ? btoa(binary) : ''\n}\n\nasync function gzipString(input: string): Promise<string> {\n\tif (typeof CompressionStream === 'undefined') {\n\t\t// Browsers without CompressionStream (very old) fall back to raw\n\t\t// base64 of the JSON. The server can detect this by sniffing the\n\t\t// gzip magic bytes; cheaper than shipping a JS gzip lib.\n\t\tconst bytes = new TextEncoder().encode(input)\n\t\treturn uint8ToBase64(bytes)\n\t}\n\tconst stream = new Blob([input]).stream().pipeThrough(new CompressionStream('gzip'))\n\tconst compressed = await new Response(stream).arrayBuffer()\n\treturn uint8ToBase64(new Uint8Array(compressed))\n}\n\nasync function loadRrwebRecord(): Promise<RrwebRecord | null> {\n\ttry {\n\t\tconst mod: unknown = await import(/* webpackChunkName: \"rrweb\" */ 'rrweb')\n\t\tif (\n\t\t\tmod &&\n\t\t\ttypeof mod === 'object' &&\n\t\t\t'record' in mod &&\n\t\t\ttypeof (mod as { record: unknown }).record === 'function'\n\t\t) {\n\t\t\treturn (mod as { record: RrwebRecord }).record\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction startRecording(store: ReplayStore, ctx: PluginContext): void {\n\tif (store.cancelled || store.stopRecording || store.loadInProgress) return\n\tstore.loadInProgress = true\n\tvoid loadRrwebRecord().then(record => {\n\t\tstore.loadInProgress = false\n\t\t// Window may have been torn down between the import resolving and\n\t\t// us getting here. Don't start a recording into a destroyed plugin.\n\t\tif (store.cancelled || !record) {\n\t\t\tif (!record) ctx.logger.warn('rrweb failed to load, replay disabled')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tconst stop = record({\n\t\t\t\temit: event => {\n\t\t\t\t\tstore.events.push(event)\n\t\t\t\t\tevictOldEvents(store.events, store.options.bufferSeconds, event.timestamp)\n\t\t\t\t},\n\t\t\t\tmaskAllInputs: store.options.maskAllInputs,\n\t\t\t\tmaskTextSelector: store.options.maskTextSelector || undefined,\n\t\t\t\tinlineStylesheet: store.options.inlineStylesheet,\n\t\t\t\tblockSelector: store.options.blockSelector,\n\t\t\t\tsampling: store.options.sampling,\n\t\t\t})\n\t\t\tstore.stopRecording = stop\n\t\t} catch (err) {\n\t\t\tctx.logger.error('rrweb record() threw', err)\n\t\t}\n\t})\n}\n\nexport function sessionReplay(options: SessionReplayOptions = {}): UseroPlugin {\n\tconst merged = {\n\t\t...DEFAULT_OPTIONS,\n\t\t...options,\n\t\tsampling: { ...DEFAULT_OPTIONS.sampling, ...(options.sampling ?? {}) },\n\t}\n\n\treturn {\n\t\tname: 'session-replay',\n\t\tonInit(ctx) {\n\t\t\t// Lose the dice roll? Don't even prepare to load rrweb.\n\t\t\tif (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {\n\t\t\t\tctx.logger.debug('skipped by sampleRate')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (typeof window === 'undefined') return\n\n\t\t\tconst store: ReplayStore = {\n\t\t\t\tevents: [],\n\t\t\t\tstopRecording: null,\n\t\t\t\tstartTimer: null,\n\t\t\t\tpageHideHandler: null,\n\t\t\t\tloadInProgress: false,\n\t\t\t\tcancelled: false,\n\t\t\t\toptions: merged,\n\t\t\t}\n\t\t\tctx.setStore(store)\n\n\t\t\tconst begin = (): void => {\n\t\t\t\tif (store.startTimer) {\n\t\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\t\tstore.startTimer = null\n\t\t\t\t}\n\t\t\t\tif (store.pageHideHandler) {\n\t\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t\t\tstore.pageHideHandler = null\n\t\t\t\t}\n\t\t\t\tstartRecording(store, ctx)\n\t\t\t}\n\n\t\t\tif (merged.startAfterMs > 0) {\n\t\t\t\t// Engagement gate: only load rrweb if the user is still on the\n\t\t\t\t// page after `startAfterMs`. If they navigate away first we\n\t\t\t\t// cancel and never pull the heavy module.\n\t\t\t\tconst cancelOnExit = (): void => {\n\t\t\t\t\tstore.cancelled = true\n\t\t\t\t\tif (store.startTimer) {\n\t\t\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\t\t\tstore.startTimer = null\n\t\t\t\t\t}\n\t\t\t\t\tif (store.pageHideHandler) {\n\t\t\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t\t\t\tstore.pageHideHandler = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstore.pageHideHandler = cancelOnExit\n\t\t\t\twindow.addEventListener('pagehide', cancelOnExit, { once: true })\n\t\t\t\twindow.addEventListener('beforeunload', cancelOnExit, { once: true })\n\t\t\t\tstore.startTimer = setTimeout(begin, merged.startAfterMs)\n\t\t\t} else {\n\t\t\t\tbegin()\n\t\t\t}\n\t\t},\n\t\tasync onFeedbackSubmit(ctx): Promise<Partial<FeedbackSubmission> | undefined> {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store || store.cancelled || store.events.length === 0) return undefined\n\t\t\t// Snapshot the current buffer so concurrent emits can't mutate\n\t\t\t// what we're serializing.\n\t\t\tconst snapshot = store.events.slice()\n\t\t\ttry {\n\t\t\t\tconst json = JSON.stringify(snapshot)\n\t\t\t\tconst replayEvents = await gzipString(json)\n\t\t\t\treturn { replayEvents }\n\t\t\t} catch (err) {\n\t\t\t\tctx.logger.error('failed to encode replay buffer', err)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t},\n\t\tonDestroy(ctx) {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store) return\n\t\t\tstore.cancelled = true\n\t\t\tif (store.startTimer) clearTimeout(store.startTimer)\n\t\t\tif (store.pageHideHandler) {\n\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t}\n\t\t\tif (store.stopRecording) {\n\t\t\t\ttry {\n\t\t\t\t\tstore.stopRecording()\n\t\t\t\t} catch (err) {\n\t\t\t\t\tctx.logger.warn('rrweb stop threw', err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tstore.events.length = 0\n\t\t},\n\t}\n}\n\n// Internal helper exports for testing only. Not part of the public API.\nexport const __test__ = { evictOldEvents, gzipString, uint8ToBase64 }\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/session-replay.ts"],"names":[],"mappings":";;;AA0IA,IAAM,QAAA,GAA4B;AAAA,EACjC,YAAA,EAAc,CAAA;AAAA,EACd,UAAA,EAAY,CAAA;AAAA,EACZ,QAAA,EAAU,EAAE,SAAA,EAAW,EAAA,EAAI,QAAQ,GAAA,EAAI;AAAA,EACvC,aAAA,EAAe,IAAA;AAAA,EACf,gBAAA,EAAkB,mBAAA;AAAA,EAClB,gBAAA,EAAkB,IAAA;AAAA,EAClB,aAAA,EAAe,oBAAA;AAAA,EACf,YAAA,EAAc,EAAA;AAAA,EACd,cAAA,EAAgB,GAAA;AAAA,EAChB,gBAAA,EAAkB,CAAA;AAAA,EAClB,MAAA,EAAQ;AACT,CAAA;AAEA,IAAM,uBAAA,GAA0B,qCAAA;AAChC,IAAM,mBAAA,GAAsB,IAAI,IAAA,GAAO,IAAA;AAEvC,SAA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,OAAO,IAAA;AACjF,EAAA,MAAM,QAAA,GACL,KAAA,CAAM,kBAAA,KAAuB,IAAA,GAC1B,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,GAAA,EAAI,GAAI,KAAA,CAAM,kBAAkB,CAAA,GACjD,CAAA;AACJ,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,CAAM,eAAA,EAAiB,QAAA,EAAS;AAC9C;AAGO,IAAM,QAAA,GAAW;AAAA,EACvB,aAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,OAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACD","file":"session-replay.cjs","sourcesContent":["// Session replay plugin for the Usero widget.\n//\n// Streams rrweb events to the SaaS side as gzipped chunks while the user\n// is on the page, instead of buffering in memory and attaching to a\n// feedback submission. This decouples session replay from feedback so we\n// capture every session (subject to bot-gate + sampling + engagement\n// gates), not just the ones that submit feedback.\n//\n// Lifecycle:\n// 1. onInit: dice-roll sample, optional engagement-time gate, mint a\n// stable per-tab `sdkSessionId` in sessionStorage, and POST to\n// /api/replay-sessions to create the row. If the server returns\n// `{accepted:false}` (bot-gated), the plugin no-ops the rest of the\n// session and getCurrentSession() returns null.\n// 2. Recording: lazy-load rrweb, append events to a buffer, flush a\n// chunk every `chunkSeconds` (or sooner if the buffer is large).\n// Each chunk is gzipped via CompressionStream and PUT to\n// /api/replay-sessions/:id/chunks/:seq with raw bytes + the three\n// X-Usero-* headers (Client-Id, Event-Count, Duration-Ms). Retries\n// with exponential backoff. R2 head-check makes retries idempotent\n// server-side. A chunk PUT returning 409 stops the session.\n// 3. onFeedbackSubmit: returns `{sessionReplayId, replayOffsetMs}` so\n// the feedback record can FK at the moment of submit. Does NOT\n// attach `replayEvents` (legacy field) — chunked uploads carry the\n// events out-of-band.\n// 4. onDestroy / pagehide: best-effort flush remaining buffer, then\n// sendBeacon to /api/replay-sessions/:id/finalise with the\n// end-timestamp. Idempotent server-side.\n//\n// Bundle hygiene: rrweb stays lazy via dynamic `import('rrweb')` behind\n// the engagement gate, so consumers who lose the dice roll or navigate\n// away inside the gate window pay zero rrweb bytes.\n\nimport type { UseroPlugin, PluginContext } from '../plugin'\n\nexport interface ReplaySampling {\n\tmousemove?: number\n\tscroll?: number\n\tmedia?: number\n\tinput?: number | 'last'\n}\n\nexport interface SessionReplayOptions {\n\t// Wait this many ms after page load before loading rrweb and creating\n\t// the session row. If the user navigates away first, rrweb is never\n\t// loaded and no session row is created. Default 0 (start immediately).\n\tstartAfterMs?: number\n\t// Probability (0..1) that this session records at all. Decided once\n\t// at init via Math.random(). Default 1.\n\tsampleRate?: number\n\t// rrweb sampling rates per event type.\n\tsampling?: ReplaySampling\n\t// Mask all <input>/<textarea> values in the recording. Default true.\n\tmaskAllInputs?: boolean\n\t// CSS selector for nodes whose text content should be masked. Default\n\t// `[data-usero-mask]`.\n\tmaskTextSelector?: string\n\t// Inline external stylesheets so the replay viewer renders correctly\n\t// without network access. Default true.\n\tinlineStylesheet?: boolean\n\t// Block (entirely skip) DOM subtrees matching this selector. Default\n\t// `[data-usero-block]`.\n\tblockSelector?: string\n\t// Flush a chunk every N seconds. Default 10. Smaller = more PUTs but\n\t// less data lost on tab crash.\n\tchunkSeconds?: number\n\t// Soft cap on buffered events before forcing a flush, regardless of\n\t// time. Default 5000.\n\tchunkMaxEvents?: number\n\t// Max attempts per chunk before giving up. Default 5.\n\tchunkMaxAttempts?: number\n\t// API origin. Override for self-hosted or local dev. Defaults to the\n\t// PluginContext baseUrl threaded through by the widget.\n\tapiUrl?: string\n}\n\ninterface RrwebEvent {\n\ttype: number\n\tdata: unknown\n\ttimestamp: number\n}\n\ninterface RrwebRecordOptions {\n\temit: (event: RrwebEvent) => void\n\tmaskAllInputs?: boolean\n\tmaskTextSelector?: string\n\tinlineStylesheet?: boolean\n\tblockSelector?: string\n\tsampling?: ReplaySampling\n}\n\ninterface RrwebRecordFn {\n\t(opts: RrwebRecordOptions): () => void\n\ttakeFullSnapshot?: (isCheckout?: boolean) => void\n}\n\ntype RrwebRecord = RrwebRecordFn\n\ninterface ResolvedOptions {\n\tstartAfterMs: number\n\tsampleRate: number\n\tsampling: ReplaySampling\n\tmaskAllInputs: boolean\n\tmaskTextSelector: string\n\tinlineStylesheet: boolean\n\tblockSelector: string\n\tchunkSeconds: number\n\tchunkMaxEvents: number\n\tchunkMaxAttempts: number\n\tapiUrl: string\n}\n\ninterface ReplayStore {\n\toptions: ResolvedOptions\n\tclientId: string\n\tsdkSessionId: string\n\tsessionReplayId: string | null\n\t// Wall-clock timestamp (ms) of the first event we ever recorded.\n\t// Used to compute replayOffsetMs at feedback-submit time.\n\trecordingStartedAt: number | null\n\tpendingEvents: RrwebEvent[]\n\tpendingFirstTs: number | null\n\tpendingLastTs: number | null\n\tnextChunkSeq: number\n\tuploadQueue: Promise<void>\n\tpendingUploads: number\n\tchunkFlushTimer: ReturnType<typeof setInterval> | null\n\tstartTimer: ReturnType<typeof setTimeout> | null\n\tpageHideHandler: (() => void) | null\n\tshadowUpdateHandler: ((event: Event) => void) | null\n\trecord: RrwebRecord | null\n\tstopRecording: (() => void) | null\n\tloadInProgress: boolean\n\tcancelled: boolean\n\t// True once the session is \"done\": bot-gated, finalised, or destroyed.\n\tstopped: boolean\n}\n\nconst DEFAULTS: ResolvedOptions = {\n\tstartAfterMs: 0,\n\tsampleRate: 1,\n\tsampling: { mousemove: 50, scroll: 100 },\n\tmaskAllInputs: true,\n\tmaskTextSelector: '[data-usero-mask]',\n\tinlineStylesheet: true,\n\tblockSelector: '[data-usero-block]',\n\tchunkSeconds: 10,\n\tchunkMaxEvents: 5000,\n\tchunkMaxAttempts: 5,\n\tapiUrl: '',\n}\n\nconst SDK_SESSION_STORAGE_KEY = 'usero:session-replay:sdk-session-id'\nconst HARD_CHUNK_BYTE_CAP = 4 * 1024 * 1024\n\nfunction uint8ToBase64(bytes: Uint8Array): string {\n\tlet binary = ''\n\tconst chunkSize = 0x8000\n\tfor (let i = 0; i < bytes.length; i += chunkSize) {\n\t\tconst slice = bytes.subarray(i, i + chunkSize)\n\t\tbinary += String.fromCharCode.apply(null, Array.from(slice))\n\t}\n\treturn typeof btoa === 'function' ? btoa(binary) : ''\n}\n\nasync function gzipBytes(input: string): Promise<Uint8Array> {\n\tif (typeof CompressionStream === 'undefined') {\n\t\t// Old browsers: send uncompressed JSON. Acceptable degradation;\n\t\t// the server endpoint accepts raw application/octet-stream.\n\t\treturn new TextEncoder().encode(input)\n\t}\n\tconst stream = new Blob([input]).stream().pipeThrough(new CompressionStream('gzip'))\n\tconst buf = await new Response(stream).arrayBuffer()\n\treturn new Uint8Array(buf)\n}\n\nfunction generateRandomId(): string {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID()\n\t}\n\tconst bytes = new Uint8Array(16)\n\tif (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n\t\tcrypto.getRandomValues(bytes)\n\t} else {\n\t\tfor (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256)\n\t}\n\tlet out = ''\n\tfor (const b of bytes) out += b.toString(16).padStart(2, '0')\n\treturn out\n}\n\nfunction mintSdkSessionId(): string {\n\ttry {\n\t\tconst existing = window.sessionStorage?.getItem(SDK_SESSION_STORAGE_KEY)\n\t\tif (existing && /^[a-z0-9-]{8,}$/i.test(existing)) return existing\n\t} catch {\n\t\t// sessionStorage can throw in sandboxed iframes — fall through.\n\t}\n\tconst id = generateRandomId()\n\ttry {\n\t\twindow.sessionStorage?.setItem(SDK_SESSION_STORAGE_KEY, id)\n\t} catch {\n\t\t// Ignore: we still return the freshly minted id.\n\t}\n\treturn id\n}\n\nfunction joinUrl(apiUrl: string, path: string): string {\n\treturn `${apiUrl.replace(/\\/$/, '')}${path}`\n}\n\ninterface CreateSessionResult {\n\taccepted: boolean\n\tsessionReplayId?: string\n\tdropReason?: string\n}\n\nasync function createSession(\n\tapiUrl: string,\n\tclientId: string,\n\tsdkSessionId: string,\n): Promise<CreateSessionResult | null> {\n\ttry {\n\t\tconst startUrl =\n\t\t\ttypeof window !== 'undefined' && window.location ? window.location.href : undefined\n\t\tconst userAgent =\n\t\t\ttypeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent : undefined\n\t\tconst res = await fetch(joinUrl(apiUrl, '/api/replay-sessions'), {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tclientId,\n\t\t\t\tsdkSessionId,\n\t\t\t\tstartUrl,\n\t\t\t\tuserAgent,\n\t\t\t\tstartedAt: new Date().toISOString(),\n\t\t\t}),\n\t\t})\n\t\tif (!res.ok) return null\n\t\tconst json = (await res.json()) as {\n\t\t\taccepted?: unknown\n\t\t\tsessionReplayId?: unknown\n\t\t\tdropReason?: unknown\n\t\t}\n\t\tif (typeof json.accepted !== 'boolean') return null\n\t\tconst result: CreateSessionResult = { accepted: json.accepted }\n\t\tif (typeof json.sessionReplayId === 'string') result.sessionReplayId = json.sessionReplayId\n\t\tif (typeof json.dropReason === 'string') result.dropReason = json.dropReason\n\t\treturn result\n\t} catch {\n\t\treturn null\n\t}\n}\n\ninterface ChunkUploadResult {\n\tok: boolean\n\tstopSession: boolean\n}\n\nasync function uploadChunk(\n\tapiUrl: string,\n\tsessionReplayId: string,\n\tclientId: string,\n\tseq: number,\n\tbytes: Uint8Array,\n\teventCount: number,\n\tdurationMs: number,\n\tlogger: PluginContext['logger'],\n\tmaxAttempts: number,\n): Promise<ChunkUploadResult> {\n\tconst url = joinUrl(\n\t\tapiUrl,\n\t\t`/api/replay-sessions/${encodeURIComponent(sessionReplayId)}/chunks/${seq}`,\n\t)\n\tlet attempt = 0\n\twhile (attempt < maxAttempts) {\n\t\ttry {\n\t\t\t// Wrap in a Blob so the body type is unambiguously BodyInit; some\n\t\t\t// TS lib targets reject raw Uint8Array as fetch body. Slice off\n\t\t\t// the buffer to satisfy the BlobPart ArrayBuffer constraint\n\t\t\t// (Uint8Array<SharedArrayBuffer> is the alternative the lib\n\t\t\t// admits, which we never produce here).\n\t\t\tconst buffer = bytes.buffer.slice(\n\t\t\t\tbytes.byteOffset,\n\t\t\t\tbytes.byteOffset + bytes.byteLength,\n\t\t\t) as ArrayBuffer\n\t\t\tconst blob = new Blob([buffer], { type: 'application/octet-stream' })\n\t\t\tconst res = await fetch(url, {\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbody: blob,\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/octet-stream',\n\t\t\t\t\t'X-Usero-Client-Id': clientId,\n\t\t\t\t\t'X-Usero-Event-Count': String(eventCount),\n\t\t\t\t\t'X-Usero-Duration-Ms': String(Math.max(0, Math.round(durationMs))),\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (res.ok) return { ok: true, stopSession: false }\n\t\t\t// 409: server told us to stop (bot-dropped, or session already\n\t\t\t// finalised). Don't retry, don't upload further chunks.\n\t\t\tif (res.status === 409) {\n\t\t\t\tlogger.warn(`chunk ${seq} rejected with 409, stopping session`)\n\t\t\t\treturn { ok: false, stopSession: true }\n\t\t\t}\n\t\t\t// Other 4xx (besides 408/429) won't get better with retry.\n\t\t\tif (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) {\n\t\t\t\tlogger.error(`chunk ${seq} rejected with ${res.status}`)\n\t\t\t\treturn { ok: false, stopSession: false }\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.warn(`chunk ${seq} attempt ${attempt + 1} failed`, err)\n\t\t}\n\t\tattempt += 1\n\t\tconst backoff = Math.min(15_000, 500 * 2 ** attempt) + Math.floor(Math.random() * 250)\n\t\tawait new Promise(resolve => setTimeout(resolve, backoff))\n\t}\n\tlogger.error(`chunk ${seq} dropped after ${maxAttempts} attempts`)\n\treturn { ok: false, stopSession: false }\n}\n\nasync function loadRrwebRecord(): Promise<RrwebRecord | null> {\n\ttry {\n\t\tconst mod: unknown = await import(/* webpackChunkName: \"rrweb\" */ 'rrweb')\n\t\tif (\n\t\t\tmod &&\n\t\t\ttypeof mod === 'object' &&\n\t\t\t'record' in mod &&\n\t\t\ttypeof (mod as { record: unknown }).record === 'function'\n\t\t) {\n\t\t\treturn (mod as { record: RrwebRecord }).record\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction scheduleChunkUpload(store: ReplayStore, ctx: PluginContext): void {\n\tif (!store.sessionReplayId) return\n\tif (store.pendingEvents.length === 0) return\n\tconst events = store.pendingEvents\n\tconst eventCount = events.length\n\tconst firstTs = store.pendingFirstTs ?? 0\n\tconst lastTs = store.pendingLastTs ?? firstTs\n\tconst durationMs = Math.max(0, lastTs - firstTs)\n\tconst seq = store.nextChunkSeq\n\tstore.nextChunkSeq += 1\n\tstore.pendingEvents = []\n\tstore.pendingFirstTs = null\n\tstore.pendingLastTs = null\n\n\tconst sessionReplayId = store.sessionReplayId\n\tconst apiUrl = store.options.apiUrl\n\tconst clientId = store.clientId\n\tconst maxAttempts = store.options.chunkMaxAttempts\n\n\tstore.pendingUploads += 1\n\tstore.uploadQueue = store.uploadQueue.then(async () => {\n\t\ttry {\n\t\t\tif (store.cancelled) return\n\t\t\tconst json = JSON.stringify(events)\n\t\t\tconst bytes = await gzipBytes(json)\n\t\t\tif (bytes.byteLength > HARD_CHUNK_BYTE_CAP) {\n\t\t\t\tctx.logger.error(\n\t\t\t\t\t`chunk ${seq} exceeds 4MB hard cap (${bytes.byteLength} bytes), dropping`,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst result = await uploadChunk(\n\t\t\t\tapiUrl,\n\t\t\t\tsessionReplayId,\n\t\t\t\tclientId,\n\t\t\t\tseq,\n\t\t\t\tbytes,\n\t\t\t\teventCount,\n\t\t\t\tdurationMs,\n\t\t\t\tctx.logger,\n\t\t\t\tmaxAttempts,\n\t\t\t)\n\t\t\tif (result.stopSession) {\n\t\t\t\tstore.stopped = true\n\t\t\t\tstopRrweb(store)\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tctx.logger.error(`chunk ${seq} encode failed`, err)\n\t\t} finally {\n\t\t\tstore.pendingUploads -= 1\n\t\t}\n\t})\n}\n\nfunction flushPendingChunk(store: ReplayStore, ctx: PluginContext): void {\n\tif (store.stopped || store.cancelled) return\n\tif (store.pendingEvents.length === 0) return\n\tscheduleChunkUpload(store, ctx)\n}\n\nfunction stopRrweb(store: ReplayStore): void {\n\tif (store.stopRecording) {\n\t\ttry {\n\t\t\tstore.stopRecording()\n\t\t} catch {\n\t\t\t// Already stopped.\n\t\t}\n\t\tstore.stopRecording = null\n\t}\n\tif (store.chunkFlushTimer) {\n\t\tclearInterval(store.chunkFlushTimer)\n\t\tstore.chunkFlushTimer = null\n\t}\n}\n\nfunction startRecording(store: ReplayStore, ctx: PluginContext): void {\n\tif (store.cancelled || store.stopped || store.stopRecording || store.loadInProgress) return\n\tstore.loadInProgress = true\n\tvoid loadRrwebRecord().then(record => {\n\t\tstore.loadInProgress = false\n\t\tif (store.cancelled || store.stopped || !record) {\n\t\t\tif (!record) ctx.logger.warn('rrweb failed to load, replay disabled')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tconst stop = record({\n\t\t\t\temit: event => {\n\t\t\t\t\tif (store.stopped || store.cancelled) return\n\t\t\t\t\tif (store.recordingStartedAt === null) store.recordingStartedAt = event.timestamp\n\t\t\t\t\tstore.pendingEvents.push(event)\n\t\t\t\t\tif (store.pendingFirstTs === null) store.pendingFirstTs = event.timestamp\n\t\t\t\t\tstore.pendingLastTs = event.timestamp\n\t\t\t\t\tif (store.pendingEvents.length >= store.options.chunkMaxEvents) {\n\t\t\t\t\t\tscheduleChunkUpload(store, ctx)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tmaskAllInputs: store.options.maskAllInputs,\n\t\t\t\tmaskTextSelector: store.options.maskTextSelector || undefined,\n\t\t\t\tinlineStylesheet: store.options.inlineStylesheet,\n\t\t\t\tblockSelector: store.options.blockSelector,\n\t\t\t\tsampling: store.options.sampling,\n\t\t\t})\n\t\t\tstore.stopRecording = stop\n\t\t\tstore.record = record\n\t\t\tscheduleShadowSnapshot(store, ctx)\n\n\t\t\tstore.chunkFlushTimer = setInterval(\n\t\t\t\t() => flushPendingChunk(store, ctx),\n\t\t\t\tstore.options.chunkSeconds * 1000,\n\t\t\t)\n\t\t} catch (err) {\n\t\t\tctx.logger.error('rrweb record() threw', err)\n\t\t}\n\t})\n}\n\nfunction scheduleShadowSnapshot(store: ReplayStore, ctx: PluginContext): void {\n\tif (store.cancelled || store.stopped || !store.record || !store.stopRecording) return\n\tconst fn = store.record.takeFullSnapshot\n\tif (typeof fn !== 'function') return\n\ttry {\n\t\tfn(true)\n\t} catch (err) {\n\t\tctx.logger.warn('takeFullSnapshot threw', err)\n\t}\n}\n\nfunction finalise(store: ReplayStore, ctx: PluginContext, opts: { useBeacon: boolean }): void {\n\tif (!store.sessionReplayId) return\n\tif (store.pendingEvents.length > 0) flushPendingChunk(store, ctx)\n\tconst url = joinUrl(\n\t\tstore.options.apiUrl,\n\t\t`/api/replay-sessions/${encodeURIComponent(store.sessionReplayId)}/finalise`,\n\t)\n\tconst body = JSON.stringify({ clientId: store.clientId, endedAt: new Date().toISOString() })\n\tif (opts.useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {\n\t\ttry {\n\t\t\tconst blob = new Blob([body], { type: 'application/json' })\n\t\t\tnavigator.sendBeacon(url, blob)\n\t\t\treturn\n\t\t} catch (err) {\n\t\t\tctx.logger.warn('finalise sendBeacon threw', err)\n\t\t}\n\t}\n\tvoid fetch(url, {\n\t\tmethod: 'POST',\n\t\tbody,\n\t\theaders: { 'Content-Type': 'application/json' },\n\t\tkeepalive: true,\n\t}).catch(err => ctx.logger.warn('finalise fetch failed', err))\n}\n\nexport interface CurrentSessionHandle {\n\tid: string\n\toffsetMs: number\n}\n\nexport function sessionReplay(options: SessionReplayOptions = {}): UseroPlugin {\n\tconst merged: ResolvedOptions = {\n\t\t...DEFAULTS,\n\t\t...options,\n\t\tsampling: { ...DEFAULTS.sampling, ...(options.sampling ?? {}) },\n\t}\n\n\treturn {\n\t\tname: 'session-replay',\n\t\tonInit(ctx) {\n\t\t\tif (typeof window === 'undefined') return\n\t\t\tif (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {\n\t\t\t\tctx.logger.debug('skipped by sampleRate')\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst apiUrl = merged.apiUrl || ctx.baseUrl\n\t\t\tif (!apiUrl) {\n\t\t\t\tctx.logger.error('session-replay needs an apiUrl (via options or PluginContext)')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst sdkSessionId = mintSdkSessionId()\n\n\t\t\tconst store: ReplayStore = {\n\t\t\t\toptions: { ...merged, apiUrl },\n\t\t\t\tclientId: ctx.clientId,\n\t\t\t\tsdkSessionId,\n\t\t\t\tsessionReplayId: null,\n\t\t\t\trecordingStartedAt: null,\n\t\t\t\tpendingEvents: [],\n\t\t\t\tpendingFirstTs: null,\n\t\t\t\tpendingLastTs: null,\n\t\t\t\tnextChunkSeq: 0,\n\t\t\t\tuploadQueue: Promise.resolve(),\n\t\t\t\tpendingUploads: 0,\n\t\t\t\tchunkFlushTimer: null,\n\t\t\t\tstartTimer: null,\n\t\t\t\tpageHideHandler: null,\n\t\t\t\tshadowUpdateHandler: null,\n\t\t\t\trecord: null,\n\t\t\t\tstopRecording: null,\n\t\t\t\tloadInProgress: false,\n\t\t\t\tcancelled: false,\n\t\t\t\tstopped: false,\n\t\t\t}\n\t\t\tctx.setStore(store)\n\n\t\t\tconst onShadowUpdate = (): void => scheduleShadowSnapshot(store, ctx)\n\t\t\tstore.shadowUpdateHandler = onShadowUpdate\n\t\t\twindow.addEventListener('usero:shadow-update', onShadowUpdate)\n\n\t\t\tconst onPageHide = (): void => {\n\t\t\t\tfinalise(store, ctx, { useBeacon: true })\n\t\t\t\tstore.stopped = true\n\t\t\t\tstopRrweb(store)\n\t\t\t}\n\t\t\tstore.pageHideHandler = onPageHide\n\t\t\twindow.addEventListener('pagehide', onPageHide)\n\n\t\t\tconst begin = async (): Promise<void> => {\n\t\t\t\tif (store.cancelled) return\n\t\t\t\tconst created = await createSession(apiUrl, ctx.clientId, sdkSessionId)\n\t\t\t\tif (!created) {\n\t\t\t\t\tctx.logger.warn('session create failed, replay disabled')\n\t\t\t\t\tstore.stopped = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (!created.accepted) {\n\t\t\t\t\tctx.logger.info(`session-replay declined: ${created.dropReason ?? 'unknown'}`)\n\t\t\t\t\tstore.stopped = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (!created.sessionReplayId) {\n\t\t\t\t\tctx.logger.error('server accepted but returned no sessionReplayId')\n\t\t\t\t\tstore.stopped = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tstore.sessionReplayId = created.sessionReplayId\n\t\t\t\tstore.recordingStartedAt = Date.now()\n\t\t\t\tstartRecording(store, ctx)\n\t\t\t}\n\n\t\t\tif (merged.startAfterMs > 0) {\n\t\t\t\tconst cancelOnExit = (): void => {\n\t\t\t\t\tstore.cancelled = true\n\t\t\t\t\tif (store.startTimer) {\n\t\t\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\t\t\tstore.startTimer = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twindow.addEventListener('pagehide', cancelOnExit, { once: true })\n\t\t\t\twindow.addEventListener('beforeunload', cancelOnExit, { once: true })\n\t\t\t\tstore.startTimer = setTimeout(() => {\n\t\t\t\t\tvoid begin()\n\t\t\t\t}, merged.startAfterMs)\n\t\t\t} else {\n\t\t\t\tvoid begin()\n\t\t\t}\n\t\t},\n\t\tonFeedbackSubmit(ctx) {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store || store.cancelled || store.stopped) return undefined\n\t\t\tif (!store.sessionReplayId) return undefined\n\t\t\tconst offsetMs =\n\t\t\t\tstore.recordingStartedAt !== null\n\t\t\t\t\t? Math.max(0, Date.now() - store.recordingStartedAt)\n\t\t\t\t\t: 0\n\t\t\treturn { sessionReplayId: store.sessionReplayId, replayOffsetMs: offsetMs }\n\t\t},\n\t\tonDestroy(ctx) {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store) return\n\t\t\tstore.cancelled = true\n\t\t\tif (store.startTimer) {\n\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\tstore.startTimer = null\n\t\t\t}\n\t\t\tif (store.pageHideHandler) {\n\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\tstore.pageHideHandler = null\n\t\t\t}\n\t\t\tif (store.shadowUpdateHandler) {\n\t\t\t\twindow.removeEventListener('usero:shadow-update', store.shadowUpdateHandler)\n\t\t\t\tstore.shadowUpdateHandler = null\n\t\t\t}\n\t\t\t// SPA route change / React unmount: send a finalise so the\n\t\t\t// server stamps endedAt. fetch+keepalive is fine here since we\n\t\t\t// aren't necessarily in a pagehide path.\n\t\t\tif (store.sessionReplayId && !store.stopped) {\n\t\t\t\tfinalise(store, ctx, { useBeacon: false })\n\t\t\t}\n\t\t\tstore.stopped = true\n\t\t\tstopRrweb(store)\n\t\t\tstore.pendingEvents.length = 0\n\t\t},\n\t}\n}\n\n// Returns the live session-replay handle for a given plugin context, or\n// null if the session was bot-dropped, sample-skipped, or not yet\n// created. Other plugins (e.g. user-test) can call this to attach the\n// replay FK + offset to their own server-side records.\nexport function getCurrentSession(ctx: PluginContext): CurrentSessionHandle | null {\n\tconst store = ctx.getStore<ReplayStore>()\n\tif (!store || store.cancelled || store.stopped || !store.sessionReplayId) return null\n\tconst offsetMs =\n\t\tstore.recordingStartedAt !== null\n\t\t\t? Math.max(0, Date.now() - store.recordingStartedAt)\n\t\t\t: 0\n\treturn { id: store.sessionReplayId, offsetMs }\n}\n\n// Internal helper exports for testing only. Not part of the public API.\nexport const __test__ = {\n\tuint8ToBase64,\n\tgzipBytes,\n\tmintSdkSessionId,\n\tuploadChunk,\n\tcreateSession,\n\tjoinUrl,\n\tHARD_CHUNK_BYTE_CAP,\n\tSDK_SESSION_STORAGE_KEY,\n}\n"]}
|