@usero/sdk 0.2.1 → 0.3.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.
- package/README.md +86 -0
- package/dist/plugins/session-replay.cjs +178 -0
- package/dist/plugins/session-replay.cjs.map +1 -0
- package/dist/plugins/session-replay.d.cts +75 -0
- package/dist/plugins/session-replay.d.ts +75 -0
- package/dist/plugins/session-replay.js +175 -0
- package/dist/plugins/session-replay.js.map +1 -0
- package/dist/react.cjs +122 -19
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +23 -0
- package/dist/react.d.ts +23 -0
- package/dist/react.js +122 -19
- package/dist/react.js.map +1 -1
- package/dist/rrweb-IQA3KVSA.js +17065 -0
- package/dist/rrweb-IQA3KVSA.js.map +1 -0
- package/dist/rrweb-SDFFFL7O.cjs +17077 -0
- package/dist/rrweb-SDFFFL7O.cjs.map +1 -0
- package/dist/usero.iife.js +43 -36
- package/dist/usero.iife.js.map +1 -1
- package/dist/vanilla.cjs +123 -19
- package/dist/vanilla.cjs.map +1 -1
- package/dist/vanilla.d.cts +25 -1
- package/dist/vanilla.d.ts +25 -1
- package/dist/vanilla.js +123 -20
- package/dist/vanilla.js.map +1 -1
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -80,6 +80,91 @@ The widget auto-detects the OS color scheme via `prefers-color-scheme`. It picks
|
|
|
80
80
|
| `onError` | `(err: Error) => void` | undefined | Fires on init or submission error |
|
|
81
81
|
| `onOpen` / `onClose` | `() => void` | undefined | Fire when the panel opens/closes |
|
|
82
82
|
|
|
83
|
+
## Plugins
|
|
84
|
+
|
|
85
|
+
The widget has a tiny plugin API for opt-in features that would otherwise bloat the base bundle. Plugins live in subpath exports so the base widget stays small for everyone who doesn't use them.
|
|
86
|
+
|
|
87
|
+
### Session replay
|
|
88
|
+
|
|
89
|
+
Attaches a rolling rrweb buffer (last 30 seconds by default) to each feedback submission, gzipped via the native CompressionStream API.
|
|
90
|
+
|
|
91
|
+
`rrweb` ships inside the plugin chunk, so `npm install @usero/sdk` is the only install step. The plugin entry is a separate subpath export, so consumers who never `import` it pay zero rrweb bytes on the base bundle.
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { initUseroFeedbackWidget } from '@usero/sdk'
|
|
95
|
+
import { sessionReplay } from '@usero/sdk/plugins/session-replay'
|
|
96
|
+
|
|
97
|
+
initUseroFeedbackWidget({
|
|
98
|
+
clientId: 'YOUR_CLIENT_ID',
|
|
99
|
+
plugins: [
|
|
100
|
+
sessionReplay({
|
|
101
|
+
bufferSeconds: 30,
|
|
102
|
+
// Wait 3s of engagement before loading rrweb. If the user navigates
|
|
103
|
+
// away first, rrweb is never fetched.
|
|
104
|
+
startAfterMs: 3000,
|
|
105
|
+
// Sample 50% of sessions. Decided once at init via Math.random().
|
|
106
|
+
sampleRate: 0.5,
|
|
107
|
+
}),
|
|
108
|
+
],
|
|
109
|
+
})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The base bundle (`@usero/sdk` and `@usero/sdk/react`) has zero rrweb references. Importing the plugin pulls in a separate chunk, and `rrweb` itself lazy-loads at runtime via dynamic import the first time the engagement gate elapses, so even consumers who DO opt into the plugin don't pay rrweb's bytes upfront.
|
|
113
|
+
|
|
114
|
+
#### Privacy defaults
|
|
115
|
+
|
|
116
|
+
| Option | Default | What it does |
|
|
117
|
+
| ------------------- | ---------------------- | ------------------------------------------------------------- |
|
|
118
|
+
| `maskAllInputs` | `true` | Mask `<input>` and `<textarea>` values in the recording |
|
|
119
|
+
| `maskTextSelector` | `'[data-usero-mask]'` | Mask text content of any node matching this selector |
|
|
120
|
+
| `blockSelector` | `'[data-usero-block]'` | Skip recording subtrees entirely |
|
|
121
|
+
| `inlineStylesheet` | `true` | Inline external stylesheets so replays render offline |
|
|
122
|
+
| `sampling` | `{ mousemove: 50, scroll: 100 }` | Throttle high-frequency events |
|
|
123
|
+
| `bufferSeconds` | `30` | Length of the rolling in-memory buffer in seconds |
|
|
124
|
+
| `startAfterMs` | `0` | Engagement gate before loading rrweb |
|
|
125
|
+
| `sampleRate` | `1` | Probability (0..1) that a given session records at all |
|
|
126
|
+
|
|
127
|
+
Tag any DOM node you want masked at the source: `<div data-usero-mask>...</div>`. Tag entire subtrees you want skipped with `data-usero-block`.
|
|
128
|
+
|
|
129
|
+
### Writing your own plugin
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import type { UseroPlugin } from '@usero/sdk'
|
|
133
|
+
|
|
134
|
+
export function consoleCapture(): UseroPlugin {
|
|
135
|
+
return {
|
|
136
|
+
name: 'console-capture',
|
|
137
|
+
onInit(ctx) {
|
|
138
|
+
const logs: string[] = []
|
|
139
|
+
ctx.setStore(logs)
|
|
140
|
+
const original = console.log
|
|
141
|
+
console.log = (...args) => {
|
|
142
|
+
logs.push(args.map(String).join(' '))
|
|
143
|
+
original(...args)
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
onFeedbackSubmit(ctx) {
|
|
147
|
+
const logs = ctx.getStore<string[]>() ?? []
|
|
148
|
+
return { metadata: { recentLogs: logs.slice(-50) } }
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Plugins return a `Partial<FeedbackSubmission>` from `onFeedbackSubmit`. Top-level keys are shallow-merged into the outgoing payload (later plugins win wholesale). `metadata` is deep-merged one level so multiple plugins can each contribute their own metadata keys without clobbering each other.
|
|
155
|
+
|
|
156
|
+
### `widget.whenReady()`
|
|
157
|
+
|
|
158
|
+
`initUseroFeedbackWidget` returns a handle with a `whenReady(): Promise<void>` method that resolves once every plugin's `onInit` has settled (fulfilled or rejected — a misbehaving plugin never blocks readiness). It's intended for end-to-end tests and dogfooding scripts that want to trigger a synthetic submit only after all plugins are live:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
const widget = initUseroFeedbackWidget({ clientId, plugins: [sessionReplay()] })
|
|
162
|
+
await widget.whenReady()
|
|
163
|
+
widget.open()
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
If no plugins are registered, `whenReady()` resolves immediately.
|
|
167
|
+
|
|
83
168
|
## Why named exports only
|
|
84
169
|
|
|
85
170
|
Default exports break tree-shaking and rename inconsistently across consumer codebases. The package exports nothing as a default, anywhere, on purpose.
|
|
@@ -99,6 +184,7 @@ Outputs:
|
|
|
99
184
|
|
|
100
185
|
- `dist/vanilla.js` (ESM) + `dist/vanilla.cjs` + `dist/vanilla.d.ts`
|
|
101
186
|
- `dist/react.js` (ESM) + `dist/react.cjs` + `dist/react.d.ts`
|
|
187
|
+
- `dist/plugins/session-replay.js` (ESM) + `.cjs` + `.d.ts` plus a sibling `dist/all-*.js` chunk that holds the bundled rrweb runtime. The plugin loads this chunk via dynamic `import()` so it only downloads when the plugin actually needs it.
|
|
102
188
|
- `dist/usero.iife.js` (minified, exposes `window.Usero`)
|
|
103
189
|
|
|
104
190
|
## License
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/plugins/session-replay.ts
|
|
4
|
+
var DEFAULT_OPTIONS = {
|
|
5
|
+
bufferSeconds: 30,
|
|
6
|
+
startAfterMs: 0,
|
|
7
|
+
sampleRate: 1,
|
|
8
|
+
sampling: { mousemove: 50, scroll: 100 },
|
|
9
|
+
maskAllInputs: true,
|
|
10
|
+
maskTextSelector: "[data-usero-mask]",
|
|
11
|
+
inlineStylesheet: true,
|
|
12
|
+
blockSelector: "[data-usero-block]"
|
|
13
|
+
};
|
|
14
|
+
function evictOldEvents(events, bufferSeconds, now) {
|
|
15
|
+
if (events.length === 0) return;
|
|
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
|
+
}
|
|
24
|
+
function uint8ToBase64(bytes) {
|
|
25
|
+
let binary = "";
|
|
26
|
+
const chunkSize = 32768;
|
|
27
|
+
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
28
|
+
const chunk = bytes.subarray(i, i + chunkSize);
|
|
29
|
+
binary += String.fromCharCode.apply(null, Array.from(chunk));
|
|
30
|
+
}
|
|
31
|
+
return typeof btoa === "function" ? btoa(binary) : "";
|
|
32
|
+
}
|
|
33
|
+
async function gzipString(input) {
|
|
34
|
+
if (typeof CompressionStream === "undefined") {
|
|
35
|
+
const bytes = new TextEncoder().encode(input);
|
|
36
|
+
return uint8ToBase64(bytes);
|
|
37
|
+
}
|
|
38
|
+
const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
39
|
+
const compressed = await new Response(stream).arrayBuffer();
|
|
40
|
+
return uint8ToBase64(new Uint8Array(compressed));
|
|
41
|
+
}
|
|
42
|
+
async function loadRrwebRecord() {
|
|
43
|
+
try {
|
|
44
|
+
const mod = await import(
|
|
45
|
+
/* webpackChunkName: "rrweb" */
|
|
46
|
+
'../rrweb-SDFFFL7O.cjs'
|
|
47
|
+
);
|
|
48
|
+
if (mod && typeof mod === "object" && "record" in mod && typeof mod.record === "function") {
|
|
49
|
+
return mod.record;
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function startRecording(store, ctx) {
|
|
57
|
+
if (store.cancelled || store.stopRecording || store.loadInProgress) return;
|
|
58
|
+
store.loadInProgress = true;
|
|
59
|
+
void loadRrwebRecord().then((record) => {
|
|
60
|
+
store.loadInProgress = false;
|
|
61
|
+
if (store.cancelled || !record) {
|
|
62
|
+
if (!record) ctx.logger.warn("rrweb failed to load, replay disabled");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const stop = record({
|
|
67
|
+
emit: (event) => {
|
|
68
|
+
store.events.push(event);
|
|
69
|
+
evictOldEvents(store.events, store.options.bufferSeconds, event.timestamp);
|
|
70
|
+
},
|
|
71
|
+
maskAllInputs: store.options.maskAllInputs,
|
|
72
|
+
maskTextSelector: store.options.maskTextSelector || void 0,
|
|
73
|
+
inlineStylesheet: store.options.inlineStylesheet,
|
|
74
|
+
blockSelector: store.options.blockSelector,
|
|
75
|
+
sampling: store.options.sampling
|
|
76
|
+
});
|
|
77
|
+
store.stopRecording = stop;
|
|
78
|
+
} catch (err) {
|
|
79
|
+
ctx.logger.error("rrweb record() threw", err);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function sessionReplay(options = {}) {
|
|
84
|
+
const merged = {
|
|
85
|
+
...DEFAULT_OPTIONS,
|
|
86
|
+
...options,
|
|
87
|
+
sampling: { ...DEFAULT_OPTIONS.sampling, ...options.sampling ?? {} }
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
name: "session-replay",
|
|
91
|
+
onInit(ctx) {
|
|
92
|
+
if (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {
|
|
93
|
+
ctx.logger.debug("skipped by sampleRate");
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (typeof window === "undefined") return;
|
|
97
|
+
const store = {
|
|
98
|
+
events: [],
|
|
99
|
+
stopRecording: null,
|
|
100
|
+
startTimer: null,
|
|
101
|
+
pageHideHandler: null,
|
|
102
|
+
loadInProgress: false,
|
|
103
|
+
cancelled: false,
|
|
104
|
+
options: merged
|
|
105
|
+
};
|
|
106
|
+
ctx.setStore(store);
|
|
107
|
+
const begin = () => {
|
|
108
|
+
if (store.startTimer) {
|
|
109
|
+
clearTimeout(store.startTimer);
|
|
110
|
+
store.startTimer = null;
|
|
111
|
+
}
|
|
112
|
+
if (store.pageHideHandler) {
|
|
113
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
114
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
115
|
+
store.pageHideHandler = null;
|
|
116
|
+
}
|
|
117
|
+
startRecording(store, ctx);
|
|
118
|
+
};
|
|
119
|
+
if (merged.startAfterMs > 0) {
|
|
120
|
+
const cancelOnExit = () => {
|
|
121
|
+
store.cancelled = true;
|
|
122
|
+
if (store.startTimer) {
|
|
123
|
+
clearTimeout(store.startTimer);
|
|
124
|
+
store.startTimer = null;
|
|
125
|
+
}
|
|
126
|
+
if (store.pageHideHandler) {
|
|
127
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
128
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
129
|
+
store.pageHideHandler = null;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
store.pageHideHandler = cancelOnExit;
|
|
133
|
+
window.addEventListener("pagehide", cancelOnExit, { once: true });
|
|
134
|
+
window.addEventListener("beforeunload", cancelOnExit, { once: true });
|
|
135
|
+
store.startTimer = setTimeout(begin, merged.startAfterMs);
|
|
136
|
+
} else {
|
|
137
|
+
begin();
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
async onFeedbackSubmit(ctx) {
|
|
141
|
+
const store = ctx.getStore();
|
|
142
|
+
if (!store || store.cancelled || store.events.length === 0) return void 0;
|
|
143
|
+
const snapshot = store.events.slice();
|
|
144
|
+
try {
|
|
145
|
+
const json = JSON.stringify(snapshot);
|
|
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
|
+
}
|
|
152
|
+
},
|
|
153
|
+
onDestroy(ctx) {
|
|
154
|
+
const store = ctx.getStore();
|
|
155
|
+
if (!store) return;
|
|
156
|
+
store.cancelled = true;
|
|
157
|
+
if (store.startTimer) clearTimeout(store.startTimer);
|
|
158
|
+
if (store.pageHideHandler) {
|
|
159
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
160
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
161
|
+
}
|
|
162
|
+
if (store.stopRecording) {
|
|
163
|
+
try {
|
|
164
|
+
store.stopRecording();
|
|
165
|
+
} catch (err) {
|
|
166
|
+
ctx.logger.warn("rrweb stop threw", err);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
store.events.length = 0;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
var __test__ = { evictOldEvents, gzipString, uint8ToBase64 };
|
|
174
|
+
|
|
175
|
+
exports.__test__ = __test__;
|
|
176
|
+
exports.sessionReplay = sessionReplay;
|
|
177
|
+
//# sourceMappingURL=session-replay.cjs.map
|
|
178
|
+
//# sourceMappingURL=session-replay.cjs.map
|
|
@@ -0,0 +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,MAAM,aAAA,GAAgB,GAAA;AAGrC,EAAA,IAAI,SAAA,GAAY,CAAA;AAChB,EAAA,KAAA,MAAW,KAAK,MAAA,EAAQ;AACvB,IAAA,IAAI,CAAA,CAAE,aAAa,MAAA,EAAQ;AAC3B,IAAA,SAAA,EAAA;AAAA,EACD;AACA,EAAA,IAAI,SAAA,GAAY,CAAA,EAAG,MAAA,CAAO,M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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"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
type FeedbackRating = 1 | 2 | 3 | 4;
|
|
2
|
+
interface ScreenshotData {
|
|
3
|
+
fileName: string;
|
|
4
|
+
url: string;
|
|
5
|
+
fileSize: number;
|
|
6
|
+
width?: number;
|
|
7
|
+
height?: number;
|
|
8
|
+
mimeType: string;
|
|
9
|
+
}
|
|
10
|
+
interface FeedbackSubmission {
|
|
11
|
+
clientId: string;
|
|
12
|
+
rating?: FeedbackRating;
|
|
13
|
+
comment?: string;
|
|
14
|
+
userEmail?: string;
|
|
15
|
+
pageUrl: string;
|
|
16
|
+
pageTitle: string;
|
|
17
|
+
referrer?: string;
|
|
18
|
+
environment?: string;
|
|
19
|
+
screenshots?: ScreenshotData[];
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
21
|
+
replayEvents?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface PluginLogger {
|
|
25
|
+
debug: (...args: unknown[]) => void;
|
|
26
|
+
info: (...args: unknown[]) => void;
|
|
27
|
+
warn: (...args: unknown[]) => void;
|
|
28
|
+
error: (...args: unknown[]) => void;
|
|
29
|
+
}
|
|
30
|
+
interface PluginContext {
|
|
31
|
+
clientId: string;
|
|
32
|
+
baseUrl: string;
|
|
33
|
+
getStore: <T>() => T | undefined;
|
|
34
|
+
setStore: <T>(value: T) => void;
|
|
35
|
+
logger: PluginLogger;
|
|
36
|
+
}
|
|
37
|
+
interface UseroPlugin {
|
|
38
|
+
name: string;
|
|
39
|
+
onInit?: (ctx: PluginContext) => void | Promise<void>;
|
|
40
|
+
onFeedbackSubmit?: (ctx: PluginContext, submission: FeedbackSubmission) => Promise<Partial<FeedbackSubmission> | undefined> | Partial<FeedbackSubmission> | undefined;
|
|
41
|
+
onDestroy?: (ctx: PluginContext) => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ReplaySampling {
|
|
45
|
+
mousemove?: number;
|
|
46
|
+
scroll?: number;
|
|
47
|
+
media?: number;
|
|
48
|
+
input?: number | 'last';
|
|
49
|
+
}
|
|
50
|
+
interface SessionReplayOptions {
|
|
51
|
+
bufferSeconds?: number;
|
|
52
|
+
startAfterMs?: number;
|
|
53
|
+
sampleRate?: number;
|
|
54
|
+
sampling?: ReplaySampling;
|
|
55
|
+
maskAllInputs?: boolean;
|
|
56
|
+
maskTextSelector?: string;
|
|
57
|
+
inlineStylesheet?: boolean;
|
|
58
|
+
blockSelector?: string;
|
|
59
|
+
}
|
|
60
|
+
interface RrwebEvent {
|
|
61
|
+
type: number;
|
|
62
|
+
data: unknown;
|
|
63
|
+
timestamp: number;
|
|
64
|
+
}
|
|
65
|
+
declare function evictOldEvents(events: RrwebEvent[], bufferSeconds: number, now: number): void;
|
|
66
|
+
declare function uint8ToBase64(bytes: Uint8Array): string;
|
|
67
|
+
declare function gzipString(input: string): Promise<string>;
|
|
68
|
+
declare function sessionReplay(options?: SessionReplayOptions): UseroPlugin;
|
|
69
|
+
declare const __test__: {
|
|
70
|
+
evictOldEvents: typeof evictOldEvents;
|
|
71
|
+
gzipString: typeof gzipString;
|
|
72
|
+
uint8ToBase64: typeof uint8ToBase64;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export { type ReplaySampling, type SessionReplayOptions, __test__, sessionReplay };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
type FeedbackRating = 1 | 2 | 3 | 4;
|
|
2
|
+
interface ScreenshotData {
|
|
3
|
+
fileName: string;
|
|
4
|
+
url: string;
|
|
5
|
+
fileSize: number;
|
|
6
|
+
width?: number;
|
|
7
|
+
height?: number;
|
|
8
|
+
mimeType: string;
|
|
9
|
+
}
|
|
10
|
+
interface FeedbackSubmission {
|
|
11
|
+
clientId: string;
|
|
12
|
+
rating?: FeedbackRating;
|
|
13
|
+
comment?: string;
|
|
14
|
+
userEmail?: string;
|
|
15
|
+
pageUrl: string;
|
|
16
|
+
pageTitle: string;
|
|
17
|
+
referrer?: string;
|
|
18
|
+
environment?: string;
|
|
19
|
+
screenshots?: ScreenshotData[];
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
21
|
+
replayEvents?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface PluginLogger {
|
|
25
|
+
debug: (...args: unknown[]) => void;
|
|
26
|
+
info: (...args: unknown[]) => void;
|
|
27
|
+
warn: (...args: unknown[]) => void;
|
|
28
|
+
error: (...args: unknown[]) => void;
|
|
29
|
+
}
|
|
30
|
+
interface PluginContext {
|
|
31
|
+
clientId: string;
|
|
32
|
+
baseUrl: string;
|
|
33
|
+
getStore: <T>() => T | undefined;
|
|
34
|
+
setStore: <T>(value: T) => void;
|
|
35
|
+
logger: PluginLogger;
|
|
36
|
+
}
|
|
37
|
+
interface UseroPlugin {
|
|
38
|
+
name: string;
|
|
39
|
+
onInit?: (ctx: PluginContext) => void | Promise<void>;
|
|
40
|
+
onFeedbackSubmit?: (ctx: PluginContext, submission: FeedbackSubmission) => Promise<Partial<FeedbackSubmission> | undefined> | Partial<FeedbackSubmission> | undefined;
|
|
41
|
+
onDestroy?: (ctx: PluginContext) => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ReplaySampling {
|
|
45
|
+
mousemove?: number;
|
|
46
|
+
scroll?: number;
|
|
47
|
+
media?: number;
|
|
48
|
+
input?: number | 'last';
|
|
49
|
+
}
|
|
50
|
+
interface SessionReplayOptions {
|
|
51
|
+
bufferSeconds?: number;
|
|
52
|
+
startAfterMs?: number;
|
|
53
|
+
sampleRate?: number;
|
|
54
|
+
sampling?: ReplaySampling;
|
|
55
|
+
maskAllInputs?: boolean;
|
|
56
|
+
maskTextSelector?: string;
|
|
57
|
+
inlineStylesheet?: boolean;
|
|
58
|
+
blockSelector?: string;
|
|
59
|
+
}
|
|
60
|
+
interface RrwebEvent {
|
|
61
|
+
type: number;
|
|
62
|
+
data: unknown;
|
|
63
|
+
timestamp: number;
|
|
64
|
+
}
|
|
65
|
+
declare function evictOldEvents(events: RrwebEvent[], bufferSeconds: number, now: number): void;
|
|
66
|
+
declare function uint8ToBase64(bytes: Uint8Array): string;
|
|
67
|
+
declare function gzipString(input: string): Promise<string>;
|
|
68
|
+
declare function sessionReplay(options?: SessionReplayOptions): UseroPlugin;
|
|
69
|
+
declare const __test__: {
|
|
70
|
+
evictOldEvents: typeof evictOldEvents;
|
|
71
|
+
gzipString: typeof gzipString;
|
|
72
|
+
uint8ToBase64: typeof uint8ToBase64;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export { type ReplaySampling, type SessionReplayOptions, __test__, sessionReplay };
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// src/plugins/session-replay.ts
|
|
2
|
+
var DEFAULT_OPTIONS = {
|
|
3
|
+
bufferSeconds: 30,
|
|
4
|
+
startAfterMs: 0,
|
|
5
|
+
sampleRate: 1,
|
|
6
|
+
sampling: { mousemove: 50, scroll: 100 },
|
|
7
|
+
maskAllInputs: true,
|
|
8
|
+
maskTextSelector: "[data-usero-mask]",
|
|
9
|
+
inlineStylesheet: true,
|
|
10
|
+
blockSelector: "[data-usero-block]"
|
|
11
|
+
};
|
|
12
|
+
function evictOldEvents(events, bufferSeconds, now) {
|
|
13
|
+
if (events.length === 0) return;
|
|
14
|
+
const cutoff = now - bufferSeconds * 1e3;
|
|
15
|
+
let dropCount = 0;
|
|
16
|
+
for (const e of events) {
|
|
17
|
+
if (e.timestamp >= cutoff) break;
|
|
18
|
+
dropCount++;
|
|
19
|
+
}
|
|
20
|
+
if (dropCount > 0) events.splice(0, dropCount);
|
|
21
|
+
}
|
|
22
|
+
function uint8ToBase64(bytes) {
|
|
23
|
+
let binary = "";
|
|
24
|
+
const chunkSize = 32768;
|
|
25
|
+
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
26
|
+
const chunk = bytes.subarray(i, i + chunkSize);
|
|
27
|
+
binary += String.fromCharCode.apply(null, Array.from(chunk));
|
|
28
|
+
}
|
|
29
|
+
return typeof btoa === "function" ? btoa(binary) : "";
|
|
30
|
+
}
|
|
31
|
+
async function gzipString(input) {
|
|
32
|
+
if (typeof CompressionStream === "undefined") {
|
|
33
|
+
const bytes = new TextEncoder().encode(input);
|
|
34
|
+
return uint8ToBase64(bytes);
|
|
35
|
+
}
|
|
36
|
+
const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
37
|
+
const compressed = await new Response(stream).arrayBuffer();
|
|
38
|
+
return uint8ToBase64(new Uint8Array(compressed));
|
|
39
|
+
}
|
|
40
|
+
async function loadRrwebRecord() {
|
|
41
|
+
try {
|
|
42
|
+
const mod = await import(
|
|
43
|
+
/* webpackChunkName: "rrweb" */
|
|
44
|
+
'../rrweb-IQA3KVSA.js'
|
|
45
|
+
);
|
|
46
|
+
if (mod && typeof mod === "object" && "record" in mod && typeof mod.record === "function") {
|
|
47
|
+
return mod.record;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function startRecording(store, ctx) {
|
|
55
|
+
if (store.cancelled || store.stopRecording || store.loadInProgress) return;
|
|
56
|
+
store.loadInProgress = true;
|
|
57
|
+
void loadRrwebRecord().then((record) => {
|
|
58
|
+
store.loadInProgress = false;
|
|
59
|
+
if (store.cancelled || !record) {
|
|
60
|
+
if (!record) ctx.logger.warn("rrweb failed to load, replay disabled");
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const stop = record({
|
|
65
|
+
emit: (event) => {
|
|
66
|
+
store.events.push(event);
|
|
67
|
+
evictOldEvents(store.events, store.options.bufferSeconds, event.timestamp);
|
|
68
|
+
},
|
|
69
|
+
maskAllInputs: store.options.maskAllInputs,
|
|
70
|
+
maskTextSelector: store.options.maskTextSelector || void 0,
|
|
71
|
+
inlineStylesheet: store.options.inlineStylesheet,
|
|
72
|
+
blockSelector: store.options.blockSelector,
|
|
73
|
+
sampling: store.options.sampling
|
|
74
|
+
});
|
|
75
|
+
store.stopRecording = stop;
|
|
76
|
+
} catch (err) {
|
|
77
|
+
ctx.logger.error("rrweb record() threw", err);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function sessionReplay(options = {}) {
|
|
82
|
+
const merged = {
|
|
83
|
+
...DEFAULT_OPTIONS,
|
|
84
|
+
...options,
|
|
85
|
+
sampling: { ...DEFAULT_OPTIONS.sampling, ...options.sampling ?? {} }
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
name: "session-replay",
|
|
89
|
+
onInit(ctx) {
|
|
90
|
+
if (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {
|
|
91
|
+
ctx.logger.debug("skipped by sampleRate");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (typeof window === "undefined") return;
|
|
95
|
+
const store = {
|
|
96
|
+
events: [],
|
|
97
|
+
stopRecording: null,
|
|
98
|
+
startTimer: null,
|
|
99
|
+
pageHideHandler: null,
|
|
100
|
+
loadInProgress: false,
|
|
101
|
+
cancelled: false,
|
|
102
|
+
options: merged
|
|
103
|
+
};
|
|
104
|
+
ctx.setStore(store);
|
|
105
|
+
const begin = () => {
|
|
106
|
+
if (store.startTimer) {
|
|
107
|
+
clearTimeout(store.startTimer);
|
|
108
|
+
store.startTimer = null;
|
|
109
|
+
}
|
|
110
|
+
if (store.pageHideHandler) {
|
|
111
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
112
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
113
|
+
store.pageHideHandler = null;
|
|
114
|
+
}
|
|
115
|
+
startRecording(store, ctx);
|
|
116
|
+
};
|
|
117
|
+
if (merged.startAfterMs > 0) {
|
|
118
|
+
const cancelOnExit = () => {
|
|
119
|
+
store.cancelled = true;
|
|
120
|
+
if (store.startTimer) {
|
|
121
|
+
clearTimeout(store.startTimer);
|
|
122
|
+
store.startTimer = null;
|
|
123
|
+
}
|
|
124
|
+
if (store.pageHideHandler) {
|
|
125
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
126
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
127
|
+
store.pageHideHandler = null;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
store.pageHideHandler = cancelOnExit;
|
|
131
|
+
window.addEventListener("pagehide", cancelOnExit, { once: true });
|
|
132
|
+
window.addEventListener("beforeunload", cancelOnExit, { once: true });
|
|
133
|
+
store.startTimer = setTimeout(begin, merged.startAfterMs);
|
|
134
|
+
} else {
|
|
135
|
+
begin();
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
async onFeedbackSubmit(ctx) {
|
|
139
|
+
const store = ctx.getStore();
|
|
140
|
+
if (!store || store.cancelled || store.events.length === 0) return void 0;
|
|
141
|
+
const snapshot = store.events.slice();
|
|
142
|
+
try {
|
|
143
|
+
const json = JSON.stringify(snapshot);
|
|
144
|
+
const replayEvents = await gzipString(json);
|
|
145
|
+
return { replayEvents };
|
|
146
|
+
} catch (err) {
|
|
147
|
+
ctx.logger.error("failed to encode replay buffer", err);
|
|
148
|
+
return void 0;
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
onDestroy(ctx) {
|
|
152
|
+
const store = ctx.getStore();
|
|
153
|
+
if (!store) return;
|
|
154
|
+
store.cancelled = true;
|
|
155
|
+
if (store.startTimer) clearTimeout(store.startTimer);
|
|
156
|
+
if (store.pageHideHandler) {
|
|
157
|
+
window.removeEventListener("pagehide", store.pageHideHandler);
|
|
158
|
+
window.removeEventListener("beforeunload", store.pageHideHandler);
|
|
159
|
+
}
|
|
160
|
+
if (store.stopRecording) {
|
|
161
|
+
try {
|
|
162
|
+
store.stopRecording();
|
|
163
|
+
} catch (err) {
|
|
164
|
+
ctx.logger.warn("rrweb stop threw", err);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
store.events.length = 0;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
var __test__ = { evictOldEvents, gzipString, uint8ToBase64 };
|
|
172
|
+
|
|
173
|
+
export { __test__, sessionReplay };
|
|
174
|
+
//# sourceMappingURL=session-replay.js.map
|
|
175
|
+
//# sourceMappingURL=session-replay.js.map
|