@mrrocket/sdk 0.28.0 → 0.29.0
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/CHANGELOG.md +9 -0
- package/README.md +4 -2
- package/dist/browser/mrrocket-messenger.js +3 -3
- package/dist/browser/mrrocket-replay.js +3 -3
- package/dist/browser/mrrocket.js +2 -2
- package/dist/client.d.ts +7 -1
- package/dist/client.js +3 -1
- package/dist/client.js.map +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/messenger-ui.js +22 -0
- package/dist/messenger-ui.js.map +1 -1
- package/dist/react-native/index.d.cts +1 -1
- package/dist/react-native/index.d.ts +1 -1
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/replay-core.d.ts +61 -2
- package/dist/replay-core.js +15 -2
- package/dist/replay-core.js.map +1 -1
- package/dist/replay.d.ts +5 -0
- package/dist/replay.js +10 -1
- package/dist/replay.js.map +1 -1
- package/dist/user-hash.d.ts +1 -1
- package/dist/user-hash.js.map +1 -1
- package/package.json +1 -1
package/dist/replay-core.d.ts
CHANGED
|
@@ -23,11 +23,47 @@ export declare const inSample: (sessionId: string, rate: number) => boolean;
|
|
|
23
23
|
export declare const triggerOfEvent: (event: string) => "purchase" | "checkout" | null;
|
|
24
24
|
/** Typed text never reaches MRRocket: every input value becomes stars, at most 12. */
|
|
25
25
|
export declare const maskInput: (text: string) => string;
|
|
26
|
+
/** Text inside this stays readable while all text is masked (a heading, a menu: nothing about the person). */
|
|
27
|
+
export declare const UNMASK_SELECTOR = "[data-ck-unmask]";
|
|
28
|
+
/** Text on the page becomes stars, one per character, spaces kept: the layout keeps its shape, nothing can be read. */
|
|
29
|
+
export declare const maskText: (text: string) => string;
|
|
30
|
+
/**
|
|
31
|
+
* Whether all text is masked now. `setting` is the site's `maskAllText`: true always, false never, and left out (the
|
|
32
|
+
* default) while the visitor is a signed-in user (`identify()` was called), since pages behind a sign-in show names,
|
|
33
|
+
* emails, addresses and the like as plain text.
|
|
34
|
+
*/
|
|
35
|
+
export declare const masksAllText: (setting: boolean | undefined, identified: boolean) => boolean;
|
|
36
|
+
/** The element rrweb hands to `maskTextFn`: only `closest` is needed, so the checks run without a browser. */
|
|
37
|
+
interface Closest {
|
|
38
|
+
closest(selector: string): unknown;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* One piece of page text for the recording. Inside `data-ck-mask` it is always masked; otherwise it is masked while
|
|
42
|
+
* `all()` says so, unless it sits inside `data-ck-unmask`. The nearer marker wins when both are around it.
|
|
43
|
+
*/
|
|
44
|
+
export declare const textMasker: (all: () => boolean) => (text: string, el?: Closest | null) => string;
|
|
26
45
|
/**
|
|
27
46
|
* rrweb's record options: all inputs masked, blocked fields left out, text in `data-ck-mask` masked, no canvas, video,
|
|
28
47
|
* fonts or inlined images, scripts and head clutter dropped. `emit` receives the events.
|
|
48
|
+
*
|
|
49
|
+
* `maskAll`: asked for every piece of text, whether all text is masked now (`masksAllText`). Left out, only
|
|
50
|
+
* `data-ck-mask` is masked, as before.
|
|
29
51
|
*/
|
|
30
|
-
export declare const recordOptions: <E>(emit: (e: E) => void) => {
|
|
52
|
+
export declare const recordOptions: <E>(emit: (e: E) => void, maskAll?: () => boolean) => {
|
|
53
|
+
blockSelector: string;
|
|
54
|
+
recordCanvas: boolean;
|
|
55
|
+
recordCrossOriginIframes: boolean;
|
|
56
|
+
collectFonts: boolean;
|
|
57
|
+
inlineImages: boolean;
|
|
58
|
+
slimDOMOptions: "all";
|
|
59
|
+
sampling: {
|
|
60
|
+
mousemove: number;
|
|
61
|
+
scroll: number;
|
|
62
|
+
media: number;
|
|
63
|
+
input: "last";
|
|
64
|
+
};
|
|
65
|
+
maskTextSelector: string;
|
|
66
|
+
maskTextFn: (text: string, el?: Closest | null) => string;
|
|
31
67
|
emit: (e: E) => void;
|
|
32
68
|
maskAllInputs: boolean;
|
|
33
69
|
maskInputOptions: {
|
|
@@ -49,7 +85,7 @@ export declare const recordOptions: <E>(emit: (e: E) => void) => {
|
|
|
49
85
|
password: boolean;
|
|
50
86
|
};
|
|
51
87
|
maskInputFn: (text: string) => string;
|
|
52
|
-
|
|
88
|
+
} | {
|
|
53
89
|
blockSelector: string;
|
|
54
90
|
recordCanvas: boolean;
|
|
55
91
|
recordCrossOriginIframes: boolean;
|
|
@@ -62,6 +98,28 @@ export declare const recordOptions: <E>(emit: (e: E) => void) => {
|
|
|
62
98
|
media: number;
|
|
63
99
|
input: "last";
|
|
64
100
|
};
|
|
101
|
+
maskTextSelector: string;
|
|
102
|
+
emit: (e: E) => void;
|
|
103
|
+
maskAllInputs: boolean;
|
|
104
|
+
maskInputOptions: {
|
|
105
|
+
color: boolean;
|
|
106
|
+
date: boolean;
|
|
107
|
+
"datetime-local": boolean;
|
|
108
|
+
email: boolean;
|
|
109
|
+
month: boolean;
|
|
110
|
+
number: boolean;
|
|
111
|
+
range: boolean;
|
|
112
|
+
search: boolean;
|
|
113
|
+
tel: boolean;
|
|
114
|
+
text: boolean;
|
|
115
|
+
time: boolean;
|
|
116
|
+
url: boolean;
|
|
117
|
+
week: boolean;
|
|
118
|
+
textarea: boolean;
|
|
119
|
+
select: boolean;
|
|
120
|
+
password: boolean;
|
|
121
|
+
};
|
|
122
|
+
maskInputFn: (text: string) => string;
|
|
65
123
|
};
|
|
66
124
|
/** The few rrweb fields this module reads. Type 4 is the Meta event that starts each full snapshot. */
|
|
67
125
|
export interface ReplayEvent {
|
|
@@ -91,3 +149,4 @@ export declare class RingBuffer<E extends ReplayEvent = ReplayEvent> {
|
|
|
91
149
|
export declare const chunkDue: (bytes: number, sinceFlushMs: number) => boolean;
|
|
92
150
|
/** Base64 of bytes, in slices so a large chunk does not overflow the call stack. */
|
|
93
151
|
export declare const toBase64: (bytes: Uint8Array) => string;
|
|
152
|
+
export {};
|
package/dist/replay-core.js
CHANGED
|
@@ -27,7 +27,15 @@ var triggerOfEvent = (event) => {
|
|
|
27
27
|
return e.startsWith("purchase") ? "purchase" : e.startsWith("checkout") ? "checkout" : null;
|
|
28
28
|
};
|
|
29
29
|
var maskInput = (text) => "*".repeat(Math.min(12, text.length));
|
|
30
|
-
var
|
|
30
|
+
var UNMASK_SELECTOR = "[data-ck-unmask]";
|
|
31
|
+
var maskText = (text) => text.replace(/\S/g, "*");
|
|
32
|
+
var masksAllText = (setting, identified) => setting ?? identified;
|
|
33
|
+
var textMasker = (all) => (text, el) => {
|
|
34
|
+
const marked = el?.closest(`${MASK_TEXT_SELECTOR},${UNMASK_SELECTOR}`);
|
|
35
|
+
if (marked?.matches) return marked.matches(MASK_TEXT_SELECTOR) ? maskText(text) : text;
|
|
36
|
+
return all() ? maskText(text) : text;
|
|
37
|
+
};
|
|
38
|
+
var recordOptions = (emit, maskAll) => ({
|
|
31
39
|
emit,
|
|
32
40
|
maskAllInputs: true,
|
|
33
41
|
maskInputOptions: {
|
|
@@ -49,7 +57,8 @@ var recordOptions = (emit) => ({
|
|
|
49
57
|
password: true
|
|
50
58
|
},
|
|
51
59
|
maskInputFn: maskInput,
|
|
52
|
-
|
|
60
|
+
// With `maskAll` every text goes through the masker, which decides piece by piece.
|
|
61
|
+
...maskAll ? { maskTextSelector: "*", maskTextFn: textMasker(maskAll) } : { maskTextSelector: MASK_TEXT_SELECTOR },
|
|
53
62
|
blockSelector: BLOCK_SELECTOR,
|
|
54
63
|
recordCanvas: false,
|
|
55
64
|
recordCrossOriginIframes: false,
|
|
@@ -112,10 +121,14 @@ export {
|
|
|
112
121
|
MAX_RECORDING_MS,
|
|
113
122
|
MAX_REQUEST_BYTES,
|
|
114
123
|
RingBuffer,
|
|
124
|
+
UNMASK_SELECTOR,
|
|
115
125
|
chunkDue,
|
|
116
126
|
inSample,
|
|
117
127
|
maskInput,
|
|
128
|
+
maskText,
|
|
129
|
+
masksAllText,
|
|
118
130
|
recordOptions,
|
|
131
|
+
textMasker,
|
|
119
132
|
toBase64,
|
|
120
133
|
triggerOfEvent
|
|
121
134
|
};
|
package/dist/replay-core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/replay-core.ts"],"sourcesContent":["/**\n * The rules of session recording, without the browser: which visits upload from the start, what a trigger is, how the\n * last minute is kept in memory, how events become upload chunks, and the privacy defaults handed to rrweb. The\n * recorder itself (./replay.ts) is loaded only when a visit records; this file is shared with MRRocket's own checks.\n */\nimport { BLOCK_ATTR_SELECTOR, MASK_SELECTOR } from \"./capture\";\nimport { hashUnit } from \"./core\";\n\nexport const DEFAULT_SAMPLE_RATE = 0.1;\n/** A recording stops after 30 minutes. */\nexport const MAX_RECORDING_MS = 30 * 60 * 1000;\n/** A visit outside the sample keeps about this much in memory, from the last full snapshot on. */\nexport const BUFFER_MS = 60 * 1000;\n/** How often a buffering visit takes a new full snapshot, so the buffer can drop what is older. */\nexport const CHECKOUT_MS = 30 * 1000;\n/** Upload a chunk every 5 seconds or once it holds about 64 KB of events, whichever comes first. */\nexport const FLUSH_MS = 5 * 1000;\nexport const FLUSH_BYTES = 64 * 1024;\n/** The buffer never holds more than this; the oldest snapshot goes first. */\nexport const BUFFER_MAX_BYTES = 4 * 1024 * 1024;\n/** The server takes at most 1 MB per request; a chunk that would not fit ends the recording. */\nexport const MAX_REQUEST_BYTES = 1024 * 1024;\n\n/** Why a recording was uploaded. */\nexport type ReplayTrigger = \"sample\" | \"error\" | \"rage\" | \"purchase\" | \"checkout\";\n\n/** Never recorded: password, hidden and card fields, payment iframes, and whatever the site marks `data-ck-block`. */\nexport const BLOCK_SELECTOR = [\n BLOCK_ATTR_SELECTOR,\n 'input[type=\"password\"]',\n 'input[type=\"hidden\"]',\n '[autocomplete^=\"cc-\"]',\n 'input[name*=\"card\" i]',\n 'input[name*=\"cvc\" i]',\n 'input[name*=\"cvv\" i]',\n 'iframe[src*=\"js.stripe.com\"]',\n 'iframe[src*=\"paypal.com\"]',\n].join(\",\");\nexport const MASK_TEXT_SELECTOR = MASK_SELECTOR;\n\n/** Whether this session uploads from its start. Stable per session id, so every page of a session agrees. */\nexport const inSample = (sessionId: string, rate: number) => hashUnit(`replay:${sessionId}`) < Math.min(1, Math.max(0, rate));\n\n/** A tracked event that uploads the buffered minute: names starting with `purchase` or `checkout`. */\nexport const triggerOfEvent = (event: string): \"purchase\" | \"checkout\" | null => {\n const e = event.toLowerCase().replace(/^\\$/, \"\");\n return e.startsWith(\"purchase\") ? \"purchase\" : e.startsWith(\"checkout\") ? \"checkout\" : null;\n};\n\n/** Typed text never reaches MRRocket: every input value becomes stars, at most 12. */\nexport const maskInput = (text: string) => \"*\".repeat(Math.min(12, text.length));\n\n/**\n * rrweb's record options: all inputs masked, blocked fields left out, text in `data-ck-mask` masked, no canvas, video,\n * fonts or inlined images, scripts and head clutter dropped. `emit` receives the events.\n */\nexport const recordOptions = <E>(emit: (e: E) => void) => ({\n emit,\n maskAllInputs: true,\n maskInputOptions: {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true,\n },\n maskInputFn: maskInput,\n maskTextSelector: MASK_TEXT_SELECTOR,\n blockSelector: BLOCK_SELECTOR,\n recordCanvas: false,\n recordCrossOriginIframes: false,\n collectFonts: false,\n inlineImages: false,\n slimDOMOptions: \"all\" as const,\n sampling: { mousemove: 50, scroll: 150, media: 800, input: \"last\" as const },\n});\n\n/** The few rrweb fields this module reads. Type 4 is the Meta event that starts each full snapshot. */\nexport interface ReplayEvent {\n type: number;\n timestamp: number;\n}\n\n/**\n * The last minute of a visit that is not uploaded (yet). Events are kept in segments that each start at a full\n * snapshot; a segment is dropped once the next one already covers the whole window, so whatever is drained starts\n * with a full snapshot and holds at least the last `windowMs`.\n */\nexport class RingBuffer<E extends ReplayEvent = ReplayEvent> {\n private segments: { events: E[]; bytes: number }[] = [];\n constructor(\n private readonly windowMs = BUFFER_MS,\n private readonly maxBytes = BUFFER_MAX_BYTES,\n ) {}\n\n push(e: E, bytes: number) {\n if (e.type === 4 || !this.segments.length) this.segments.push({ events: [], bytes: 0 });\n const seg = this.segments[this.segments.length - 1];\n seg.events.push(e);\n seg.bytes += bytes;\n const from = e.timestamp - this.windowMs;\n while (this.segments.length > 1 && (this.segments[1].events[0].timestamp <= from || this.bytes > this.maxBytes)) this.segments.shift();\n }\n\n get bytes() {\n return this.segments.reduce((s, x) => s + x.bytes, 0);\n }\n\n get size() {\n return this.segments.reduce((s, x) => s + x.events.length, 0);\n }\n\n /** The oldest event kept, or null when empty. */\n get first() {\n return this.segments[0]?.events[0]?.timestamp ?? null;\n }\n\n /** Everything kept, oldest first, and empties the buffer. */\n drain(): E[] {\n const out = this.segments.flatMap((s) => s.events);\n this.segments = [];\n return out;\n }\n\n clear() {\n this.segments = [];\n }\n}\n\n/** Whether a chunk is due: enough bytes, or enough time since the last upload. */\nexport const chunkDue = (bytes: number, sinceFlushMs: number) => bytes >= FLUSH_BYTES || (bytes > 0 && sinceFlushMs >= FLUSH_MS);\n\n/** Base64 of bytes, in slices so a large chunk does not overflow the call stack. */\nexport const toBase64 = (bytes: Uint8Array) => {\n let s = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return btoa(s);\n};\n"],"mappings":";AAKA,SAAS,qBAAqB,qBAAqB;AACnD,SAAS,gBAAgB;AAElB,IAAM,sBAAsB;AAE5B,IAAM,mBAAmB,KAAK,KAAK;AAEnC,IAAM,YAAY,KAAK;AAEvB,IAAM,cAAc,KAAK;AAEzB,IAAM,WAAW,IAAI;AACrB,IAAM,cAAc,KAAK;AAEzB,IAAM,mBAAmB,IAAI,OAAO;AAEpC,IAAM,oBAAoB,OAAO;AAMjC,IAAM,iBAAiB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,EAAE,K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,SAAS,KAAK,EAAE,QAAQ,CAAC,GAAG,OAAO,EAAE,CAAC;AACtF,UAAM,MAAM,KAAK,SAAS,KAAK,SAAS,SAAS,CAAC;AAClD,QAAI,OAAO,KAAK,CAAC;AACjB,QAAI,SAAS;AACb,UAAM,OAAO,EAAE,YAAY,KAAK;AAChC,WAAO,KAAK,SAAS,SAAS,MAAM,KAAK,SAAS,CAAC,EAAE,OAAO,CAAC,EAAE,aAAa,QAAQ,KAAK,QAAQ,KAAK,UAAW,MAAK,SAAS,MAAM;AAAA,EACzI;AAAA,EAEA,IAAI,QAAQ;AACR,WAAO,KAAK,SAAS,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,OAAO,CAAC;AAAA,EACxD;AAAA,EAEA,IAAI,OAAO;AACP,WAAO,KAAK,SAAS,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,OAAO,QAAQ,CAAC;AAAA,EAChE;AAAA;AAAA,EAGA,IAAI,QAAQ;AACR,WAAO,KAAK,SAAS,CAAC,GAAG,OAAO,CAAC,GAAG,aAAa;AAAA,EACrD;AAAA;AAAA,EAGA,QAAa;AACT,UAAM,MAAM,KAAK,SAAS,QAAQ,CAAC,MAAM,EAAE,MAAM;AACjD,SAAK,WAAW,CAAC;AACjB,WAAO;AAAA,EACX;AAAA,EAEA,QAAQ;AACJ,SAAK,WAAW,CAAC;AAAA,EACrB;AACJ;AAGO,IAAM,WAAW,CAAC,OAAe,iBAAyB,SAAS,eAAgB,QAAQ,KAAK,gBAAgB;AAGhH,IAAM,WAAW,CAAC,UAAsB;AAC3C,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAQ,MAAK,OAAO,aAAa,GAAG,MAAM,SAAS,GAAG,IAAI,KAAM,CAAC;AACxG,SAAO,KAAK,CAAC;AACjB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/replay-core.ts"],"sourcesContent":["/**\n * The rules of session recording, without the browser: which visits upload from the start, what a trigger is, how the\n * last minute is kept in memory, how events become upload chunks, and the privacy defaults handed to rrweb. The\n * recorder itself (./replay.ts) is loaded only when a visit records; this file is shared with MRRocket's own checks.\n */\nimport { BLOCK_ATTR_SELECTOR, MASK_SELECTOR } from \"./capture\";\nimport { hashUnit } from \"./core\";\n\nexport const DEFAULT_SAMPLE_RATE = 0.1;\n/** A recording stops after 30 minutes. */\nexport const MAX_RECORDING_MS = 30 * 60 * 1000;\n/** A visit outside the sample keeps about this much in memory, from the last full snapshot on. */\nexport const BUFFER_MS = 60 * 1000;\n/** How often a buffering visit takes a new full snapshot, so the buffer can drop what is older. */\nexport const CHECKOUT_MS = 30 * 1000;\n/** Upload a chunk every 5 seconds or once it holds about 64 KB of events, whichever comes first. */\nexport const FLUSH_MS = 5 * 1000;\nexport const FLUSH_BYTES = 64 * 1024;\n/** The buffer never holds more than this; the oldest snapshot goes first. */\nexport const BUFFER_MAX_BYTES = 4 * 1024 * 1024;\n/** The server takes at most 1 MB per request; a chunk that would not fit ends the recording. */\nexport const MAX_REQUEST_BYTES = 1024 * 1024;\n\n/** Why a recording was uploaded. */\nexport type ReplayTrigger = \"sample\" | \"error\" | \"rage\" | \"purchase\" | \"checkout\";\n\n/** Never recorded: password, hidden and card fields, payment iframes, and whatever the site marks `data-ck-block`. */\nexport const BLOCK_SELECTOR = [\n BLOCK_ATTR_SELECTOR,\n 'input[type=\"password\"]',\n 'input[type=\"hidden\"]',\n '[autocomplete^=\"cc-\"]',\n 'input[name*=\"card\" i]',\n 'input[name*=\"cvc\" i]',\n 'input[name*=\"cvv\" i]',\n 'iframe[src*=\"js.stripe.com\"]',\n 'iframe[src*=\"paypal.com\"]',\n].join(\",\");\nexport const MASK_TEXT_SELECTOR = MASK_SELECTOR;\n\n/** Whether this session uploads from its start. Stable per session id, so every page of a session agrees. */\nexport const inSample = (sessionId: string, rate: number) => hashUnit(`replay:${sessionId}`) < Math.min(1, Math.max(0, rate));\n\n/** A tracked event that uploads the buffered minute: names starting with `purchase` or `checkout`. */\nexport const triggerOfEvent = (event: string): \"purchase\" | \"checkout\" | null => {\n const e = event.toLowerCase().replace(/^\\$/, \"\");\n return e.startsWith(\"purchase\") ? \"purchase\" : e.startsWith(\"checkout\") ? \"checkout\" : null;\n};\n\n/** Typed text never reaches MRRocket: every input value becomes stars, at most 12. */\nexport const maskInput = (text: string) => \"*\".repeat(Math.min(12, text.length));\n\n/** Text inside this stays readable while all text is masked (a heading, a menu: nothing about the person). */\nexport const UNMASK_SELECTOR = \"[data-ck-unmask]\";\n\n/** Text on the page becomes stars, one per character, spaces kept: the layout keeps its shape, nothing can be read. */\nexport const maskText = (text: string) => text.replace(/\\S/g, \"*\");\n\n/**\n * Whether all text is masked now. `setting` is the site's `maskAllText`: true always, false never, and left out (the\n * default) while the visitor is a signed-in user (`identify()` was called), since pages behind a sign-in show names,\n * emails, addresses and the like as plain text.\n */\nexport const masksAllText = (setting: boolean | undefined, identified: boolean) => setting ?? identified;\n\n/** The element rrweb hands to `maskTextFn`: only `closest` is needed, so the checks run without a browser. */\ninterface Closest {\n closest(selector: string): unknown;\n}\n\n/**\n * One piece of page text for the recording. Inside `data-ck-mask` it is always masked; otherwise it is masked while\n * `all()` says so, unless it sits inside `data-ck-unmask`. The nearer marker wins when both are around it.\n */\nexport const textMasker =\n (all: () => boolean) =>\n (text: string, el?: Closest | null): string => {\n const marked = el?.closest(`${MASK_TEXT_SELECTOR},${UNMASK_SELECTOR}`) as { matches?(selector: string): boolean } | null | undefined;\n if (marked?.matches) return marked.matches(MASK_TEXT_SELECTOR) ? maskText(text) : text;\n return all() ? maskText(text) : text;\n };\n\n/**\n * rrweb's record options: all inputs masked, blocked fields left out, text in `data-ck-mask` masked, no canvas, video,\n * fonts or inlined images, scripts and head clutter dropped. `emit` receives the events.\n *\n * `maskAll`: asked for every piece of text, whether all text is masked now (`masksAllText`). Left out, only\n * `data-ck-mask` is masked, as before.\n */\nexport const recordOptions = <E>(emit: (e: E) => void, maskAll?: () => boolean) => ({\n emit,\n maskAllInputs: true,\n maskInputOptions: {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true,\n },\n maskInputFn: maskInput,\n // With `maskAll` every text goes through the masker, which decides piece by piece.\n ...(maskAll ? { maskTextSelector: \"*\", maskTextFn: textMasker(maskAll) } : { maskTextSelector: MASK_TEXT_SELECTOR }),\n blockSelector: BLOCK_SELECTOR,\n recordCanvas: false,\n recordCrossOriginIframes: false,\n collectFonts: false,\n inlineImages: false,\n slimDOMOptions: \"all\" as const,\n sampling: { mousemove: 50, scroll: 150, media: 800, input: \"last\" as const },\n});\n\n/** The few rrweb fields this module reads. Type 4 is the Meta event that starts each full snapshot. */\nexport interface ReplayEvent {\n type: number;\n timestamp: number;\n}\n\n/**\n * The last minute of a visit that is not uploaded (yet). Events are kept in segments that each start at a full\n * snapshot; a segment is dropped once the next one already covers the whole window, so whatever is drained starts\n * with a full snapshot and holds at least the last `windowMs`.\n */\nexport class RingBuffer<E extends ReplayEvent = ReplayEvent> {\n private segments: { events: E[]; bytes: number }[] = [];\n constructor(\n private readonly windowMs = BUFFER_MS,\n private readonly maxBytes = BUFFER_MAX_BYTES,\n ) {}\n\n push(e: E, bytes: number) {\n if (e.type === 4 || !this.segments.length) this.segments.push({ events: [], bytes: 0 });\n const seg = this.segments[this.segments.length - 1];\n seg.events.push(e);\n seg.bytes += bytes;\n const from = e.timestamp - this.windowMs;\n while (this.segments.length > 1 && (this.segments[1].events[0].timestamp <= from || this.bytes > this.maxBytes)) this.segments.shift();\n }\n\n get bytes() {\n return this.segments.reduce((s, x) => s + x.bytes, 0);\n }\n\n get size() {\n return this.segments.reduce((s, x) => s + x.events.length, 0);\n }\n\n /** The oldest event kept, or null when empty. */\n get first() {\n return this.segments[0]?.events[0]?.timestamp ?? null;\n }\n\n /** Everything kept, oldest first, and empties the buffer. */\n drain(): E[] {\n const out = this.segments.flatMap((s) => s.events);\n this.segments = [];\n return out;\n }\n\n clear() {\n this.segments = [];\n }\n}\n\n/** Whether a chunk is due: enough bytes, or enough time since the last upload. */\nexport const chunkDue = (bytes: number, sinceFlushMs: number) => bytes >= FLUSH_BYTES || (bytes > 0 && sinceFlushMs >= FLUSH_MS);\n\n/** Base64 of bytes, in slices so a large chunk does not overflow the call stack. */\nexport const toBase64 = (bytes: Uint8Array) => {\n let s = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return btoa(s);\n};\n"],"mappings":";AAKA,SAAS,qBAAqB,qBAAqB;AACnD,SAAS,gBAAgB;AAElB,IAAM,sBAAsB;AAE5B,IAAM,mBAAmB,KAAK,KAAK;AAEnC,IAAM,YAAY,KAAK;AAEvB,IAAM,cAAc,KAAK;AAEzB,IAAM,WAAW,IAAI;AACrB,IAAM,cAAc,KAAK;AAEzB,IAAM,mBAAmB,IAAI,OAAO;AAEpC,IAAM,oBAAoB,OAAO;AAMjC,IAAM,iBAAiB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,EAAE,KAAK,GAAG;AACH,IAAM,qBAAqB;AAG3B,IAAM,WAAW,CAAC,WAAmB,SAAiB,SAAS,UAAU,SAAS,EAAE,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,IAAI,CAAC;AAGrH,IAAM,iBAAiB,CAAC,UAAkD;AAC7E,QAAM,IAAI,MAAM,YAAY,EAAE,QAAQ,OAAO,EAAE;AAC/C,SAAO,EAAE,WAAW,UAAU,IAAI,aAAa,EAAE,WAAW,UAAU,IAAI,aAAa;AAC3F;AAGO,IAAM,YAAY,CAAC,SAAiB,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,CAAC;AAGxE,IAAM,kBAAkB;AAGxB,IAAM,WAAW,CAAC,SAAiB,KAAK,QAA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chunk while the recording is theirs. */
|
|
22
22
|
userHash?: string;
|
|
23
23
|
sampleRate: number;
|
|
24
|
+
/**
|
|
25
|
+
* Mask every text on the page, not only `data-ck-mask`. Left out (the default): while the visitor is a signed-in
|
|
26
|
+
* user (`identify()` was called). `true`: always. `false`: never. `data-ck-unmask` keeps an element readable.
|
|
27
|
+
*/
|
|
28
|
+
maskAllText?: boolean;
|
|
24
29
|
warn: (message: string) => void;
|
|
25
30
|
}
|
|
26
31
|
export interface ReplayHandle {
|
package/dist/replay.js
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
RingBuffer,
|
|
12
12
|
chunkDue,
|
|
13
13
|
inSample,
|
|
14
|
+
masksAllText,
|
|
14
15
|
recordOptions,
|
|
15
16
|
toBase64,
|
|
16
17
|
triggerOfEvent
|
|
@@ -162,7 +163,8 @@ var startReplay = async (o) => {
|
|
|
162
163
|
};
|
|
163
164
|
const onHide = () => mode === "upload" && flush(true);
|
|
164
165
|
const onVisibility = () => document.visibilityState === "hidden" && mode === "upload" && flush(false);
|
|
165
|
-
const
|
|
166
|
+
const maskAll = o.maskAllText === false ? void 0 : () => masksAllText(o.maskAllText, identified);
|
|
167
|
+
const stopRecording = record(recordOptions(emit, maskAll));
|
|
166
168
|
if (!stopRecording) return null;
|
|
167
169
|
console.error = patched;
|
|
168
170
|
window.addEventListener("error", onError);
|
|
@@ -195,7 +197,14 @@ var startReplay = async (o) => {
|
|
|
195
197
|
if (hash) userHash = hash;
|
|
196
198
|
else if (id !== distinctId) userHash = void 0;
|
|
197
199
|
distinctId = id;
|
|
200
|
+
const masksNow = !identified && o.maskAllText === void 0;
|
|
198
201
|
identified = true;
|
|
202
|
+
if (masksNow && !stopped) {
|
|
203
|
+
try {
|
|
204
|
+
record.takeFullSnapshot(true);
|
|
205
|
+
} catch {
|
|
206
|
+
}
|
|
207
|
+
}
|
|
199
208
|
},
|
|
200
209
|
stop: (discard = false) => end(discard)
|
|
201
210
|
};
|
package/dist/replay.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/replay.ts"],"sourcesContent":["\"use client\";\n\n/**\n * The session recorder. The provider imports this file (and rrweb's recorder with it) only when a visit records: the\n * product has recordings on and the visitor gave replay consent. Pages without recording never load it.\n *\n * A visit in the product's sample uploads from its start. Any other visit keeps the last minute in memory and uploads\n * it only when something happens worth watching: a JS error, a rage click, or a `purchase…` / `checkout…` event; from\n * then on it uploads like a sampled one. Chunks go every 5 seconds or 64 KB, gzip'd where the browser can, to\n * `POST {host}/api/sdk/replay`; the last one leaves with sendBeacon when the page hides. A recording ends after 30\n * minutes. Withdrawing consent stops it and drops what was not sent.\n */\nimport type { ClickInfo } from \"./capture\";\nimport { warnUnsigned } from \"./identity\";\nimport {\n BUFFER_MS,\n CHECKOUT_MS,\n FLUSH_BYTES,\n MAX_RECORDING_MS,\n MAX_REQUEST_BYTES,\n type ReplayEvent,\n type ReplayTrigger,\n RingBuffer,\n chunkDue,\n inSample,\n recordOptions,\n toBase64,\n triggerOfEvent,\n} from \"./replay-core\";\n\nexport interface ReplayOptions {\n host: string;\n apiKey: string;\n /** The SDK's session id; every chunk carries it, so the recording joins the session's events. */\n sessionId: string;\n /** The identify() id or the cookie id; missing cookieless until identify(). */\n distinctId?: string;\n /** Whether `distinctId` comes from identify() (a person) rather than the visitor cookie. */\n identified?: boolean;\n /** The identity hash of `distinctId` (0.16.0), sent with every chunk while the recording is theirs. */\n userHash?: string;\n sampleRate: number;\n warn: (message: string) => void;\n}\n\nexport interface ReplayHandle {\n /** A tracked event; `purchase…` and `checkout…` upload the buffered minute. */\n event(name: string): void;\n click(c: ClickInfo, rage: boolean): void;\n /** A client-side navigation. */\n page(path: string): void;\n /** The person the site identified, with their identity hash when it has one (0.16.0). */\n identify(id: string, userHash?: string): void;\n /** Stops recording. `discard` (consent withdrawn) drops everything not sent yet. */\n stop(discard?: boolean): void;\n}\n\n/** One line of the masked event list the server keeps next to the recording (pages, clicks, rage clicks, errors). */\ninterface Mark {\n t: number;\n kind: \"pageview\" | \"click\" | \"rage\" | \"error\";\n path: string;\n label?: string;\n x?: number;\n y?: number;\n vw?: number;\n dead?: boolean;\n}\n\ninterface Held extends ReplayEvent {\n json: string;\n}\n\nconst clip = (s: unknown, n: number) => String(s ?? \"\").slice(0, n);\nconst pathNow = () => window.location.pathname.slice(0, 300) || \"/\";\n\nconst gzip = async (text: string) => {\n const stream = new Blob([text]).stream().pipeThrough(new CompressionStream(\"gzip\"));\n return new Uint8Array(await new Response(stream).arrayBuffer());\n};\n\nexport const startReplay = async (o: ReplayOptions): Promise<ReplayHandle | null> => {\n if (typeof window === \"undefined\") return null;\n const { record } = await import(\"@rrweb/record\");\n\n const url = `${o.host}/api/sdk/replay`;\n let mode: \"upload\" | \"buffer\" = inSample(o.sessionId, o.sampleRate) ? \"upload\" : \"buffer\";\n let trigger: ReplayTrigger | null = mode === \"upload\" ? \"sample\" : null;\n let distinctId = o.distinctId;\n let identified = o.identified === true;\n let userHash = o.userHash;\n let start: number | null = null;\n let seq = 0;\n let stopped = false;\n const begun = Date.now();\n const ring = new RingBuffer<Held>();\n let pending: Held[] = [];\n let pendingBytes = 0;\n let lastFlush = Date.now();\n let marks: Mark[] = [{ t: Date.now(), kind: \"pageview\", path: pathNow() }];\n let queue: Promise<void> = Promise.resolve();\n\n const end = (discard: boolean) => {\n if (stopped) return;\n if (!discard && mode === \"upload\") flush(false);\n stopped = true;\n stopRecording?.();\n window.clearInterval(tick);\n window.clearInterval(checkout);\n window.removeEventListener(\"error\", onError);\n window.removeEventListener(\"unhandledrejection\", onRejection);\n window.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n if (console.error === patched) console.error = original;\n pending = [];\n ring.clear();\n marks = [];\n };\n\n const send = async (payload: Record<string, unknown>, events: string, sync: boolean) => {\n let body: string;\n if (!sync && typeof CompressionStream !== \"undefined\") body = JSON.stringify({ ...payload, enc: \"gzip\", data: toBase64(await gzip(events)) });\n else body = JSON.stringify({ ...payload, enc: \"json\", data: events });\n if (body.length > MAX_REQUEST_BYTES) {\n o.warn(\"A recording chunk was over 1 MB (a very large page). The recording stopped.\");\n end(true);\n return;\n }\n if (sync && \"sendBeacon\" in navigator && navigator.sendBeacon(url, body)) return;\n try {\n const r = await fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body, keepalive: sync || body.length < 60_000 });\n warnUnsigned(r.status);\n // Recordings turned off, consent missing, the recording reached its size cap, or the person's identity hash\n // is missing or wrong (401): stop for this visit.\n if (r.status === 401 || r.status === 403 || r.status === 409 || r.status === 413) end(true);\n } catch {\n o.warn(`Could not reach ${o.host || \"this origin\"} to upload a recording.`);\n }\n };\n\n function flush(sync: boolean) {\n if (!pending.length) return;\n const events = pending;\n pending = [];\n pendingBytes = 0;\n lastFlush = Date.now();\n start ??= events[0].timestamp;\n const chunkMarks = marks;\n marks = [];\n const payload = {\n key: o.apiKey,\n sessionId: o.sessionId,\n distinctId,\n identified,\n ...(userHash ? { userHash } : {}),\n start,\n seq: seq++,\n consent: { replay: true },\n trigger,\n final: sync,\n meta: {\n first: events[0].timestamp,\n last: events[events.length - 1].timestamp,\n vw: window.innerWidth,\n vh: window.innerHeight,\n marks: chunkMarks,\n },\n };\n const json = `[${events.map((e) => e.json).join(\",\")}]`;\n if (sync) void send(payload, json, true);\n else queue = queue.then(() => send(payload, json, false));\n }\n\n const fire = (kind: Exclude<ReplayTrigger, \"sample\">) => {\n if (stopped || mode === \"upload\") return;\n mode = \"upload\";\n trigger = kind;\n window.clearInterval(checkout);\n pending = ring.drain();\n pendingBytes = pending.reduce((s, e) => s + e.json.length, 0);\n flush(false);\n };\n\n const emit = (e: ReplayEvent) => {\n if (stopped) return;\n if (Date.now() - (start ?? begun) > MAX_RECORDING_MS) {\n end(false);\n return;\n }\n const json = JSON.stringify(e);\n const item: Held = { type: e.type, timestamp: e.timestamp, json };\n if (mode === \"buffer\") {\n ring.push(item, json.length);\n const from = ring.first ?? e.timestamp - BUFFER_MS;\n marks = marks.filter((m) => m.t >= from);\n return;\n }\n pending.push(item);\n pendingBytes += json.length;\n if (pendingBytes >= FLUSH_BYTES) flush(false);\n };\n\n const original = console.error;\n const patched = (...args: unknown[]) => {\n try {\n record.addCustomEvent(\"$console\", { level: \"error\", text: clip(args.map((a) => (a instanceof Error ? a.message : typeof a === \"string\" ? a : \"[object]\")).join(\" \"), 300) });\n } catch {\n // Recording must never break the page's own logging.\n }\n original.apply(console, args);\n };\n const onError = (e: ErrorEvent) => {\n const message = clip(e.message || \"Script error\", 200);\n marks.push({ t: Date.now(), kind: \"error\", path: pathNow(), label: message });\n try {\n record.addCustomEvent(\"$error\", { message });\n } catch {\n // ignore\n }\n fire(\"error\");\n };\n const onRejection = (e: PromiseRejectionEvent) => {\n const r = e.reason as { message?: unknown } | undefined;\n const message = clip(typeof r?.message === \"string\" ? r.message : \"Unhandled promise rejection\", 200);\n marks.push({ t: Date.now(), kind: \"error\", path: pathNow(), label: message });\n try {\n record.addCustomEvent(\"$error\", { message });\n } catch {\n // ignore\n }\n fire(\"error\");\n };\n const onHide = () => mode === \"upload\" && flush(true);\n const onVisibility = () => document.visibilityState === \"hidden\" && mode === \"upload\" && flush(false);\n\n const stopRecording = record(recordOptions(emit) as unknown as Parameters<typeof record>[0]);\n if (!stopRecording) return null;\n console.error = patched;\n window.addEventListener(\"error\", onError);\n window.addEventListener(\"unhandledrejection\", onRejection);\n window.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n const tick = window.setInterval(() => {\n if (Date.now() - (start ?? begun) > MAX_RECORDING_MS) end(false);\n else if (mode === \"upload\" && chunkDue(pendingBytes, Date.now() - lastFlush)) flush(false);\n }, 1000);\n // A buffering visit snapshots every 30 seconds, so the buffer always starts at a full snapshot within the minute.\n const checkout = mode === \"buffer\" ? window.setInterval(() => record.takeFullSnapshot(true), CHECKOUT_MS) : 0;\n\n return {\n event: (name) => {\n const t = triggerOfEvent(name);\n if (t) fire(t);\n },\n click: (c, rage) => {\n if (stopped) return;\n const t = Date.now();\n const path = pathNow();\n const label = c.label || c.selector.split(\" > \").pop() || \"\";\n marks.push({ t, kind: \"click\", path, label, x: c.x, y: c.y, vw: c.vw, dead: !c.interactive });\n if (rage) {\n marks.push({ t, kind: \"rage\", path, label, x: c.x, y: c.y, vw: c.vw });\n fire(\"rage\");\n }\n },\n page: (path) => !stopped && marks.push({ t: Date.now(), kind: \"pageview\", path: path.slice(0, 300) || \"/\" }),\n identify: (id, hash) => {\n // A hash belongs to its id: another id without one goes unsigned.\n if (hash) userHash = hash;\n else if (id !== distinctId) userHash = undefined;\n distinctId = id;\n identified = true;\n },\n stop: (discard = false) => end(discard),\n };\n};\n"],"mappings":";;;AAaA,SAAS,oBAAoB;AAC7B;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AA6CP,IAAM,OAAO,CAAC,GAAY,MAAc,OAAO,KAAK,EAAE,EAAE,MAAM,GAAG,CAAC;AAClE,IAAM,UAAU,MAAM,OAAO,SAAS,SAAS,MAAM,GAAG,GAAG,KAAK;AAEhE,IAAM,OAAO,OAAO,SAAiB;AACjC,QAAM,SAAS,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,YAAY,IAAI,kBAAkB,MAAM,CAAC;AAClF,SAAO,IAAI,WAAW,MAAM,IAAI,SAAS,MAAM,EAAE,YAAY,CAAC;AAClE;AAEO,IAAM,cAAc,OAAO,MAAmD;AACjF,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,EAAE,OAAO,IAAI,MAAM,OAAO,eAAe;AAE/C,QAAM,MAAM,GAAG,EAAE,IAAI;AACrB,MAAI,OAA4B,SAAS,EAAE,WAAW,EAAE,UAAU,IAAI,WAAW;AACjF,MAAI,UAAgC,SAAS,WAAW,WAAW;AACnE,M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G,SAAS;AAChB,UAAI,QAAS;AACb,YAAM,IAAI,KAAK,IAAI;AACnB,YAAM,OAAO,QAAQ;AACrB,YAAM,QAAQ,EAAE,SAAS,EAAE,SAAS,MAAM,KAAK,EAAE,IAAI,KAAK;AAC1D,YAAM,KAAK,EAAE,GAAG,MAAM,SAAS,MAAM,OAAO,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,IAAI,EAAE,IAAI,MAAM,CAAC,EAAE,YAAY,CAAC;AAC5F,UAAI,MAAM;AACN,cAAM,KAAK,EAAE,GAAG,MAAM,QAAQ,MAAM,OAAO,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC;AACrE,aAAK,MAAM;AAAA,MACf;AAAA,IACJ;AAAA,IACA,MAAM,CAAC,SAAS,CAAC,WAAW,MAAM,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,YAAY,MAAM,KAAK,MAAM,GAAG,GAAG,KAAK,IAAI,CAAC;AAAA,IAC3G,UAAU,CAAC,IAAI,SAAS;AAEpB,UAAI,KAAM,YAAW;AAAA,eACZ,OAAO,WAAY,YAAW;AACvC,mBAAa;AACb,mBAAa;AAAA,IACjB;AAAA,IACA,MAAM,CAAC,UAAU,UAAU,IAAI,OAAO;AAAA,EAC1C;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/replay.ts"],"sourcesContent":["\"use client\";\n\n/**\n * The session recorder. The provider imports this file (and rrweb's recorder with it) only when a visit records: the\n * product has recordings on and the visitor gave replay consent. Pages without recording never load it.\n *\n * A visit in the product's sample uploads from its start. Any other visit keeps the last minute in memory and uploads\n * it only when something happens worth watching: a JS error, a rage click, or a `purchase…` / `checkout…` event; from\n * then on it uploads like a sampled one. Chunks go every 5 seconds or 64 KB, gzip'd where the browser can, to\n * `POST {host}/api/sdk/replay`; the last one leaves with sendBeacon when the page hides. A recording ends after 30\n * minutes. Withdrawing consent stops it and drops what was not sent.\n */\nimport type { ClickInfo } from \"./capture\";\nimport { warnUnsigned } from \"./identity\";\nimport {\n BUFFER_MS,\n CHECKOUT_MS,\n FLUSH_BYTES,\n MAX_RECORDING_MS,\n MAX_REQUEST_BYTES,\n type ReplayEvent,\n type ReplayTrigger,\n RingBuffer,\n chunkDue,\n inSample,\n masksAllText,\n recordOptions,\n toBase64,\n triggerOfEvent,\n} from \"./replay-core\";\n\nexport interface ReplayOptions {\n host: string;\n apiKey: string;\n /** The SDK's session id; every chunk carries it, so the recording joins the session's events. */\n sessionId: string;\n /** The identify() id or the cookie id; missing cookieless until identify(). */\n distinctId?: string;\n /** Whether `distinctId` comes from identify() (a person) rather than the visitor cookie. */\n identified?: boolean;\n /** The identity hash of `distinctId` (0.16.0), sent with every chunk while the recording is theirs. */\n userHash?: string;\n sampleRate: number;\n /**\n * Mask every text on the page, not only `data-ck-mask`. Left out (the default): while the visitor is a signed-in\n * user (`identify()` was called). `true`: always. `false`: never. `data-ck-unmask` keeps an element readable.\n */\n maskAllText?: boolean;\n warn: (message: string) => void;\n}\n\nexport interface ReplayHandle {\n /** A tracked event; `purchase…` and `checkout…` upload the buffered minute. */\n event(name: string): void;\n click(c: ClickInfo, rage: boolean): void;\n /** A client-side navigation. */\n page(path: string): void;\n /** The person the site identified, with their identity hash when it has one (0.16.0). */\n identify(id: string, userHash?: string): void;\n /** Stops recording. `discard` (consent withdrawn) drops everything not sent yet. */\n stop(discard?: boolean): void;\n}\n\n/** One line of the masked event list the server keeps next to the recording (pages, clicks, rage clicks, errors). */\ninterface Mark {\n t: number;\n kind: \"pageview\" | \"click\" | \"rage\" | \"error\";\n path: string;\n label?: string;\n x?: number;\n y?: number;\n vw?: number;\n dead?: boolean;\n}\n\ninterface Held extends ReplayEvent {\n json: string;\n}\n\nconst clip = (s: unknown, n: number) => String(s ?? \"\").slice(0, n);\nconst pathNow = () => window.location.pathname.slice(0, 300) || \"/\";\n\nconst gzip = async (text: string) => {\n const stream = new Blob([text]).stream().pipeThrough(new CompressionStream(\"gzip\"));\n return new Uint8Array(await new Response(stream).arrayBuffer());\n};\n\nexport const startReplay = async (o: ReplayOptions): Promise<ReplayHandle | null> => {\n if (typeof window === \"undefined\") return null;\n const { record } = await import(\"@rrweb/record\");\n\n const url = `${o.host}/api/sdk/replay`;\n let mode: \"upload\" | \"buffer\" = inSample(o.sessionId, o.sampleRate) ? \"upload\" : \"buffer\";\n let trigger: ReplayTrigger | null = mode === \"upload\" ? \"sample\" : null;\n let distinctId = o.distinctId;\n let identified = o.identified === true;\n let userHash = o.userHash;\n let start: number | null = null;\n let seq = 0;\n let stopped = false;\n const begun = Date.now();\n const ring = new RingBuffer<Held>();\n let pending: Held[] = [];\n let pendingBytes = 0;\n let lastFlush = Date.now();\n let marks: Mark[] = [{ t: Date.now(), kind: \"pageview\", path: pathNow() }];\n let queue: Promise<void> = Promise.resolve();\n\n const end = (discard: boolean) => {\n if (stopped) return;\n if (!discard && mode === \"upload\") flush(false);\n stopped = true;\n stopRecording?.();\n window.clearInterval(tick);\n window.clearInterval(checkout);\n window.removeEventListener(\"error\", onError);\n window.removeEventListener(\"unhandledrejection\", onRejection);\n window.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n if (console.error === patched) console.error = original;\n pending = [];\n ring.clear();\n marks = [];\n };\n\n const send = async (payload: Record<string, unknown>, events: string, sync: boolean) => {\n let body: string;\n if (!sync && typeof CompressionStream !== \"undefined\") body = JSON.stringify({ ...payload, enc: \"gzip\", data: toBase64(await gzip(events)) });\n else body = JSON.stringify({ ...payload, enc: \"json\", data: events });\n if (body.length > MAX_REQUEST_BYTES) {\n o.warn(\"A recording chunk was over 1 MB (a very large page). The recording stopped.\");\n end(true);\n return;\n }\n if (sync && \"sendBeacon\" in navigator && navigator.sendBeacon(url, body)) return;\n try {\n const r = await fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body, keepalive: sync || body.length < 60_000 });\n warnUnsigned(r.status);\n // Recordings turned off, consent missing, the recording reached its size cap, or the person's identity hash\n // is missing or wrong (401): stop for this visit.\n if (r.status === 401 || r.status === 403 || r.status === 409 || r.status === 413) end(true);\n } catch {\n o.warn(`Could not reach ${o.host || \"this origin\"} to upload a recording.`);\n }\n };\n\n function flush(sync: boolean) {\n if (!pending.length) return;\n const events = pending;\n pending = [];\n pendingBytes = 0;\n lastFlush = Date.now();\n start ??= events[0].timestamp;\n const chunkMarks = marks;\n marks = [];\n const payload = {\n key: o.apiKey,\n sessionId: o.sessionId,\n distinctId,\n identified,\n ...(userHash ? { userHash } : {}),\n start,\n seq: seq++,\n consent: { replay: true },\n trigger,\n final: sync,\n meta: {\n first: events[0].timestamp,\n last: events[events.length - 1].timestamp,\n vw: window.innerWidth,\n vh: window.innerHeight,\n marks: chunkMarks,\n },\n };\n const json = `[${events.map((e) => e.json).join(\",\")}]`;\n if (sync) void send(payload, json, true);\n else queue = queue.then(() => send(payload, json, false));\n }\n\n const fire = (kind: Exclude<ReplayTrigger, \"sample\">) => {\n if (stopped || mode === \"upload\") return;\n mode = \"upload\";\n trigger = kind;\n window.clearInterval(checkout);\n pending = ring.drain();\n pendingBytes = pending.reduce((s, e) => s + e.json.length, 0);\n flush(false);\n };\n\n const emit = (e: ReplayEvent) => {\n if (stopped) return;\n if (Date.now() - (start ?? begun) > MAX_RECORDING_MS) {\n end(false);\n return;\n }\n const json = JSON.stringify(e);\n const item: Held = { type: e.type, timestamp: e.timestamp, json };\n if (mode === \"buffer\") {\n ring.push(item, json.length);\n const from = ring.first ?? e.timestamp - BUFFER_MS;\n marks = marks.filter((m) => m.t >= from);\n return;\n }\n pending.push(item);\n pendingBytes += json.length;\n if (pendingBytes >= FLUSH_BYTES) flush(false);\n };\n\n const original = console.error;\n const patched = (...args: unknown[]) => {\n try {\n record.addCustomEvent(\"$console\", { level: \"error\", text: clip(args.map((a) => (a instanceof Error ? a.message : typeof a === \"string\" ? a : \"[object]\")).join(\" \"), 300) });\n } catch {\n // Recording must never break the page's own logging.\n }\n original.apply(console, args);\n };\n const onError = (e: ErrorEvent) => {\n const message = clip(e.message || \"Script error\", 200);\n marks.push({ t: Date.now(), kind: \"error\", path: pathNow(), label: message });\n try {\n record.addCustomEvent(\"$error\", { message });\n } catch {\n // ignore\n }\n fire(\"error\");\n };\n const onRejection = (e: PromiseRejectionEvent) => {\n const r = e.reason as { message?: unknown } | undefined;\n const message = clip(typeof r?.message === \"string\" ? r.message : \"Unhandled promise rejection\", 200);\n marks.push({ t: Date.now(), kind: \"error\", path: pathNow(), label: message });\n try {\n record.addCustomEvent(\"$error\", { message });\n } catch {\n // ignore\n }\n fire(\"error\");\n };\n const onHide = () => mode === \"upload\" && flush(true);\n const onVisibility = () => document.visibilityState === \"hidden\" && mode === \"upload\" && flush(false);\n\n // All text is masked while the visitor is a signed-in user (or always, or never: `maskAllText`); asked per piece of\n // text, so it follows identify() without a restart.\n const maskAll = o.maskAllText === false ? undefined : () => masksAllText(o.maskAllText, identified);\n const stopRecording = record(recordOptions(emit, maskAll) as unknown as Parameters<typeof record>[0]);\n if (!stopRecording) return null;\n console.error = patched;\n window.addEventListener(\"error\", onError);\n window.addEventListener(\"unhandledrejection\", onRejection);\n window.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n const tick = window.setInterval(() => {\n if (Date.now() - (start ?? begun) > MAX_RECORDING_MS) end(false);\n else if (mode === \"upload\" && chunkDue(pendingBytes, Date.now() - lastFlush)) flush(false);\n }, 1000);\n // A buffering visit snapshots every 30 seconds, so the buffer always starts at a full snapshot within the minute.\n const checkout = mode === \"buffer\" ? window.setInterval(() => record.takeFullSnapshot(true), CHECKOUT_MS) : 0;\n\n return {\n event: (name) => {\n const t = triggerOfEvent(name);\n if (t) fire(t);\n },\n click: (c, rage) => {\n if (stopped) return;\n const t = Date.now();\n const path = pathNow();\n const label = c.label || c.selector.split(\" > \").pop() || \"\";\n marks.push({ t, kind: \"click\", path, label, x: c.x, y: c.y, vw: c.vw, dead: !c.interactive });\n if (rage) {\n marks.push({ t, kind: \"rage\", path, label, x: c.x, y: c.y, vw: c.vw });\n fire(\"rage\");\n }\n },\n page: (path) => !stopped && marks.push({ t: Date.now(), kind: \"pageview\", path: path.slice(0, 300) || \"/\" }),\n identify: (id, hash) => {\n // A hash belongs to its id: another id without one goes unsigned.\n if (hash) userHash = hash;\n else if (id !== distinctId) userHash = undefined;\n distinctId = id;\n const masksNow = !identified && o.maskAllText === undefined;\n identified = true;\n // A new full snapshot, so the text already on screen is masked in everything recorded from here on (what\n // was recorded before the sign-in stays as it was).\n if (masksNow && !stopped) {\n try {\n record.takeFullSnapshot(true);\n } catch {\n // The next snapshot masks it.\n }\n }\n },\n stop: (discard = false) => end(discard),\n };\n};\n"],"mappings":";;;AAaA,SAAS,oBAAoB;AAC7B;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAkDP,IAAM,OAAO,CAAC,GAAY,MAAc,OAAO,KAAK,EAAE,EAAE,MAAM,GAAG,CAAC;AAClE,IAAM,UAAU,MAAM,OAAO,SAAS,SAAS,MAAM,GAAG,GAAG,KAAK;AAEhE,IAAM,OAAO,OAAO,SAAiB;AACjC,QAAM,SAAS,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,YAAY,IAAI,kBAAkB,MAAM,CAAC;AAClF,SAAO,IAAI,WAAW,MAAM,IAAI,SAAS,MAAM,EAAE,YAAY,CAAC;AAClE;AAEO,IAAM,cAAc,OAAO,MAAmD;AACjF,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,EAAE,OAAO,IAAI,MAAM,OAAO,eAAe;AAE/C,QAAM,MAAM,GAAG,EAAE,IAAI;AACrB,MAAI,OAA4B,SAAS,EAAE,WAAW,EAAE,UAAU,IAAI,WAAW;AACjF,MAAI,UAAgC,SAAS,WAAW,WAAW;AACnE,MAAI,aAAa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;AAC7B,UAAI,EAAG,MAAK,CAAC;AAAA,IACjB;AAAA,IACA,OAAO,CAAC,GAAG,SAAS;AAChB,UAAI,QAAS;AACb,YAAM,IAAI,KAAK,IAAI;AACnB,YAAM,OAAO,QAAQ;AACrB,YAAM,QAAQ,EAAE,SAAS,EAAE,SAAS,MAAM,KAAK,EAAE,IAAI,KAAK;AAC1D,YAAM,KAAK,EAAE,GAAG,MAAM,SAAS,MAAM,OAAO,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,IAAI,EAAE,IAAI,MAAM,CAAC,EAAE,YAAY,CAAC;AAC5F,UAAI,MAAM;AACN,cAAM,KAAK,EAAE,GAAG,MAAM,QAAQ,MAAM,OAAO,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC;AACrE,aAAK,MAAM;AAAA,MACf;AAAA,IACJ;AAAA,IACA,MAAM,CAAC,SAAS,CAAC,WAAW,MAAM,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,YAAY,MAAM,KAAK,MAAM,GAAG,GAAG,KAAK,IAAI,CAAC;AAAA,IAC3G,UAAU,CAAC,IAAI,SAAS;AAEpB,UAAI,KAAM,YAAW;AAAA,eACZ,OAAO,WAAY,YAAW;AACvC,mBAAa;AACb,YAAM,WAAW,CAAC,cAAc,EAAE,gBAAgB;AAClD,mBAAa;AAGb,UAAI,YAAY,CAAC,SAAS;AACtB,YAAI;AACA,iBAAO,iBAAiB,IAAI;AAAA,QAChC,QAAQ;AAAA,QAER;AAAA,MACJ;AAAA,IACJ;AAAA,IACA,MAAM,CAAC,UAAU,UAAU,IAAI,OAAO;AAAA,EAC1C;AACJ;","names":[]}
|
package/dist/user-hash.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* <CockpitProvider distinctId={user?.id} userHash={hash}> // or identify(user.id, props, { hash }) in the browser
|
|
8
8
|
*
|
|
9
9
|
* The formula, for a backend in another language (the server key is `mrr_sk_…`, MRRocket › Settings › Products ›
|
|
10
|
-
* Sign-in;
|
|
10
|
+
* Sign-in; the HMAC key is the server key's SHA-256, which MRRocket keeps encrypted, never in the clear):
|
|
11
11
|
*
|
|
12
12
|
* userHash = lowercase hex( HMAC-SHA256( key = SHA-256(server key) as its 32 raw bytes, message = user id as UTF-8 ) )
|
|
13
13
|
*
|
package/dist/user-hash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/user-hash.ts"],"sourcesContent":["/**\n * Identity verification (0.16.0), the server side: signs a user id so MRRocket can tell that requests for it come from\n * that user's own session, not from someone who only knows the id. Like Intercom's identity verification.\n *\n * // app/layout.tsx (a server component)\n * const hash = user ? await userHash(user.id) : undefined;\n * <CockpitProvider distinctId={user?.id} userHash={hash}> // or identify(user.id, props, { hash }) in the browser\n *\n * The formula, for a backend in another language (the server key is `mrr_sk_…`, MRRocket › Settings › Products ›\n * Sign-in;
|
|
1
|
+
{"version":3,"sources":["../src/user-hash.ts"],"sourcesContent":["/**\n * Identity verification (0.16.0), the server side: signs a user id so MRRocket can tell that requests for it come from\n * that user's own session, not from someone who only knows the id. Like Intercom's identity verification.\n *\n * // app/layout.tsx (a server component)\n * const hash = user ? await userHash(user.id) : undefined;\n * <CockpitProvider distinctId={user?.id} userHash={hash}> // or identify(user.id, props, { hash }) in the browser\n *\n * The formula, for a backend in another language (the server key is `mrr_sk_…`, MRRocket › Settings › Products ›\n * Sign-in; the HMAC key is the server key's SHA-256, which MRRocket keeps encrypted, never in the clear):\n *\n * userHash = lowercase hex( HMAC-SHA256( key = SHA-256(server key) as its 32 raw bytes, message = user id as UTF-8 ) )\n *\n * Only on your server: the server key must never reach a browser or an app bundle. WebCrypto only (`crypto.subtle`), so\n * it runs on Node 18+ (Next.js provides `crypto` there; plain Node 18 needs `globalThis.crypto ??=\n * require(\"node:crypto\").webcrypto`), the Edge runtime, Cloudflare Workers, Deno and Bun.\n */\n\nexport interface UserHashOptions {\n /** The product's server key (`mrr_sk_…`). Defaults to `MRROCKET_SERVER_KEY`. */\n serverKey?: string;\n}\n\nexport const envServerKey = () => {\n try {\n return typeof process !== \"undefined\" ? process.env.MRROCKET_SERVER_KEY : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst hex = (buf: ArrayBuffer) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n/**\n * The hash of `userId` for `identify(id, props, { hash })` (64 lowercase hex characters). Throws when there is no\n * server key (pass `serverKey` or set `MRROCKET_SERVER_KEY`) or no WebCrypto, so a missing setting shows at once on\n * your server instead of as refused requests in the browser.\n */\nexport const userHash = async (userId: string, { serverKey }: UserHashOptions = {}): Promise<string> => {\n if (typeof userId !== \"string\" || !userId) throw new Error(\"userHash: the user id must be a non-empty string (the same id you pass to identify).\");\n const key = (serverKey ?? envServerKey() ?? \"\").trim();\n if (!key) throw new Error(\"userHash: no server key. Set MRROCKET_SERVER_KEY (MRRocket › Settings › Products › your product › Sign-in) or pass { serverKey }.\");\n const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;\n if (!subtle) throw new Error('userHash needs WebCrypto (crypto.subtle). On plain Node 18 add: globalThis.crypto ??= require(\"node:crypto\").webcrypto');\n const utf8 = new TextEncoder();\n const signingKey = await subtle.digest(\"SHA-256\", utf8.encode(key));\n const hmac = await subtle.importKey(\"raw\", signingKey, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await subtle.sign(\"HMAC\", hmac, utf8.encode(userId)));\n};\n"],"mappings":";AAuBO,IAAM,eAAe,MAAM;AAC9B,MAAI;AACA,WAAO,OAAO,YAAY,cAAc,QAAQ,IAAI,sBAAsB;AAAA,EAC9E,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,IAAM,MAAM,CAAC,QAAqB,MAAM,KAAK,IAAI,WAAW,GAAG,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAO1G,IAAM,WAAW,OAAO,QAAgB,EAAE,UAAU,IAAqB,CAAC,MAAuB;AACpG,MAAI,OAAO,WAAW,YAAY,CAAC,OAAQ,OAAM,IAAI,MAAM,sFAAsF;AACjJ,QAAM,OAAO,aAAa,aAAa,KAAK,IAAI,KAAK;AACrD,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,uJAAmI;AAC7J,QAAM,SAAU,WAAmC,QAAQ;AAC3D,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wHAAwH;AACrJ,QAAM,OAAO,IAAI,YAAY;AAC7B,QAAM,aAAa,MAAM,OAAO,OAAO,WAAW,KAAK,OAAO,GAAG,CAAC;AAClE,QAAM,OAAO,MAAM,OAAO,UAAU,OAAO,YAAY,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;AACzG,SAAO,IAAI,MAAM,OAAO,KAAK,QAAQ,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;AACnE;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mrrocket/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.0",
|
|
4
4
|
"description": "MRRocket SDK: page views, events, heatmap clicks, session recordings, A/B tests, feature flags, error tracking, feedback board, surveys, a chat messenger, a cancel flow, onboarding tours and checklists, in-app messages, push notifications and redirect tests that your MRRocket agents can run and read. Next.js (@mrrocket/sdk/next), React Native and Expo (@mrrocket/sdk/react-native), and a script tag for any website.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nextjs",
|