@keploy/capture-sdk 3.0.1 → 3.1.0-rc.2
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 +1617 -130
- package/body-redact/package.json +6 -0
- package/body-worker-start/package.json +6 -0
- package/dist/body-jobs.d.ts +134 -0
- package/dist/body-redact.d.ts +23 -0
- package/dist/body-redact.js +1 -0
- package/dist/body-redact.js.map +1 -0
- package/dist/body-redact.mjs +1 -0
- package/dist/body-redact.mjs.map +1 -0
- package/dist/body-worker-none.d.ts +3 -0
- package/dist/body-worker-none.js +1 -0
- package/dist/body-worker-none.js.map +1 -0
- package/dist/body-worker-none.mjs +1 -0
- package/dist/body-worker-none.mjs.map +1 -0
- package/dist/body-worker-start.d.ts +3 -0
- package/dist/body-worker-start.js +1 -0
- package/dist/body-worker-start.js.map +1 -0
- package/dist/body-worker-start.mjs +1 -0
- package/dist/body-worker-start.mjs.map +1 -0
- package/dist/body-worker-unbundled.d.ts +1 -0
- package/dist/body-worker-unbundled.mjs +1 -0
- package/dist/body-worker-unbundled.mjs.map +1 -0
- package/dist/body-worker.d.ts +1 -0
- package/dist/body-worker.js +1 -0
- package/dist/body-worker.js.map +1 -0
- package/dist/errors.d.ts +224 -28
- package/dist/index.bundler.mjs +1 -0
- package/dist/index.bundler.mjs.map +1 -0
- package/dist/index.d.ts +23 -28
- package/dist/index.js +1 -2354
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1 -2297
- package/dist/index.mjs.map +1 -0
- package/dist/leave.d.ts +67 -0
- package/dist/module-of.d.ts +58 -0
- package/dist/network.d.ts +163 -4
- package/dist/privacy.d.ts +387 -12
- package/dist/recorder.d.ts +304 -64
- package/dist/redact.d.ts +48 -6
- package/dist/request-term.d.ts +23 -0
- package/dist/request-term.js +1 -0
- package/dist/request-term.js.map +1 -0
- package/dist/request-term.mjs +1 -0
- package/dist/request-term.mjs.map +1 -0
- package/dist/strict-attributes.d.ts +9 -0
- package/dist/strict-attributes.js +1 -0
- package/dist/strict-attributes.js.map +1 -0
- package/dist/strict-attributes.mjs +1 -0
- package/dist/strict-attributes.mjs.map +1 -0
- package/dist/term-candidate.d.ts +16 -0
- package/dist/transport.d.ts +269 -130
- package/dist/types.d.ts +152 -9
- package/package.json +37 -4
- package/request-term/package.json +6 -0
- package/strict-attributes/package.json +6 -0
package/dist/index.js
CHANGED
|
@@ -1,2354 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/index.ts
|
|
31
|
-
var index_exports = {};
|
|
32
|
-
__export(index_exports, {
|
|
33
|
-
CaptureError: () => CaptureError,
|
|
34
|
-
CaptureIdentityBuilder: () => CaptureIdentityBuilder,
|
|
35
|
-
IngestRejection: () => IngestRejection,
|
|
36
|
-
KeployCapture: () => KeployCapture,
|
|
37
|
-
KeployCaptureRecorder: () => KeployCaptureRecorder,
|
|
38
|
-
NetworkInterceptor: () => NetworkInterceptor,
|
|
39
|
-
PrivacyEngine: () => PrivacyEngine,
|
|
40
|
-
SDK_ERRORS: () => SDK_ERRORS,
|
|
41
|
-
SDK_WARNINGS: () => SDK_WARNINGS,
|
|
42
|
-
SESSION_ID_MAX_LENGTH: () => SESSION_ID_MAX_LENGTH,
|
|
43
|
-
SESSION_ID_PATTERN: () => SESSION_ID_PATTERN,
|
|
44
|
-
SESSION_ID_RULE: () => SESSION_ID_RULE,
|
|
45
|
-
SessionIdRefusal: () => SessionIdRefusal,
|
|
46
|
-
Transport: () => Transport,
|
|
47
|
-
codeForStatus: () => codeForStatus,
|
|
48
|
-
currentOrigin: () => currentOrigin,
|
|
49
|
-
defaultPrivacyConfig: () => defaultPrivacyConfig,
|
|
50
|
-
describeValue: () => describeValue,
|
|
51
|
-
isValidSessionId: () => isValidSessionId,
|
|
52
|
-
mintSessionNonce: () => mintSessionNonce,
|
|
53
|
-
parseServerError: () => parseServerError
|
|
54
|
-
});
|
|
55
|
-
module.exports = __toCommonJS(index_exports);
|
|
56
|
-
|
|
57
|
-
// src/redact.ts
|
|
58
|
-
var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
|
|
59
|
-
"password",
|
|
60
|
-
"passwd",
|
|
61
|
-
"pwd",
|
|
62
|
-
"secret",
|
|
63
|
-
"token",
|
|
64
|
-
"access_token",
|
|
65
|
-
"accesstoken",
|
|
66
|
-
"refresh_token",
|
|
67
|
-
"refreshtoken",
|
|
68
|
-
"id_token",
|
|
69
|
-
"idtoken",
|
|
70
|
-
"authorization",
|
|
71
|
-
"auth",
|
|
72
|
-
"apikey",
|
|
73
|
-
"api_key",
|
|
74
|
-
"client_secret",
|
|
75
|
-
"clientsecret",
|
|
76
|
-
"private_key",
|
|
77
|
-
"privatekey",
|
|
78
|
-
"session",
|
|
79
|
-
"sessionid",
|
|
80
|
-
"session_id",
|
|
81
|
-
"cookie",
|
|
82
|
-
"ssn",
|
|
83
|
-
"socialsecuritynumber",
|
|
84
|
-
"creditcard",
|
|
85
|
-
"credit_card",
|
|
86
|
-
"cardnumber",
|
|
87
|
-
"card_number",
|
|
88
|
-
"cvv",
|
|
89
|
-
"cvc",
|
|
90
|
-
"pin",
|
|
91
|
-
"otp"
|
|
92
|
-
]);
|
|
93
|
-
var REDACTED = "[REDACTED]";
|
|
94
|
-
var TRUNCATED_UNPARSEABLE = "[UNPARSEABLE_BODY_NOT_REDACTED]";
|
|
95
|
-
var NOT_RECORDED = [
|
|
96
|
-
/^\[Blob: \d+ bytes, truncated\]$/,
|
|
97
|
-
// The XHR path's Blob, which is named rather than read: its body has
|
|
98
|
-
// to be serialised inside send(), and Blob.text() is async.
|
|
99
|
-
/^\[Blob: \d+ bytes\]$/,
|
|
100
|
-
/^\[Binary: \d+ bytes\]$/,
|
|
101
|
-
/^\[Response body too large: \d+ bytes\]$/,
|
|
102
|
-
/^\[ReadableStream\]$/,
|
|
103
|
-
/^\[Unreadable body\]$/,
|
|
104
|
-
// `[${xhr.responseType} response]` — the XMLHttpRequestResponseType
|
|
105
|
-
// enum: "", arraybuffer, blob, document, json, text.
|
|
106
|
-
/^\[(?:arraybuffer|blob|document|json|text|) response\]$/
|
|
107
|
-
];
|
|
108
|
-
function isNotRecordedNote(body) {
|
|
109
|
-
return NOT_RECORDED.some((re) => re.test(body));
|
|
110
|
-
}
|
|
111
|
-
function normalizeKey(key) {
|
|
112
|
-
return key.toLowerCase().replace(/[-_\s]/g, "");
|
|
113
|
-
}
|
|
114
|
-
function isSensitiveKey(key) {
|
|
115
|
-
const n = normalizeKey(key);
|
|
116
|
-
if (SENSITIVE_KEYS.has(n)) return true;
|
|
117
|
-
return n.endsWith("password") || n.endsWith("secret") || n.endsWith("token") || n.endsWith("apikey") || n.endsWith("privatekey");
|
|
118
|
-
}
|
|
119
|
-
var EMAIL_RE = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
|
|
120
|
-
var SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
|
|
121
|
-
var PHONE_RE = /(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g;
|
|
122
|
-
var JWT_RE = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g;
|
|
123
|
-
var IPV4_RE = /(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![\d.])/g;
|
|
124
|
-
function passesLuhn(digits) {
|
|
125
|
-
let sum = 0;
|
|
126
|
-
let double = false;
|
|
127
|
-
for (let i = digits.length - 1; i >= 0; i--) {
|
|
128
|
-
let d = digits.charCodeAt(i) - 48;
|
|
129
|
-
if (d < 0 || d > 9) return false;
|
|
130
|
-
if (double) {
|
|
131
|
-
d *= 2;
|
|
132
|
-
if (d > 9) d -= 9;
|
|
133
|
-
}
|
|
134
|
-
sum += d;
|
|
135
|
-
double = !double;
|
|
136
|
-
}
|
|
137
|
-
return sum % 10 === 0;
|
|
138
|
-
}
|
|
139
|
-
function isLikelyCardNumber(digits) {
|
|
140
|
-
if (digits.length < 13 || digits.length > 19) return false;
|
|
141
|
-
const isVisa = digits[0] === "4" && (digits.length === 13 || digits.length === 16 || digits.length === 19);
|
|
142
|
-
const isMastercard = /^(5[1-5]|2[2-7])/.test(digits) && digits.length === 16;
|
|
143
|
-
const isAmex = /^3[47]/.test(digits) && digits.length === 15;
|
|
144
|
-
const isDiscover = /^6(?:011|5)/.test(digits) && digits.length === 16;
|
|
145
|
-
const isJcbDiners = /^(?:35|3[068])/.test(digits) && digits.length >= 14 && digits.length <= 19;
|
|
146
|
-
if (!(isVisa || isMastercard || isAmex || isDiscover || isJcbDiners))
|
|
147
|
-
return false;
|
|
148
|
-
return passesLuhn(digits);
|
|
149
|
-
}
|
|
150
|
-
function redactCards(s) {
|
|
151
|
-
return s.replace(/\b(?:\d[ -]?){12,18}\d\b/g, (match) => {
|
|
152
|
-
const digits = match.replace(/[^0-9]/g, "");
|
|
153
|
-
return isLikelyCardNumber(digits) ? REDACTED : match;
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
function redactStringValue(value, extra = []) {
|
|
157
|
-
if (!value) return value;
|
|
158
|
-
let out = value;
|
|
159
|
-
out = out.replace(JWT_RE, REDACTED);
|
|
160
|
-
out = out.replace(EMAIL_RE, REDACTED);
|
|
161
|
-
out = out.replace(SSN_RE, REDACTED);
|
|
162
|
-
out = out.replace(PHONE_RE, REDACTED);
|
|
163
|
-
out = out.replace(IPV4_RE, REDACTED);
|
|
164
|
-
out = redactCards(out);
|
|
165
|
-
for (const re of extra) out = out.replace(re, REDACTED);
|
|
166
|
-
return out;
|
|
167
|
-
}
|
|
168
|
-
var MAX_DEPTH = 64;
|
|
169
|
-
function redactValue(value, keyHint, depth, extra) {
|
|
170
|
-
if (depth > MAX_DEPTH) return REDACTED;
|
|
171
|
-
if (value === null || value === void 0) return value;
|
|
172
|
-
const t = typeof value;
|
|
173
|
-
if (t === "number" || t === "boolean" || t === "bigint") {
|
|
174
|
-
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
175
|
-
if (typeof value === "number" && Number.isInteger(value)) {
|
|
176
|
-
const digits = String(value);
|
|
177
|
-
if (isLikelyCardNumber(digits)) return REDACTED;
|
|
178
|
-
}
|
|
179
|
-
return value;
|
|
180
|
-
}
|
|
181
|
-
if (t === "string") {
|
|
182
|
-
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
183
|
-
return redactStringValue(value, extra);
|
|
184
|
-
}
|
|
185
|
-
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
186
|
-
if (Array.isArray(value)) {
|
|
187
|
-
return value.map((v) => redactValue(v, keyHint, depth + 1, extra));
|
|
188
|
-
}
|
|
189
|
-
if (t === "object") {
|
|
190
|
-
const out = /* @__PURE__ */ Object.create(null);
|
|
191
|
-
for (const [k, v] of Object.entries(value)) {
|
|
192
|
-
out[k] = redactValue(v, isSensitiveKey(k) ? k : null, depth + 1, extra);
|
|
193
|
-
}
|
|
194
|
-
return { ...out };
|
|
195
|
-
}
|
|
196
|
-
return value;
|
|
197
|
-
}
|
|
198
|
-
function redactBody(body, contentType, extra = []) {
|
|
199
|
-
if (body === null || body === void 0 || body === "") return body ?? null;
|
|
200
|
-
if (isNotRecordedNote(body)) return body;
|
|
201
|
-
const looksJson = (contentType ?? "").toLowerCase().includes("json") || /^\s*[[{]/.test(body);
|
|
202
|
-
if (looksJson) {
|
|
203
|
-
try {
|
|
204
|
-
return JSON.stringify(redactValue(JSON.parse(body), null, 0, extra));
|
|
205
|
-
} catch {
|
|
206
|
-
return TRUNCATED_UNPARSEABLE;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
return redactStringValue(body, extra);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// src/privacy.ts
|
|
213
|
-
var SENSITIVE_PARAMS = /* @__PURE__ */ new Set([
|
|
214
|
-
"token",
|
|
215
|
-
"accesstoken",
|
|
216
|
-
"idtoken",
|
|
217
|
-
"refreshtoken",
|
|
218
|
-
"password",
|
|
219
|
-
"secret",
|
|
220
|
-
"apikey",
|
|
221
|
-
"clientsecret",
|
|
222
|
-
"signature",
|
|
223
|
-
"authorization",
|
|
224
|
-
"sessionid"
|
|
225
|
-
]);
|
|
226
|
-
function isSensitiveParam(name) {
|
|
227
|
-
return SENSITIVE_PARAMS.has(name.toLowerCase().replace(/[-_]/g, ""));
|
|
228
|
-
}
|
|
229
|
-
function findContentType(headers) {
|
|
230
|
-
if (!headers) return void 0;
|
|
231
|
-
for (const [k, v] of Object.entries(headers)) {
|
|
232
|
-
if (k.toLowerCase() === "content-type") return v;
|
|
233
|
-
}
|
|
234
|
-
return void 0;
|
|
235
|
-
}
|
|
236
|
-
var BUILTIN_PII_PATTERNS = [
|
|
237
|
-
{
|
|
238
|
-
name: "email",
|
|
239
|
-
pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
|
|
240
|
-
},
|
|
241
|
-
{
|
|
242
|
-
name: "phone_us",
|
|
243
|
-
// Every leading group used to be optional, reducing this to "any
|
|
244
|
-
// 7-digit run": it matched order ids, invoice numbers, timestamps and
|
|
245
|
-
// Content-Length values. A separator or explicit country code is now
|
|
246
|
-
// required.
|
|
247
|
-
pattern: /(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g
|
|
248
|
-
},
|
|
249
|
-
{
|
|
250
|
-
name: "ssn",
|
|
251
|
-
pattern: /\b\d{3}-\d{2}-\d{4}\b/g
|
|
252
|
-
},
|
|
253
|
-
// credit_card was removed from this list. The pattern
|
|
254
|
-
// /\b(?:\d[ -]*?){13,19}\b/ matched every 13-digit Date.now() and every
|
|
255
|
-
// long numeric id, and replacing inside a serialized number produced
|
|
256
|
-
// invalid JSON. Card numbers are now detected in redact.ts against
|
|
257
|
-
// string values only, requiring issuer prefix + length + Luhn.
|
|
258
|
-
{
|
|
259
|
-
name: "ipv4",
|
|
260
|
-
pattern: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g
|
|
261
|
-
}
|
|
262
|
-
];
|
|
263
|
-
var DEFAULT_SENSITIVE_HEADERS = [
|
|
264
|
-
"authorization",
|
|
265
|
-
"cookie",
|
|
266
|
-
"set-cookie",
|
|
267
|
-
"x-api-key",
|
|
268
|
-
"x-auth-token",
|
|
269
|
-
"proxy-authorization"
|
|
270
|
-
];
|
|
271
|
-
function defaultPrivacyConfig() {
|
|
272
|
-
return {
|
|
273
|
-
maskSelectors: [],
|
|
274
|
-
unmaskSelectors: [],
|
|
275
|
-
blockSelectors: [],
|
|
276
|
-
maskNetworkBodies: false,
|
|
277
|
-
sensitiveHeaders: [...DEFAULT_SENSITIVE_HEADERS],
|
|
278
|
-
piiPatterns: []
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
function mergePrivacyConfig(base, partial) {
|
|
282
|
-
const defined = Object.fromEntries(
|
|
283
|
-
Object.entries(partial).filter(([, v]) => v !== void 0)
|
|
284
|
-
);
|
|
285
|
-
const merged = { ...base, ...defined };
|
|
286
|
-
if (defined.sensitiveHeaders) {
|
|
287
|
-
const seen = /* @__PURE__ */ new Set();
|
|
288
|
-
merged.sensitiveHeaders = [
|
|
289
|
-
...DEFAULT_SENSITIVE_HEADERS,
|
|
290
|
-
...base.sensitiveHeaders,
|
|
291
|
-
...defined.sensitiveHeaders
|
|
292
|
-
].filter((h) => {
|
|
293
|
-
const k = h.toLowerCase();
|
|
294
|
-
if (seen.has(k)) return false;
|
|
295
|
-
seen.add(k);
|
|
296
|
-
return true;
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
return merged;
|
|
300
|
-
}
|
|
301
|
-
function compileGlobal(patterns) {
|
|
302
|
-
return patterns.map(
|
|
303
|
-
({ pattern }) => pattern.flags.includes("g") ? new RegExp(pattern.source, pattern.flags) : new RegExp(pattern.source, pattern.flags + "g")
|
|
304
|
-
);
|
|
305
|
-
}
|
|
306
|
-
var PrivacyEngine = class {
|
|
307
|
-
config;
|
|
308
|
-
builtinPatterns;
|
|
309
|
-
/** The integrator's piiPatterns, compiled global once. */
|
|
310
|
-
userPatterns;
|
|
311
|
-
constructor(config = {}) {
|
|
312
|
-
this.config = mergePrivacyConfig(defaultPrivacyConfig(), config);
|
|
313
|
-
this.builtinPatterns = compileGlobal(BUILTIN_PII_PATTERNS);
|
|
314
|
-
this.userPatterns = compileGlobal(this.config.piiPatterns);
|
|
315
|
-
}
|
|
316
|
-
/* -------------------------------------------------------------- */
|
|
317
|
-
/* Text masking */
|
|
318
|
-
/* -------------------------------------------------------------- */
|
|
319
|
-
/**
|
|
320
|
-
* Replace every occurrence of known PII patterns in `text` with
|
|
321
|
-
* `[REDACTED]`. Returns the scrubbed string.
|
|
322
|
-
*/
|
|
323
|
-
maskText(text) {
|
|
324
|
-
if (!text) return text;
|
|
325
|
-
let result = redactStringValue(text, this.userPatterns);
|
|
326
|
-
for (const re of this.builtinPatterns) {
|
|
327
|
-
result = result.replace(re, "[REDACTED]");
|
|
328
|
-
}
|
|
329
|
-
return result;
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* Redact a URL without disturbing the parts that carry request identity.
|
|
333
|
-
*
|
|
334
|
-
* The path is left exactly as captured — it is what the canonical key is
|
|
335
|
-
* computed from, and rewriting it makes the recording unreplayable.
|
|
336
|
-
* Query values are redacted by parameter NAME (token, password, apikey,
|
|
337
|
-
* ... — the set canonkey.ts excludes from the key) and by nothing else:
|
|
338
|
-
* no regex, built-in or user-supplied, runs over a URL. Every other
|
|
339
|
-
* value and every name is kept, because they are part of identity too.
|
|
340
|
-
* An earlier version of this method scanned every value (the inline
|
|
341
|
-
* comment below records what that did to the key); this comment said
|
|
342
|
-
* so and outlived the fix.
|
|
343
|
-
*/
|
|
344
|
-
maskUrl(rawUrl) {
|
|
345
|
-
if (!rawUrl) return rawUrl;
|
|
346
|
-
const hashAt = rawUrl.indexOf("#");
|
|
347
|
-
const withoutHash = hashAt === -1 ? rawUrl : rawUrl.slice(0, hashAt);
|
|
348
|
-
const qAt = withoutHash.indexOf("?");
|
|
349
|
-
if (qAt === -1) return withoutHash;
|
|
350
|
-
const head = withoutHash.slice(0, qAt);
|
|
351
|
-
const query = withoutHash.slice(qAt + 1);
|
|
352
|
-
const parts = query.split("&").map((pair) => {
|
|
353
|
-
if (pair === "") return pair;
|
|
354
|
-
const eq = pair.indexOf("=");
|
|
355
|
-
if (eq === -1) return pair;
|
|
356
|
-
const name = pair.slice(0, eq);
|
|
357
|
-
if (isSensitiveParam(name)) return `${name}=[REDACTED]`;
|
|
358
|
-
return pair;
|
|
359
|
-
});
|
|
360
|
-
return `${head}?${parts.join("&")}`;
|
|
361
|
-
}
|
|
362
|
-
/* -------------------------------------------------------------- */
|
|
363
|
-
/* Network data masking */
|
|
364
|
-
/* -------------------------------------------------------------- */
|
|
365
|
-
/**
|
|
366
|
-
* Returns a deep-copy of the given {@link NetworkEvent} with sensitive
|
|
367
|
-
* headers redacted and (optionally) bodies masked.
|
|
368
|
-
*/
|
|
369
|
-
maskNetworkData(event) {
|
|
370
|
-
const masked = { ...event };
|
|
371
|
-
masked.requestHeaders = this.maskHeaders(event.requestHeaders);
|
|
372
|
-
masked.responseHeaders = this.maskHeaders(event.responseHeaders);
|
|
373
|
-
if (this.config.maskNetworkBodies) {
|
|
374
|
-
masked.requestBody = event.requestBody ? "[MASKED]" : null;
|
|
375
|
-
masked.responseBody = event.responseBody ? "[MASKED]" : null;
|
|
376
|
-
} else {
|
|
377
|
-
const reqCt = findContentType(event.requestHeaders);
|
|
378
|
-
const resCt = findContentType(event.responseHeaders);
|
|
379
|
-
masked.requestBody = redactBody(
|
|
380
|
-
event.requestBody,
|
|
381
|
-
reqCt,
|
|
382
|
-
this.userPatterns
|
|
383
|
-
);
|
|
384
|
-
masked.responseBody = redactBody(
|
|
385
|
-
event.responseBody,
|
|
386
|
-
resCt,
|
|
387
|
-
this.userPatterns
|
|
388
|
-
);
|
|
389
|
-
}
|
|
390
|
-
masked.url = this.maskUrl(event.url);
|
|
391
|
-
return masked;
|
|
392
|
-
}
|
|
393
|
-
/* -------------------------------------------------------------- */
|
|
394
|
-
/* Config accessors */
|
|
395
|
-
/* -------------------------------------------------------------- */
|
|
396
|
-
getConfig() {
|
|
397
|
-
return this.config;
|
|
398
|
-
}
|
|
399
|
-
updateConfig(partial) {
|
|
400
|
-
this.config = mergePrivacyConfig(this.config, partial);
|
|
401
|
-
this.userPatterns = compileGlobal(this.config.piiPatterns);
|
|
402
|
-
}
|
|
403
|
-
/* -------------------------------------------------------------- */
|
|
404
|
-
/* Internals */
|
|
405
|
-
/* -------------------------------------------------------------- */
|
|
406
|
-
maskHeaders(headers) {
|
|
407
|
-
const result = {};
|
|
408
|
-
const sensitiveSet = new Set(
|
|
409
|
-
this.config.sensitiveHeaders.map((h) => h.toLowerCase())
|
|
410
|
-
);
|
|
411
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
412
|
-
if (sensitiveSet.has(key.toLowerCase())) {
|
|
413
|
-
result[key] = "[REDACTED]";
|
|
414
|
-
} else {
|
|
415
|
-
result[key] = this.maskText(value);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
return result;
|
|
419
|
-
}
|
|
420
|
-
};
|
|
421
|
-
|
|
422
|
-
// src/network.ts
|
|
423
|
-
function absolute(url) {
|
|
424
|
-
try {
|
|
425
|
-
const base = typeof document !== "undefined" ? document.baseURI : void 0;
|
|
426
|
-
return new URL(url, base).href;
|
|
427
|
-
} catch {
|
|
428
|
-
return url;
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
function headersToRecord(headers) {
|
|
432
|
-
const result = {};
|
|
433
|
-
if (!headers) return result;
|
|
434
|
-
if (headers instanceof Headers) {
|
|
435
|
-
headers.forEach((value, key) => {
|
|
436
|
-
result[key] = value;
|
|
437
|
-
});
|
|
438
|
-
} else if (Array.isArray(headers)) {
|
|
439
|
-
for (const [key, value] of headers) {
|
|
440
|
-
result[key] = value;
|
|
441
|
-
}
|
|
442
|
-
} else {
|
|
443
|
-
Object.assign(result, headers);
|
|
444
|
-
}
|
|
445
|
-
return result;
|
|
446
|
-
}
|
|
447
|
-
var TRUNCATED_SUFFIX = "...[truncated]";
|
|
448
|
-
function truncate(text, maxSize) {
|
|
449
|
-
return text.length > maxSize ? text.slice(0, maxSize) + TRUNCATED_SUFFIX : text;
|
|
450
|
-
}
|
|
451
|
-
function formDataText(body) {
|
|
452
|
-
const parts = [];
|
|
453
|
-
body.forEach((value, key) => {
|
|
454
|
-
parts.push(
|
|
455
|
-
typeof value === "string" ? `${key}=${value}` : `${key}=[File: ${value.name}, ${value.size} bytes]`
|
|
456
|
-
);
|
|
457
|
-
});
|
|
458
|
-
return parts.join("&");
|
|
459
|
-
}
|
|
460
|
-
function serializeXhrBody(body, maxSize) {
|
|
461
|
-
if (body == null) return null;
|
|
462
|
-
if (typeof body === "string") return truncate(body, maxSize);
|
|
463
|
-
if (body instanceof FormData) return truncate(formDataText(body), maxSize);
|
|
464
|
-
if (body instanceof URLSearchParams)
|
|
465
|
-
return truncate(body.toString(), maxSize);
|
|
466
|
-
if (typeof Blob !== "undefined" && body instanceof Blob)
|
|
467
|
-
return `[Blob: ${body.size} bytes]`;
|
|
468
|
-
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
469
|
-
return binaryBody(body, maxSize);
|
|
470
|
-
if (typeof Document !== "undefined" && body instanceof Document) {
|
|
471
|
-
try {
|
|
472
|
-
return truncate(new XMLSerializer().serializeToString(body), maxSize);
|
|
473
|
-
} catch {
|
|
474
|
-
return "[Unreadable body]";
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
return "[Unreadable body]";
|
|
478
|
-
}
|
|
479
|
-
function binaryBody(body, maxSize) {
|
|
480
|
-
const bytes = body instanceof ArrayBuffer ? new Uint8Array(body) : new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
481
|
-
if (bytes.byteLength > maxSize) return `[Binary: ${bytes.byteLength} bytes]`;
|
|
482
|
-
try {
|
|
483
|
-
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
484
|
-
} catch {
|
|
485
|
-
return `[Binary: ${bytes.byteLength} bytes]`;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
async function serializeBody(body, maxSize) {
|
|
489
|
-
if (body == null) return null;
|
|
490
|
-
try {
|
|
491
|
-
if (typeof body === "string") return truncate(body, maxSize);
|
|
492
|
-
if (body instanceof URLSearchParams)
|
|
493
|
-
return truncate(body.toString(), maxSize);
|
|
494
|
-
if (body instanceof FormData) return truncate(formDataText(body), maxSize);
|
|
495
|
-
if (body instanceof Blob) {
|
|
496
|
-
if (body.size > maxSize) return `[Blob: ${body.size} bytes, truncated]`;
|
|
497
|
-
const text = await body.text();
|
|
498
|
-
return text;
|
|
499
|
-
}
|
|
500
|
-
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
501
|
-
return binaryBody(body, maxSize);
|
|
502
|
-
return "[ReadableStream]";
|
|
503
|
-
} catch {
|
|
504
|
-
return "[Unreadable body]";
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
async function readResponseBody(response, maxSize) {
|
|
508
|
-
try {
|
|
509
|
-
const clone = response.clone();
|
|
510
|
-
const contentLength = Number(clone.headers.get("content-length") ?? 0);
|
|
511
|
-
if (contentLength > maxSize) {
|
|
512
|
-
return `[Response body too large: ${contentLength} bytes]`;
|
|
513
|
-
}
|
|
514
|
-
return truncate(await clone.text(), maxSize);
|
|
515
|
-
} catch {
|
|
516
|
-
return null;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
function recordedUrl(raw) {
|
|
520
|
-
const base = typeof document !== "undefined" && document.baseURI ? document.baseURI : typeof location !== "undefined" ? location.href : void 0;
|
|
521
|
-
return new URL(raw, base).href;
|
|
522
|
-
}
|
|
523
|
-
var NetworkInterceptor = class {
|
|
524
|
-
callback = null;
|
|
525
|
-
privacyEngine;
|
|
526
|
-
maxBodySize;
|
|
527
|
-
/** Absolute URLs never observed — the SDK's own ingest endpoint. */
|
|
528
|
-
ignored;
|
|
529
|
-
active = false;
|
|
530
|
-
// Store originals so we can restore them on stop().
|
|
531
|
-
originalFetch = null;
|
|
532
|
-
originalXhrOpen = null;
|
|
533
|
-
originalXhrSend = null;
|
|
534
|
-
originalXhrSetHeader = null;
|
|
535
|
-
constructor(privacyConfig = {}, maxBodySize = 524288, ignoreUrls = []) {
|
|
536
|
-
this.privacyEngine = new PrivacyEngine(privacyConfig);
|
|
537
|
-
this.maxBodySize = maxBodySize;
|
|
538
|
-
this.ignored = new Set(ignoreUrls.map(absolute));
|
|
539
|
-
}
|
|
540
|
-
/** True for a request the interceptor must pass through untouched. */
|
|
541
|
-
ignores(url) {
|
|
542
|
-
return this.ignored.size > 0 && this.ignored.has(absolute(url));
|
|
543
|
-
}
|
|
544
|
-
/* -------------------------------------------------------------- */
|
|
545
|
-
/* Lifecycle */
|
|
546
|
-
/* -------------------------------------------------------------- */
|
|
547
|
-
start(callback) {
|
|
548
|
-
if (this.active) return;
|
|
549
|
-
this.active = true;
|
|
550
|
-
this.callback = callback;
|
|
551
|
-
this.patchFetch();
|
|
552
|
-
this.patchXHR();
|
|
553
|
-
}
|
|
554
|
-
stop() {
|
|
555
|
-
if (!this.active) return;
|
|
556
|
-
this.active = false;
|
|
557
|
-
this.callback = null;
|
|
558
|
-
this.restoreFetch();
|
|
559
|
-
this.restoreXHR();
|
|
560
|
-
}
|
|
561
|
-
/* -------------------------------------------------------------- */
|
|
562
|
-
/* Fetch patching */
|
|
563
|
-
/* -------------------------------------------------------------- */
|
|
564
|
-
patchFetch() {
|
|
565
|
-
if (typeof globalThis.fetch !== "function") return;
|
|
566
|
-
const originalFetch = globalThis.fetch;
|
|
567
|
-
this.originalFetch = originalFetch;
|
|
568
|
-
const patchedFetch = async (input, init) => {
|
|
569
|
-
const request = new Request(input, init);
|
|
570
|
-
if (this.ignores(request.url)) {
|
|
571
|
-
return originalFetch.call(globalThis, input, init);
|
|
572
|
-
}
|
|
573
|
-
const startTime = performance.now();
|
|
574
|
-
const method = request.method;
|
|
575
|
-
const url = recordedUrl(request.url);
|
|
576
|
-
const requestHeaders = headersToRecord(request.headers);
|
|
577
|
-
let requestBody = null;
|
|
578
|
-
if (init?.body != null) {
|
|
579
|
-
requestBody = await serializeBody(init.body, this.maxBodySize);
|
|
580
|
-
} else if (request.body) {
|
|
581
|
-
try {
|
|
582
|
-
const clone = request.clone();
|
|
583
|
-
requestBody = truncate(await clone.text(), this.maxBodySize);
|
|
584
|
-
} catch {
|
|
585
|
-
requestBody = null;
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
let response;
|
|
589
|
-
try {
|
|
590
|
-
response = await originalFetch.call(globalThis, input, init);
|
|
591
|
-
} catch (err) {
|
|
592
|
-
const duration2 = performance.now() - startTime;
|
|
593
|
-
this.emit({
|
|
594
|
-
method,
|
|
595
|
-
url,
|
|
596
|
-
requestHeaders,
|
|
597
|
-
requestBody,
|
|
598
|
-
responseHeaders: {},
|
|
599
|
-
responseBody: null,
|
|
600
|
-
statusCode: 0,
|
|
601
|
-
duration: duration2,
|
|
602
|
-
type: "fetch"
|
|
603
|
-
});
|
|
604
|
-
throw err;
|
|
605
|
-
}
|
|
606
|
-
const duration = performance.now() - startTime;
|
|
607
|
-
const responseHeaders = headersToRecord(response.headers);
|
|
608
|
-
const responseBody = await readResponseBody(response, this.maxBodySize);
|
|
609
|
-
this.emit({
|
|
610
|
-
method,
|
|
611
|
-
url,
|
|
612
|
-
requestHeaders,
|
|
613
|
-
requestBody,
|
|
614
|
-
responseHeaders,
|
|
615
|
-
responseBody,
|
|
616
|
-
statusCode: response.status,
|
|
617
|
-
duration,
|
|
618
|
-
type: "fetch"
|
|
619
|
-
});
|
|
620
|
-
return response;
|
|
621
|
-
};
|
|
622
|
-
globalThis.fetch = patchedFetch;
|
|
623
|
-
}
|
|
624
|
-
restoreFetch() {
|
|
625
|
-
if (this.originalFetch) {
|
|
626
|
-
globalThis.fetch = this.originalFetch;
|
|
627
|
-
this.originalFetch = null;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
/* -------------------------------------------------------------- */
|
|
631
|
-
/* XMLHttpRequest patching */
|
|
632
|
-
/* -------------------------------------------------------------- */
|
|
633
|
-
patchXHR() {
|
|
634
|
-
if (typeof XMLHttpRequest === "undefined") return;
|
|
635
|
-
const originalOpen = XMLHttpRequest.prototype.open;
|
|
636
|
-
const originalSend = XMLHttpRequest.prototype.send;
|
|
637
|
-
this.originalXhrOpen = originalOpen;
|
|
638
|
-
this.originalXhrSend = originalSend;
|
|
639
|
-
const maxBodySize = this.maxBodySize;
|
|
640
|
-
const isActive = () => this.active;
|
|
641
|
-
const emit = (event) => this.emit(event);
|
|
642
|
-
const ignores = (u) => this.ignores(u);
|
|
643
|
-
const meta = /* @__PURE__ */ new WeakMap();
|
|
644
|
-
const origSetHeader = XMLHttpRequest.prototype.setRequestHeader;
|
|
645
|
-
this.originalXhrSetHeader = origSetHeader;
|
|
646
|
-
XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
|
|
647
|
-
const m = meta.get(this);
|
|
648
|
-
if (m) {
|
|
649
|
-
m.requestHeaders[name] = value;
|
|
650
|
-
}
|
|
651
|
-
return origSetHeader.call(this, name, value);
|
|
652
|
-
};
|
|
653
|
-
const forwardOpen = originalOpen;
|
|
654
|
-
XMLHttpRequest.prototype.open = function(method, url, ...rest) {
|
|
655
|
-
const href = typeof url === "string" ? url : url.toString();
|
|
656
|
-
const result = forwardOpen.call(this, method, url, ...rest);
|
|
657
|
-
if (!ignores(href)) {
|
|
658
|
-
meta.set(this, {
|
|
659
|
-
method,
|
|
660
|
-
// RESOLVED, not the raw string the app typed. See recordedUrl.
|
|
661
|
-
url: recordedUrl(href),
|
|
662
|
-
requestHeaders: {},
|
|
663
|
-
startTime: 0
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
|
-
return result;
|
|
667
|
-
};
|
|
668
|
-
XMLHttpRequest.prototype.send = function(body) {
|
|
669
|
-
const m = meta.get(this);
|
|
670
|
-
if (m) {
|
|
671
|
-
m.startTime = performance.now();
|
|
672
|
-
}
|
|
673
|
-
const onFinish = () => {
|
|
674
|
-
if (!m || !isActive()) return;
|
|
675
|
-
const duration = performance.now() - m.startTime;
|
|
676
|
-
const rawHeaders = this.getAllResponseHeaders();
|
|
677
|
-
const responseHeaders = {};
|
|
678
|
-
if (rawHeaders) {
|
|
679
|
-
for (const line of rawHeaders.trim().split(/[\r\n]+/)) {
|
|
680
|
-
const idx = line.indexOf(": ");
|
|
681
|
-
if (idx > 0) {
|
|
682
|
-
responseHeaders[line.slice(0, idx)] = line.slice(idx + 2);
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
let responseBody = null;
|
|
687
|
-
try {
|
|
688
|
-
if (typeof this.responseText === "string") {
|
|
689
|
-
responseBody = truncate(this.responseText, maxBodySize);
|
|
690
|
-
}
|
|
691
|
-
} catch {
|
|
692
|
-
responseBody = `[${this.responseType} response]`;
|
|
693
|
-
}
|
|
694
|
-
const requestBody = serializeXhrBody(body, maxBodySize);
|
|
695
|
-
emit({
|
|
696
|
-
method: m.method,
|
|
697
|
-
url: m.url,
|
|
698
|
-
requestHeaders: m.requestHeaders,
|
|
699
|
-
requestBody,
|
|
700
|
-
responseHeaders,
|
|
701
|
-
responseBody,
|
|
702
|
-
statusCode: this.status,
|
|
703
|
-
duration,
|
|
704
|
-
type: "xhr"
|
|
705
|
-
});
|
|
706
|
-
};
|
|
707
|
-
this.addEventListener("loadend", onFinish, { once: true });
|
|
708
|
-
return originalSend.call(this, body);
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
restoreXHR() {
|
|
712
|
-
if (typeof XMLHttpRequest === "undefined") return;
|
|
713
|
-
if (this.originalXhrOpen) {
|
|
714
|
-
XMLHttpRequest.prototype.open = this.originalXhrOpen;
|
|
715
|
-
this.originalXhrOpen = null;
|
|
716
|
-
}
|
|
717
|
-
if (this.originalXhrSend) {
|
|
718
|
-
XMLHttpRequest.prototype.send = this.originalXhrSend;
|
|
719
|
-
this.originalXhrSend = null;
|
|
720
|
-
}
|
|
721
|
-
if (this.originalXhrSetHeader) {
|
|
722
|
-
XMLHttpRequest.prototype.setRequestHeader = this.originalXhrSetHeader;
|
|
723
|
-
this.originalXhrSetHeader = null;
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
/* -------------------------------------------------------------- */
|
|
727
|
-
/* Internal */
|
|
728
|
-
/* -------------------------------------------------------------- */
|
|
729
|
-
emit(raw) {
|
|
730
|
-
if (!this.callback) return;
|
|
731
|
-
try {
|
|
732
|
-
const masked = this.privacyEngine.maskNetworkData(raw);
|
|
733
|
-
this.callback(masked);
|
|
734
|
-
} catch {
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
};
|
|
738
|
-
|
|
739
|
-
// src/session-id.ts
|
|
740
|
-
var SESSION_ID_MAX_LENGTH = 200;
|
|
741
|
-
var SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
|
|
742
|
-
var SESSION_ID_RULE = `must be 1-${SESSION_ID_MAX_LENGTH} characters of letters, digits, dot, dash and underscore, with no empty dot-separated segment`;
|
|
743
|
-
function isValidSessionId(value) {
|
|
744
|
-
return typeof value === "string" && value.length > 0 && value.length <= SESSION_ID_MAX_LENGTH && SESSION_ID_PATTERN.test(value);
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
// src/errors.ts
|
|
748
|
-
var SERVER_EVIDENCE = [
|
|
749
|
-
"status",
|
|
750
|
-
"serverMessage",
|
|
751
|
-
"endpoint",
|
|
752
|
-
"sessionId"
|
|
753
|
-
];
|
|
754
|
-
var SERVER_OPTIONAL_EVIDENCE = ["issues"];
|
|
755
|
-
var SDK_ERRORS = {
|
|
756
|
-
KUI_E_INGEST_KEY_REJECTED: {
|
|
757
|
-
summary: "The ingest server refused the SDK's API key (401 or 403), so no events from this page can be stored. Capture has stopped.",
|
|
758
|
-
remedy: {
|
|
759
|
-
command: null,
|
|
760
|
-
manual: "The key is missing, unknown, expired, revoked, or not a UI INGEST key (a personal access token is refused with 403 however it is scoped). Mint a UI ingest key for this app with the api-server GraphQL mutation `createUIIngestKey(appId, name, ttlDays)`, authenticated as a member of the app's organisation, and pass the returned token as `apiKey` to KeployCapture.init(). No CLI verb mints one yet; a new key takes effect on the next page load."
|
|
761
|
-
},
|
|
762
|
-
evidence: SERVER_EVIDENCE,
|
|
763
|
-
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
764
|
-
},
|
|
765
|
-
KUI_E_INGEST_ENDPOINT_NOT_FOUND: {
|
|
766
|
-
summary: "The ingest server answered 404 or 405: nothing at `endpoint` accepts a POST, so no events from this page can be stored. Capture has stopped.",
|
|
767
|
-
remedy: {
|
|
768
|
-
command: null,
|
|
769
|
-
manual: "`endpoint` is wrong, not the key. The documented ingest route is `<api-server>/ui/v1/ingest` (the SDK never calls anything else). A 404 or 405 the SDK can read comes from a path typo under `/ui/v1/` or from a same-origin proxy that does not forward the route. Fix the `endpoint` passed to KeployCapture.init() and reload. If the endpoint is on another origin and its path is outside `/ui/v1/` (or the api-server has no UI ingest route), the browser refuses the CORS preflight instead and no status reaches the SDK: it retries as a network error and this code is never raised, so check the endpoint before trusting silence."
|
|
770
|
-
},
|
|
771
|
-
evidence: SERVER_EVIDENCE,
|
|
772
|
-
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
773
|
-
},
|
|
774
|
-
KUI_E_SESSION_CONFLICT: {
|
|
775
|
-
summary: "The ingest server answered 409: this session id is already claimed by a completed session or a different capture, or a batchId was re-used with different events. Capture has stopped.",
|
|
776
|
-
remedy: {
|
|
777
|
-
command: null,
|
|
778
|
-
manual: "Give each run its own session id. The usual cause is a `sessionIdGenerator` that returns a fixed value, so a second run of the same scenario posts into the first run's session; a session completed from the dashboard while the page was still recording answers the same way. Remove the override or make it return a fresh id per page load. Events already stored under this session are intact."
|
|
779
|
-
},
|
|
780
|
-
evidence: SERVER_EVIDENCE,
|
|
781
|
-
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
782
|
-
},
|
|
783
|
-
KUI_E_INGEST_REJECTED: {
|
|
784
|
-
summary: "The ingest server refused a batch with a terminal 4xx it will keep refusing: the body is malformed (400), its encoding is unsupported (415), or it is over a size limit (413). Capture has stopped.",
|
|
785
|
-
remedy: {
|
|
786
|
-
command: null,
|
|
787
|
-
manual: "Read `serverMessage`, which is the server's own sentence. 413 is one of two things the server does not tell apart by status: `ui session has reached its size limit` means this session is complete -- call KeployCapture.stop() and then init() for a new one; a sentence containing `request body exceeds` (`request body exceeds N bytes` on the wire size, `decoded request body exceeds N bytes` after gzip) means the server's body cap is lower than the 10 MiB this SDK forms every batch under, an SDK/server version mismatch. 400 and 415 are the same mismatch: the SDK builds every byte it sends, checks the session id (the one integrator-supplied value) against the server's rule before sending, clamps `batchSize` to the 5000-event cap it knows and cuts every batch at the 10 MiB decoded cap, so a 4xx of this kind means the server's rules are newer than this SDK's; `evidence.issues` names the field the server refused. Upgrade @keploy/capture-sdk to the version the server documents."
|
|
788
|
-
},
|
|
789
|
-
evidence: SERVER_EVIDENCE,
|
|
790
|
-
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
791
|
-
},
|
|
792
|
-
KUI_E_SESSION_ID_INVALID: {
|
|
793
|
-
summary: "The configured `sessionIdGenerator` did not produce a session id the ingest server would accept -- it returned a string outside the rule, returned a non-string, or threw -- so capture did not start and nothing was sent.",
|
|
794
|
-
remedy: {
|
|
795
|
-
command: null,
|
|
796
|
-
manual: "`evidence.received` says what the generator produced (`string <value>`, `number 42`, `object Map {}`, `a Promise (sessionIdGenerator must return a string synchronously)`, or `threw <error>`), `evidence.sessionId` is the string it returned or null when it returned no string, and `evidence.rule` is the server's rule for one: a session id must be 1-200 characters of letters, digits, dot, dash and underscore, with no empty dot-separated segment. Make `sessionIdGenerator` return a string inside that rule (encode a `user:42/session 1`-style correlation id, e.g. base64url it) and not throw, or remove the override and let the SDK mint a UUID. The check runs before the first byte is sent, so the fix takes effect on the next init()."
|
|
797
|
-
},
|
|
798
|
-
evidence: ["sessionId", "received", "rule"],
|
|
799
|
-
optionalEvidence: []
|
|
800
|
-
}
|
|
801
|
-
};
|
|
802
|
-
var SDK_WARNINGS = {
|
|
803
|
-
KUI_E_EVENT_UNSERIALISABLE: {
|
|
804
|
-
summary: "The SDK dropped one captured event because it could not be serialised to JSON (a cycle, a BigInt, a getter that throws). The capture continues without it.",
|
|
805
|
-
remedy: {
|
|
806
|
-
command: null,
|
|
807
|
-
manual: "`evidence.eventId` and `evidence.eventType` say which event and `evidence.reason` is the message of the error JSON.stringify threw (its own for a cycle or a BigInt; a getter's or toJSON's own when one throws). A `custom` event comes from integrator code (KeployCaptureRecorder.emitEvent): make its payload plain JSON (no cycles, no BigInt, no throwing getters). Any other type is the SDK's own serialisation and a defect to report. The SDK says this once per capture -- the first such event after each init(); later unserialisable events in that capture are dropped silently."
|
|
808
|
-
},
|
|
809
|
-
evidence: ["eventId", "eventType", "reason"],
|
|
810
|
-
optionalEvidence: []
|
|
811
|
-
},
|
|
812
|
-
KUI_E_EVENT_OVERSIZED: {
|
|
813
|
-
summary: "The SDK dropped one captured event because, alone in a request body, it is over the ingest server's decoded cap (`evidence.cap` bytes); no batch could carry it. The capture continues without it.",
|
|
814
|
-
remedy: {
|
|
815
|
-
command: null,
|
|
816
|
-
manual: "`evidence.bytes` is the size of a request body carrying only this event (its JSON plus the batch envelope) and `evidence.cap` the server's limit on one body. A `dom` event this large is an rrweb FullSnapshot of a very large page, and without it later events in the recording name nodes the recording never showed: leave the heaviest subtrees out of the snapshot with `privacy.blockSelectors`; a `network` event this large is a captured body under a raised `maxBodySize` -- lower it in KeployCapture.init() so bodies are truncated before capture. The SDK says this once per capture -- the first such event after each init(); later oversized events in that capture are dropped silently."
|
|
817
|
-
},
|
|
818
|
-
evidence: ["eventId", "eventType", "bytes", "cap"],
|
|
819
|
-
optionalEvidence: []
|
|
820
|
-
}
|
|
821
|
-
};
|
|
822
|
-
function oneLine(text) {
|
|
823
|
-
return text.replace(/\s+/g, " ").trim();
|
|
824
|
-
}
|
|
825
|
-
function warningLine(evidence, prose) {
|
|
826
|
-
const { code, ...fields } = evidence;
|
|
827
|
-
return `[keploy] ${code}: dropped an event: ${oneLine(prose)} The capture continues; any further such events in this capture are dropped silently. evidence=${evidenceJson(fields)}`;
|
|
828
|
-
}
|
|
829
|
-
function evidenceJson(fields) {
|
|
830
|
-
try {
|
|
831
|
-
return JSON.stringify(fields);
|
|
832
|
-
} catch {
|
|
833
|
-
const rendered = {};
|
|
834
|
-
for (const [key, value] of Object.entries(fields)) {
|
|
835
|
-
rendered[key] = typeof value === "string" || typeof value === "number" ? value : describeValue(value);
|
|
836
|
-
}
|
|
837
|
-
return JSON.stringify(rendered);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
function codeForStatus(status) {
|
|
841
|
-
if (status === 401 || status === 403) return "KUI_E_INGEST_KEY_REJECTED";
|
|
842
|
-
if (status === 404 || status === 405) {
|
|
843
|
-
return "KUI_E_INGEST_ENDPOINT_NOT_FOUND";
|
|
844
|
-
}
|
|
845
|
-
if (status === 409) return "KUI_E_SESSION_CONFLICT";
|
|
846
|
-
if (status >= 400 && status < 500 && status !== 429) {
|
|
847
|
-
return "KUI_E_INGEST_REJECTED";
|
|
848
|
-
}
|
|
849
|
-
return null;
|
|
850
|
-
}
|
|
851
|
-
var NO_SERVER_ERROR = { message: null, issues: null };
|
|
852
|
-
var SERVER_TEXT_LIMIT = 500;
|
|
853
|
-
function parseServerError(body) {
|
|
854
|
-
if (body === null) return NO_SERVER_ERROR;
|
|
855
|
-
const text = body.trim();
|
|
856
|
-
if (text === "") return NO_SERVER_ERROR;
|
|
857
|
-
try {
|
|
858
|
-
const parsed = JSON.parse(text);
|
|
859
|
-
if (parsed !== null && typeof parsed === "object") {
|
|
860
|
-
const shaped = parsed;
|
|
861
|
-
if (typeof shaped.error === "string") {
|
|
862
|
-
const sentence = shaped.error.trim();
|
|
863
|
-
return {
|
|
864
|
-
message: sentence === "" ? null : sentence.slice(0, SERVER_TEXT_LIMIT),
|
|
865
|
-
issues: issuesOf(shaped.issues)
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
} catch {
|
|
870
|
-
}
|
|
871
|
-
return { message: text.slice(0, SERVER_TEXT_LIMIT), issues: null };
|
|
872
|
-
}
|
|
873
|
-
var ISSUES_LIMIT = 100;
|
|
874
|
-
function issuesOf(raw) {
|
|
875
|
-
if (!Array.isArray(raw)) return null;
|
|
876
|
-
const out = [];
|
|
877
|
-
for (const item of raw) {
|
|
878
|
-
if (out.length === ISSUES_LIMIT) break;
|
|
879
|
-
if (item === null || typeof item !== "object") continue;
|
|
880
|
-
const { path, message } = item;
|
|
881
|
-
if (typeof path !== "string" || typeof message !== "string") continue;
|
|
882
|
-
out.push({
|
|
883
|
-
path: path.slice(0, SERVER_TEXT_LIMIT),
|
|
884
|
-
message: message.slice(0, SERVER_TEXT_LIMIT)
|
|
885
|
-
});
|
|
886
|
-
}
|
|
887
|
-
return out.length > 0 ? out : null;
|
|
888
|
-
}
|
|
889
|
-
function describeValue(value) {
|
|
890
|
-
if (typeof value === "string") return value;
|
|
891
|
-
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
892
|
-
if (typeof value === "function") return `[function ${value.name}]`;
|
|
893
|
-
if (typeof value !== "object" || value === null) return String(value);
|
|
894
|
-
try {
|
|
895
|
-
return JSON.stringify(value);
|
|
896
|
-
} catch {
|
|
897
|
-
const ctor = value.constructor;
|
|
898
|
-
const name = typeof ctor?.name === "string" ? ctor.name : "object";
|
|
899
|
-
return `[${name} not JSON-serialisable]`;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
var ISSUES_IN_PROSE = 5;
|
|
903
|
-
var CaptureError = class extends Error {
|
|
904
|
-
code;
|
|
905
|
-
/** The HTTP status that produced this, or null for a code raised before anything was sent. */
|
|
906
|
-
status;
|
|
907
|
-
/** The server's own sentence (the `error` field of its body, or the body's text), or null when there was none. */
|
|
908
|
-
serverMessage;
|
|
909
|
-
/** The server's `issues[]` -- which fields it refused -- or null when its body carried none. */
|
|
910
|
-
issues;
|
|
911
|
-
remedy;
|
|
912
|
-
evidence;
|
|
913
|
-
constructor(code, message, status, server, evidence) {
|
|
914
|
-
super(message);
|
|
915
|
-
this.name = "CaptureError";
|
|
916
|
-
this.code = code;
|
|
917
|
-
this.remedy = SDK_ERRORS[code].remedy;
|
|
918
|
-
this.status = status;
|
|
919
|
-
this.serverMessage = server.message;
|
|
920
|
-
this.issues = server.issues;
|
|
921
|
-
this.evidence = evidence;
|
|
922
|
-
}
|
|
923
|
-
};
|
|
924
|
-
var IngestRejection = class extends CaptureError {
|
|
925
|
-
constructor(init) {
|
|
926
|
-
const { message, issues } = init.server;
|
|
927
|
-
let text = `[keploy] capture stopped: the server rejected this batch with ${init.status} and will reject the rest, so capture has stopped (${init.code}). ${message === null ? "(no response body)" : message}`;
|
|
928
|
-
if (issues !== null) {
|
|
929
|
-
const named = issues.slice(0, ISSUES_IN_PROSE).map((i) => `${i.path === "" ? "body" : i.path}: ${i.message}`).join("; ");
|
|
930
|
-
const more = issues.length - ISSUES_IN_PROSE;
|
|
931
|
-
text += ` -- ${named}${more > 0 ? ` (+${more} more)` : ""}`;
|
|
932
|
-
}
|
|
933
|
-
super(init.code, text, init.status, init.server, {
|
|
934
|
-
status: init.status,
|
|
935
|
-
serverMessage: message,
|
|
936
|
-
endpoint: init.endpoint,
|
|
937
|
-
sessionId: init.sessionId,
|
|
938
|
-
...issues !== null ? { issues } : {}
|
|
939
|
-
});
|
|
940
|
-
}
|
|
941
|
-
};
|
|
942
|
-
var SessionIdRefusal = class extends CaptureError {
|
|
943
|
-
constructor(init) {
|
|
944
|
-
const what = init.sessionId !== null ? `returned ${JSON.stringify(init.sessionId)}, which the ingest server would refuse` : init.received.startsWith("threw ") ? init.received : `returned ${init.received}, which is not a session id`;
|
|
945
|
-
super(
|
|
946
|
-
"KUI_E_SESSION_ID_INVALID",
|
|
947
|
-
`[keploy] capture did not start: sessionIdGenerator ${what} (KUI_E_SESSION_ID_INVALID). A session id ${SESSION_ID_RULE}.`,
|
|
948
|
-
null,
|
|
949
|
-
NO_SERVER_ERROR,
|
|
950
|
-
{
|
|
951
|
-
sessionId: init.sessionId,
|
|
952
|
-
received: init.received,
|
|
953
|
-
rule: SESSION_ID_RULE
|
|
954
|
-
}
|
|
955
|
-
);
|
|
956
|
-
}
|
|
957
|
-
};
|
|
958
|
-
function describeReceived(outcome) {
|
|
959
|
-
if ("threw" in outcome) return `threw ${describeValue(outcome.threw)}`;
|
|
960
|
-
const value = outcome.returned;
|
|
961
|
-
if (typeof value === "object" && value !== null) {
|
|
962
|
-
if (typeof value.then === "function") {
|
|
963
|
-
return "a Promise (sessionIdGenerator must return a string synchronously)";
|
|
964
|
-
}
|
|
965
|
-
const ctor = value.constructor;
|
|
966
|
-
const name = typeof ctor?.name === "string" ? ctor.name : "";
|
|
967
|
-
if (name !== "" && name !== "Object") {
|
|
968
|
-
return `object ${name} ${describeValue(value)}`;
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
return `${typeof value} ${describeValue(value)}`;
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
// package.json
|
|
975
|
-
var version = "3.0.1";
|
|
976
|
-
|
|
977
|
-
// src/transport.ts
|
|
978
|
-
var SDK_NAME = "@keploy/capture-sdk";
|
|
979
|
-
var SDK_VERSION = version;
|
|
980
|
-
var MAX_RETRY_ATTEMPTS = 3;
|
|
981
|
-
var BASE_RETRY_DELAY_MS = 1e3;
|
|
982
|
-
var KEEPALIVE_QUOTA_BYTES = 65536;
|
|
983
|
-
function sleep(ms) {
|
|
984
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
985
|
-
}
|
|
986
|
-
function utf8Length(text) {
|
|
987
|
-
return new TextEncoder().encode(text).length;
|
|
988
|
-
}
|
|
989
|
-
async function compressPayload(data) {
|
|
990
|
-
if (typeof CompressionStream !== "undefined" && typeof Response !== "undefined") {
|
|
991
|
-
try {
|
|
992
|
-
const compressed = new Response(data).body.pipeThrough(
|
|
993
|
-
new CompressionStream("gzip")
|
|
994
|
-
);
|
|
995
|
-
const buf = await new Response(compressed).arrayBuffer();
|
|
996
|
-
const plain = utf8Length(data);
|
|
997
|
-
if (buf.byteLength < plain) {
|
|
998
|
-
return { body: buf, bytes: buf.byteLength, encoding: "gzip" };
|
|
999
|
-
}
|
|
1000
|
-
return { body: data, bytes: plain, encoding: null };
|
|
1001
|
-
} catch {
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
return { body: data, bytes: utf8Length(data), encoding: null };
|
|
1005
|
-
}
|
|
1006
|
-
var MAX_EVENTS_PER_BATCH = 5e3;
|
|
1007
|
-
var MAX_BATCH_BYTES = 10 * 1024 * 1024;
|
|
1008
|
-
var Transport = class {
|
|
1009
|
-
config;
|
|
1010
|
-
queue = [];
|
|
1011
|
-
/**
|
|
1012
|
-
* Flights that failed to send and must go out again AS THEY WERE.
|
|
1013
|
-
* Drained ahead of the event queue by run(). Never merged back into
|
|
1014
|
-
* `queue`: re-splicing a dispatched flight's events with newer ones
|
|
1015
|
-
* would put already-stored events under a new batchId, which is the
|
|
1016
|
-
* duplication the id exists to prevent -- and re-using the id over a
|
|
1017
|
-
* different event set is the 409 the server answers instead.
|
|
1018
|
-
*/
|
|
1019
|
-
retryQueue = [];
|
|
1020
|
-
/** Only used by the no-randomUUID fallback of mintBatchId(). */
|
|
1021
|
-
batchCounter = 0;
|
|
1022
|
-
flushTimer = null;
|
|
1023
|
-
/** The flush in progress, or null. One at a time: batches stay ordered. */
|
|
1024
|
-
current = null;
|
|
1025
|
-
sessionId = null;
|
|
1026
|
-
metadata = null;
|
|
1027
|
-
/*
|
|
1028
|
-
* The browser half of the offline backend join, or null when this
|
|
1029
|
-
* capture cannot be joined. Sent on EVERY batch rather than once at
|
|
1030
|
-
* session start: a batch is the only thing the server is guaranteed to
|
|
1031
|
-
* receive, and an identity that arrives only with the first one is
|
|
1032
|
-
* lost whenever that batch is the one that fails.
|
|
1033
|
-
*/
|
|
1034
|
-
captureIdentity = null;
|
|
1035
|
-
online = true;
|
|
1036
|
-
started = false;
|
|
1037
|
-
/** The stamp the next queued event gets; see enqueue(). */
|
|
1038
|
-
nextSeq = 1;
|
|
1039
|
-
/** Set by a drain request that arrived while a flush was running. */
|
|
1040
|
-
drainPending = false;
|
|
1041
|
-
/**
|
|
1042
|
-
* Set when an event over the keepalive quota was queued while the
|
|
1043
|
-
* browser said it was offline, so the online handler drains for it
|
|
1044
|
-
* instead of taking one batch. Cleared once the queue has run empty.
|
|
1045
|
-
*/
|
|
1046
|
-
rushDeferred = false;
|
|
1047
|
-
/*
|
|
1048
|
-
* Bytes of keepalive request bodies currently on the wire, so the
|
|
1049
|
-
* unload flush can size itself against what is LEFT of the quota
|
|
1050
|
-
* rather than the whole of it.
|
|
1051
|
-
*/
|
|
1052
|
-
inflightKeepaliveBytes = 0;
|
|
1053
|
-
/**
|
|
1054
|
-
* Bytes of a request carrying no events: the fixed cost every request
|
|
1055
|
-
* pays, so an event's own size can be measured against the quota.
|
|
1056
|
-
*/
|
|
1057
|
-
envelopeBytes = 0;
|
|
1058
|
-
/** Set by the first event JSON.stringify refused; see reportUnserialisable(). */
|
|
1059
|
-
reportedUnserialisable = false;
|
|
1060
|
-
reportedOversized = false;
|
|
1061
|
-
/**
|
|
1062
|
-
* Each queued event's JSON bytes, measured once at enqueue (the
|
|
1063
|
-
* keepalive rush needs the number there anyway) and read wherever a
|
|
1064
|
-
* cut is sized: the timed flight and the unload flush.
|
|
1065
|
-
*/
|
|
1066
|
-
bytesOf = /* @__PURE__ */ new WeakMap();
|
|
1067
|
-
/** The batch run() is working on, so the unload flush can take it back. */
|
|
1068
|
-
inFlight = null;
|
|
1069
|
-
constructor(config) {
|
|
1070
|
-
this.config = {
|
|
1071
|
-
...config,
|
|
1072
|
-
batchSize: Math.min(config.batchSize, MAX_EVENTS_PER_BATCH)
|
|
1073
|
-
};
|
|
1074
|
-
}
|
|
1075
|
-
/* -------------------------------------------------------------- */
|
|
1076
|
-
/* Lifecycle */
|
|
1077
|
-
/* -------------------------------------------------------------- */
|
|
1078
|
-
/**
|
|
1079
|
-
* Report a condition that ends the capture, and end it.
|
|
1080
|
-
*
|
|
1081
|
-
* NOT a throw: this runs inside a flush that nobody awaits, so a throw
|
|
1082
|
-
* becomes an unhandled rejection and is exactly as invisible as the
|
|
1083
|
-
* bare `return` it replaces. An integrator gets the callback; everyone
|
|
1084
|
-
* else gets a console error, which is the floor.
|
|
1085
|
-
*/
|
|
1086
|
-
fail(code, status, detail) {
|
|
1087
|
-
this.queue = [];
|
|
1088
|
-
this.retryQueue = [];
|
|
1089
|
-
const err = new IngestRejection({
|
|
1090
|
-
code,
|
|
1091
|
-
status,
|
|
1092
|
-
server: parseServerError(detail),
|
|
1093
|
-
endpoint: this.config.endpoint,
|
|
1094
|
-
sessionId: this.sessionId ?? null
|
|
1095
|
-
});
|
|
1096
|
-
console.error(err.message);
|
|
1097
|
-
void this.stop();
|
|
1098
|
-
try {
|
|
1099
|
-
this.config.onCaptureEnd?.();
|
|
1100
|
-
} catch {
|
|
1101
|
-
}
|
|
1102
|
-
try {
|
|
1103
|
-
this.config.onError?.(err);
|
|
1104
|
-
} catch {
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
start(sessionId, metadata, captureIdentity = null) {
|
|
1108
|
-
if (this.started) return;
|
|
1109
|
-
this.started = true;
|
|
1110
|
-
this.sessionId = sessionId;
|
|
1111
|
-
this.metadata = metadata;
|
|
1112
|
-
this.captureIdentity = captureIdentity;
|
|
1113
|
-
this.envelopeBytes = utf8Length(
|
|
1114
|
-
JSON.stringify(this.payload([], this.mintBatchId()))
|
|
1115
|
-
);
|
|
1116
|
-
this.flushTimer = setInterval(() => {
|
|
1117
|
-
void this.flush();
|
|
1118
|
-
}, this.config.batchInterval);
|
|
1119
|
-
if (typeof window !== "undefined") {
|
|
1120
|
-
window.addEventListener("online", this.handleOnline);
|
|
1121
|
-
window.addEventListener("offline", this.handleOffline);
|
|
1122
|
-
window.addEventListener("pagehide", this.handleUnload);
|
|
1123
|
-
window.addEventListener("beforeunload", this.handleUnload);
|
|
1124
|
-
document.addEventListener("visibilitychange", this.handleVisibility);
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
/**
|
|
1128
|
-
* Stop accepting events and send what is queued.
|
|
1129
|
-
*
|
|
1130
|
-
* Resolves when the final flush has settled — a caller that needs to
|
|
1131
|
-
* know the tail arrived (a test, an integrator about to navigate)
|
|
1132
|
-
* can await it; nothing requires it.
|
|
1133
|
-
*/
|
|
1134
|
-
stop() {
|
|
1135
|
-
if (!this.started) return this.current ?? Promise.resolve();
|
|
1136
|
-
this.started = false;
|
|
1137
|
-
if (this.flushTimer) {
|
|
1138
|
-
clearInterval(this.flushTimer);
|
|
1139
|
-
this.flushTimer = null;
|
|
1140
|
-
}
|
|
1141
|
-
const drained = this.flush(true);
|
|
1142
|
-
if (typeof window !== "undefined") {
|
|
1143
|
-
window.removeEventListener("online", this.handleOnline);
|
|
1144
|
-
window.removeEventListener("offline", this.handleOffline);
|
|
1145
|
-
void drained.finally(() => this.disarmWhenDrained());
|
|
1146
|
-
}
|
|
1147
|
-
return drained;
|
|
1148
|
-
}
|
|
1149
|
-
/**
|
|
1150
|
-
* Removes the unload and hidden-tab listeners once there is nothing
|
|
1151
|
-
* left for them to send: after stop(), the first time the queue is
|
|
1152
|
-
* empty. Called wherever the queue can become empty — the drain
|
|
1153
|
-
* stop() started, a later drain (a hidden tab, or fail() on a
|
|
1154
|
-
* terminal rejection), the unload flush itself — because a listener
|
|
1155
|
-
* kept past that point is a leak for the life of the document: a
|
|
1156
|
-
* drain that failed on logout kept them, and the hidden-tab drain
|
|
1157
|
-
* that later emptied the queue removed nothing, so the Transport was
|
|
1158
|
-
* retained by pagehide, beforeunload and visibilitychange for as
|
|
1159
|
-
* long as the document lived. Idempotent; a no-op while started or
|
|
1160
|
-
* while events remain.
|
|
1161
|
-
*/
|
|
1162
|
-
disarmWhenDrained() {
|
|
1163
|
-
if (this.started || this.pendingCount() > 0) return;
|
|
1164
|
-
if (typeof window === "undefined") return;
|
|
1165
|
-
window.removeEventListener("pagehide", this.handleUnload);
|
|
1166
|
-
window.removeEventListener("beforeunload", this.handleUnload);
|
|
1167
|
-
document.removeEventListener("visibilitychange", this.handleVisibility);
|
|
1168
|
-
}
|
|
1169
|
-
/* -------------------------------------------------------------- */
|
|
1170
|
-
/* Enqueue */
|
|
1171
|
-
/* -------------------------------------------------------------- */
|
|
1172
|
-
enqueue(event) {
|
|
1173
|
-
if (!this.started) return;
|
|
1174
|
-
event.seq = this.nextSeq++;
|
|
1175
|
-
let bytes;
|
|
1176
|
-
try {
|
|
1177
|
-
const own = utf8Length(JSON.stringify(event));
|
|
1178
|
-
this.bytesOf.set(event, own);
|
|
1179
|
-
bytes = this.envelopeBytes + own;
|
|
1180
|
-
} catch (err) {
|
|
1181
|
-
this.reportUnserialisable(event, err);
|
|
1182
|
-
return;
|
|
1183
|
-
}
|
|
1184
|
-
if (bytes > MAX_BATCH_BYTES) {
|
|
1185
|
-
this.reportOversized(event, bytes);
|
|
1186
|
-
return;
|
|
1187
|
-
}
|
|
1188
|
-
this.queue.push(event);
|
|
1189
|
-
while (this.queue.length > this.config.maxQueueSize) {
|
|
1190
|
-
this.queue.shift();
|
|
1191
|
-
}
|
|
1192
|
-
if (bytes > KEEPALIVE_QUOTA_BYTES) {
|
|
1193
|
-
if (this.online) void this.flush(true);
|
|
1194
|
-
else this.rushDeferred = true;
|
|
1195
|
-
} else if (this.queue.length >= this.config.batchSize) {
|
|
1196
|
-
void this.flush();
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
/**
|
|
1200
|
-
* Say that an event was dropped because it could not be serialised —
|
|
1201
|
-
* ONCE per transport, and the line says so.
|
|
1202
|
-
*
|
|
1203
|
-
* Not a throw: the caller is rrweb's emit callback or the
|
|
1204
|
-
* integrator's own code, and the SDK has no business ending their
|
|
1205
|
-
* turn. Not `onError` either: that one is reserved for a terminal
|
|
1206
|
-
* condition that ENDS the capture, and this one does not — the
|
|
1207
|
-
* session goes on without this event.
|
|
1208
|
-
*
|
|
1209
|
-
* Once, because a custom event emitted from a render or a timer would
|
|
1210
|
-
* otherwise write a console line every few milliseconds for the life
|
|
1211
|
-
* of the page: the SDK degrading the page it is there to record. The
|
|
1212
|
-
* first line carries the event's id and the reason, which is what a
|
|
1213
|
-
* developer needs to find the emitter; the rest would only repeat it.
|
|
1214
|
-
*/
|
|
1215
|
-
reportUnserialisable(event, err) {
|
|
1216
|
-
if (this.reportedUnserialisable) return;
|
|
1217
|
-
this.reportedUnserialisable = true;
|
|
1218
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
1219
|
-
console.error(
|
|
1220
|
-
warningLine(
|
|
1221
|
-
{
|
|
1222
|
-
code: "KUI_E_EVENT_UNSERIALISABLE",
|
|
1223
|
-
eventId: event.id,
|
|
1224
|
-
eventType: event.type,
|
|
1225
|
-
reason
|
|
1226
|
-
},
|
|
1227
|
-
// The reason rides in the evidence JSON only, escaped: repeated
|
|
1228
|
-
// here it would put V8's three-line cycle message, or an
|
|
1229
|
-
// "evidence=" of its own, into the prose. See warningLine.
|
|
1230
|
-
`it cannot be serialised to JSON.`
|
|
1231
|
-
)
|
|
1232
|
-
);
|
|
1233
|
-
}
|
|
1234
|
-
/**
|
|
1235
|
-
* Say that an event was dropped because, alone in a body, it is over
|
|
1236
|
-
* the server's decoded cap -- ONCE per transport, like
|
|
1237
|
-
* reportUnserialisable and for the same reasons: not a throw into the
|
|
1238
|
-
* emitter's turn, not `onError` (the capture goes on), and not a line
|
|
1239
|
-
* per event.
|
|
1240
|
-
*/
|
|
1241
|
-
reportOversized(event, bytes) {
|
|
1242
|
-
if (this.reportedOversized) return;
|
|
1243
|
-
this.reportedOversized = true;
|
|
1244
|
-
console.error(
|
|
1245
|
-
warningLine(
|
|
1246
|
-
{
|
|
1247
|
-
code: "KUI_E_EVENT_OVERSIZED",
|
|
1248
|
-
eventId: event.id,
|
|
1249
|
-
eventType: event.type,
|
|
1250
|
-
bytes,
|
|
1251
|
-
cap: MAX_BATCH_BYTES
|
|
1252
|
-
},
|
|
1253
|
-
`${bytes} bytes in a body, over the ingest server's ${MAX_BATCH_BYTES}-byte cap, so no batch could carry it.`
|
|
1254
|
-
)
|
|
1255
|
-
);
|
|
1256
|
-
}
|
|
1257
|
-
/** The request body for `events`, with everything a batch carries. */
|
|
1258
|
-
payload(events, batchId) {
|
|
1259
|
-
return {
|
|
1260
|
-
sessionId: this.sessionId,
|
|
1261
|
-
batchId,
|
|
1262
|
-
events,
|
|
1263
|
-
metadata: this.metadata,
|
|
1264
|
-
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
1265
|
-
captureIdentity: this.captureIdentity
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
/* -------------------------------------------------------------- */
|
|
1269
|
-
/* Flush */
|
|
1270
|
-
/* -------------------------------------------------------------- */
|
|
1271
|
-
/**
|
|
1272
|
-
* Send queued events.
|
|
1273
|
-
*
|
|
1274
|
-
* `drain` sends EVERYTHING queued — batch after batch, each one sized
|
|
1275
|
-
* like a timed batch, so the server's body limit is the same one a
|
|
1276
|
-
* timed batch faces — and if a flush is already running it is picked
|
|
1277
|
-
* up by that flush when its current batch finishes. A drain that
|
|
1278
|
-
* silently returned because a batch happened to be in flight would
|
|
1279
|
-
* leave a hidden tab holding events it may never get another chance
|
|
1280
|
-
* to send. A drain also ignores the `offline` flag: it is the last
|
|
1281
|
-
* attempt, the browser's offline signal is advisory, and a fetch that
|
|
1282
|
-
* fails retries and re-queues anyway. The promise resolves when the
|
|
1283
|
-
* running flush, drain included, has settled.
|
|
1284
|
-
*/
|
|
1285
|
-
flush(drain = false) {
|
|
1286
|
-
if (drain) this.drainPending = true;
|
|
1287
|
-
if (this.current) return this.current;
|
|
1288
|
-
if (this.pendingCount() === 0 || !this.online && !this.drainPending) {
|
|
1289
|
-
this.drainPending = false;
|
|
1290
|
-
return Promise.resolve();
|
|
1291
|
-
}
|
|
1292
|
-
this.current = this.run();
|
|
1293
|
-
return this.current;
|
|
1294
|
-
}
|
|
1295
|
-
async run() {
|
|
1296
|
-
try {
|
|
1297
|
-
do {
|
|
1298
|
-
const flight = this.reviveNext() ?? this.formFlight();
|
|
1299
|
-
if (flight === null) return;
|
|
1300
|
-
this.inFlight = flight;
|
|
1301
|
-
try {
|
|
1302
|
-
await this.sendWithRetry(flight);
|
|
1303
|
-
} catch {
|
|
1304
|
-
if (!flight.abandoned) {
|
|
1305
|
-
this.retryQueue.unshift(flight);
|
|
1306
|
-
this.trimToCapacity();
|
|
1307
|
-
}
|
|
1308
|
-
return;
|
|
1309
|
-
} finally {
|
|
1310
|
-
if (this.inFlight === flight) this.inFlight = null;
|
|
1311
|
-
}
|
|
1312
|
-
} while (this.drainPending && this.pendingCount() > 0);
|
|
1313
|
-
} finally {
|
|
1314
|
-
this.drainPending = false;
|
|
1315
|
-
if (this.pendingCount() === 0) this.rushDeferred = false;
|
|
1316
|
-
this.current = null;
|
|
1317
|
-
this.disarmWhenDrained();
|
|
1318
|
-
}
|
|
1319
|
-
}
|
|
1320
|
-
/* -------------------------------------------------------------- */
|
|
1321
|
-
/* Network send */
|
|
1322
|
-
/* -------------------------------------------------------------- */
|
|
1323
|
-
async sendWithRetry(flight) {
|
|
1324
|
-
const json = flight.json;
|
|
1325
|
-
for (let attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) {
|
|
1326
|
-
if (flight.abandoned) return;
|
|
1327
|
-
try {
|
|
1328
|
-
const { body, bytes, encoding } = await compressPayload(json);
|
|
1329
|
-
if (flight.abandoned) return;
|
|
1330
|
-
const headers = {
|
|
1331
|
-
"Content-Type": "application/json",
|
|
1332
|
-
"X-API-Key": this.config.apiKey
|
|
1333
|
-
};
|
|
1334
|
-
if (encoding) {
|
|
1335
|
-
headers["Content-Encoding"] = encoding;
|
|
1336
|
-
}
|
|
1337
|
-
const keepalive = bytes <= KEEPALIVE_QUOTA_BYTES;
|
|
1338
|
-
if (keepalive) this.inflightKeepaliveBytes += bytes;
|
|
1339
|
-
let response;
|
|
1340
|
-
let detail;
|
|
1341
|
-
flight.onWire = true;
|
|
1342
|
-
flight.dispatched = true;
|
|
1343
|
-
try {
|
|
1344
|
-
response = await fetch(this.config.endpoint, {
|
|
1345
|
-
method: "POST",
|
|
1346
|
-
headers,
|
|
1347
|
-
body,
|
|
1348
|
-
keepalive
|
|
1349
|
-
});
|
|
1350
|
-
try {
|
|
1351
|
-
detail = await response.text();
|
|
1352
|
-
} catch {
|
|
1353
|
-
detail = null;
|
|
1354
|
-
}
|
|
1355
|
-
} finally {
|
|
1356
|
-
flight.onWire = false;
|
|
1357
|
-
if (keepalive) this.inflightKeepaliveBytes -= bytes;
|
|
1358
|
-
}
|
|
1359
|
-
if (response.ok) return;
|
|
1360
|
-
const code = codeForStatus(response.status);
|
|
1361
|
-
if (code !== null) {
|
|
1362
|
-
this.fail(code, response.status, detail);
|
|
1363
|
-
return;
|
|
1364
|
-
}
|
|
1365
|
-
} catch {
|
|
1366
|
-
}
|
|
1367
|
-
const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt) * (0.5 + Math.random() * 0.5);
|
|
1368
|
-
await sleep(delay);
|
|
1369
|
-
}
|
|
1370
|
-
throw new Error("Transport: all retry attempts failed");
|
|
1371
|
-
}
|
|
1372
|
-
/* -------------------------------------------------------------- */
|
|
1373
|
-
/* Page-unload flush */
|
|
1374
|
-
/* -------------------------------------------------------------- */
|
|
1375
|
-
/**
|
|
1376
|
-
* The last flush, issued while the document is being torn down.
|
|
1377
|
-
*
|
|
1378
|
-
* THIS WAS navigator.sendBeacon, AND EVERY SESSION LOST ITS TAIL.
|
|
1379
|
-
* sendBeacon cannot set headers, so the batch arrived at the ingest
|
|
1380
|
-
* endpoint with no X-API-Key and was refused with 401 — after the
|
|
1381
|
-
* events had been spliced out of the queue, and with no response for
|
|
1382
|
-
* anything here to read. MEASURED in Chromium 145.0.7632.6 with a
|
|
1383
|
-
* cross-origin endpoint, 5 runs per scenario: the beacon's
|
|
1384
|
-
* application/json Blob also forces a CORS preflight the beacon does
|
|
1385
|
-
* not survive, 0/5 delivered on navigate-away and 0/5 on tab close.
|
|
1386
|
-
*
|
|
1387
|
-
* fetch with keepalive:true is what sendBeacon is specified as, plus
|
|
1388
|
-
* headers: same measurement, 5/5 and 5/5, key attached. The request
|
|
1389
|
-
* is dispatched SYNCHRONOUSLY inside the unload handler — no
|
|
1390
|
-
* compression, because CompressionStream is async and an await here
|
|
1391
|
-
* lands after the document is gone.
|
|
1392
|
-
*
|
|
1393
|
-
* THE PAYLOAD IS CUT AT THE KEEPALIVE QUOTA, oldest events first. A
|
|
1394
|
-
* keepalive request over the quota is refused by the browser before
|
|
1395
|
-
* it leaves, and one refused request loses everything; one cut at the
|
|
1396
|
-
* quota ships the prefix that fits. The quota is on the SUM of
|
|
1397
|
-
* in-flight keepalive bodies, so a timed batch still on the wire is
|
|
1398
|
-
* subtracted.
|
|
1399
|
-
*
|
|
1400
|
-
* THE CUT IS AT THE FIRST EVENT THAT DOES NOT FIT, in order — not
|
|
1401
|
-
* skip-and-continue. An event over the quota on its own (a network
|
|
1402
|
-
* event with a large body; an rrweb FullSnapshot of a big page) holds
|
|
1403
|
-
* back everything queued behind it, small or not. Not for order's
|
|
1404
|
-
* sake — every event carries its `seq` and the server sorts by it, so
|
|
1405
|
-
* a document that survives its pagehide (a back/forward-cache entry)
|
|
1406
|
-
* and later ships the held-back event from its timer is stored in
|
|
1407
|
-
* order regardless. For the node map: the flow engine's extractor.ts
|
|
1408
|
-
* builds it from the FullSnapshot, and every incremental event
|
|
1409
|
-
* behind a snapshot names its nodes by that snapshot's ids. Shipped
|
|
1410
|
-
* without it, they are resolved against a map that does not hold
|
|
1411
|
-
* their nodes, and selectorFromNode answers `body` for a node it
|
|
1412
|
-
* cannot find — a click on `body` in the generated test, silently,
|
|
1413
|
-
* where the session ending at the snapshot would have been the
|
|
1414
|
-
* truth. So what does not fit holds back what depends on it.
|
|
1415
|
-
*
|
|
1416
|
-
* Events that do not fit stay in the queue: there is no way to send
|
|
1417
|
-
* them from a dying page, and no way to report it — this is the one
|
|
1418
|
-
* flush that is fire-and-forget, and only because the document is
|
|
1419
|
-
* leaving. Which is why an event that can never fit is not left to
|
|
1420
|
-
* wait here: enqueue() sends it as soon as it is queued.
|
|
1421
|
-
*/
|
|
1422
|
-
/**
|
|
1423
|
-
* Take back the batch run() is holding, if no request for it has been
|
|
1424
|
-
* dispatched yet.
|
|
1425
|
-
*
|
|
1426
|
-
* THE GAP THIS CLOSES. run() splices a batch out of the queue and
|
|
1427
|
-
* hands it to sendWithRetry, and a request does not leave the browser
|
|
1428
|
-
* straight away: compressPayload is asynchronous, and after a failed
|
|
1429
|
-
* attempt sendWithRetry sleeps 0.5–1 s, then 1–2 s, before the next
|
|
1430
|
-
* one. Through all of that the events are in neither the queue nor a
|
|
1431
|
-
* request, and the unload flush could not see them. pagehide in that
|
|
1432
|
-
* window shipped the events queued AFTER them with keepalive and
|
|
1433
|
-
* never dispatched these, because an await does not resume in a
|
|
1434
|
-
* document that is gone — so the server's seq-sorted file got the
|
|
1435
|
-
* tail with a hole in the body. A hole is worse than a short
|
|
1436
|
-
* recording: the events after it name node ids the missing batch
|
|
1437
|
-
* introduced, and the flow engine resolves them against a map that
|
|
1438
|
-
* does not hold them.
|
|
1439
|
-
*
|
|
1440
|
-
* ONLY WHILE NOTHING IS ON THE WIRE. A dispatched keepalive request
|
|
1441
|
-
* outlives the document by design, and one without keepalive may
|
|
1442
|
-
* still arrive; re-sending those events would duplicate them in a
|
|
1443
|
-
* file the server appends to by seq. That request in flight when the
|
|
1444
|
-
* document dies is the residual limit, and it is the same one every
|
|
1445
|
-
* in-flight request has.
|
|
1446
|
-
*
|
|
1447
|
-
* `abandoned` stops every further attempt, so a document that
|
|
1448
|
-
* SURVIVES its pagehide (a back/forward-cache entry, a cancelled
|
|
1449
|
-
* navigation) does not send the batch a second time when the backoff
|
|
1450
|
-
* resumes, and run()'s catch does not unshift what has already gone.
|
|
1451
|
-
*/
|
|
1452
|
-
reclaimInFlight() {
|
|
1453
|
-
const flight = this.inFlight;
|
|
1454
|
-
if (!flight || flight.onWire || flight.abandoned) return;
|
|
1455
|
-
flight.abandoned = true;
|
|
1456
|
-
this.inFlight = null;
|
|
1457
|
-
if (flight.dispatched) {
|
|
1458
|
-
this.retryQueue.unshift(flight);
|
|
1459
|
-
this.trimToCapacity();
|
|
1460
|
-
return;
|
|
1461
|
-
}
|
|
1462
|
-
this.queue.unshift(...flight.events);
|
|
1463
|
-
this.trimToCapacity();
|
|
1464
|
-
}
|
|
1465
|
-
/**
|
|
1466
|
-
* The next waiting flight as a FRESH ATTEMPT CONTEXT, or null.
|
|
1467
|
-
*
|
|
1468
|
-
* `abandoned` does one job: it stops the sendWithRetry loop that was
|
|
1469
|
-
* running when the unload flush took the flight. That loop still
|
|
1470
|
-
* holds the OLD object, so it must keep seeing `abandoned === true`
|
|
1471
|
-
* -- but the re-send must not, or it returns from sendWithRetry
|
|
1472
|
-
* before its first attempt and run() counts the flight as delivered.
|
|
1473
|
-
* MEASURED: a flight over the keepalive quota, reclaimed at pagehide
|
|
1474
|
-
* during its backoff on a document that survived (a download click,
|
|
1475
|
-
* a cancelled navigation, a bfcache restore), was shifted by the next
|
|
1476
|
-
* flush and dropped -- queueSize 2 -> 0, zero requests, where the
|
|
1477
|
-
* pre-batchId transport delivered both events. So the flags are
|
|
1478
|
-
* per attempt and the id and bytes are per flight.
|
|
1479
|
-
*/
|
|
1480
|
-
reviveNext() {
|
|
1481
|
-
const waiting = this.retryQueue.shift();
|
|
1482
|
-
if (!waiting) return null;
|
|
1483
|
-
return {
|
|
1484
|
-
events: waiting.events,
|
|
1485
|
-
batchId: waiting.batchId,
|
|
1486
|
-
json: waiting.json,
|
|
1487
|
-
dispatched: waiting.dispatched,
|
|
1488
|
-
onWire: false,
|
|
1489
|
-
abandoned: false
|
|
1490
|
-
};
|
|
1491
|
-
}
|
|
1492
|
-
/**
|
|
1493
|
-
* A new flight from the head of the queue, or null when it is empty.
|
|
1494
|
-
* The id and the bytes are minted together, once.
|
|
1495
|
-
*
|
|
1496
|
-
* CUT BY BYTES AS WELL AS BY COUNT, the way the unload flush cuts
|
|
1497
|
-
* against the keepalive quota: at the first event that would take the
|
|
1498
|
-
* decoded body over MAX_BATCH_BYTES, everything behind it holding for
|
|
1499
|
-
* the next flight. The first event always fits -- enqueue() refused
|
|
1500
|
-
* anything that alone would not -- so a flight is never empty while
|
|
1501
|
-
* the queue is not.
|
|
1502
|
-
*/
|
|
1503
|
-
formFlight() {
|
|
1504
|
-
if (this.queue.length === 0) return null;
|
|
1505
|
-
let bytes = this.envelopeBytes;
|
|
1506
|
-
let count = 0;
|
|
1507
|
-
const most = Math.min(this.config.batchSize, this.queue.length);
|
|
1508
|
-
while (count < most) {
|
|
1509
|
-
const cost = this.eventBytes(this.queue[count]) + (count === 0 ? 0 : 1);
|
|
1510
|
-
if (bytes + cost > MAX_BATCH_BYTES) break;
|
|
1511
|
-
bytes += cost;
|
|
1512
|
-
count++;
|
|
1513
|
-
}
|
|
1514
|
-
const batch = this.queue.splice(0, Math.max(count, 1));
|
|
1515
|
-
const batchId = this.mintBatchId();
|
|
1516
|
-
return {
|
|
1517
|
-
events: batch,
|
|
1518
|
-
batchId,
|
|
1519
|
-
json: JSON.stringify(this.payload(batch, batchId)),
|
|
1520
|
-
dispatched: false,
|
|
1521
|
-
onWire: false,
|
|
1522
|
-
abandoned: false
|
|
1523
|
-
};
|
|
1524
|
-
}
|
|
1525
|
-
/** The event's JSON bytes: what enqueue() measured, or measured now for an event that reached the queue another way. */
|
|
1526
|
-
eventBytes(event) {
|
|
1527
|
-
let own = this.bytesOf.get(event);
|
|
1528
|
-
if (own === void 0) {
|
|
1529
|
-
own = utf8Length(JSON.stringify(event));
|
|
1530
|
-
this.bytesOf.set(event, own);
|
|
1531
|
-
}
|
|
1532
|
-
return own;
|
|
1533
|
-
}
|
|
1534
|
-
/**
|
|
1535
|
-
* The SDK's idempotency key for one POST: 36 characters of a UUID,
|
|
1536
|
-
* which is within the server's session-id shape (letters, digits,
|
|
1537
|
-
* dot, dash, underscore). Falls back to time plus a counter and a
|
|
1538
|
-
* random suffix where crypto.randomUUID is not available; only
|
|
1539
|
-
* uniqueness within one session matters, since the server scopes the
|
|
1540
|
-
* id to the session.
|
|
1541
|
-
*/
|
|
1542
|
-
mintBatchId() {
|
|
1543
|
-
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
1544
|
-
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
1545
|
-
this.batchCounter += 1;
|
|
1546
|
-
const rand = Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0");
|
|
1547
|
-
return `${Date.now().toString(16).padStart(12, "0")}-${(this.batchCounter % 4294967296).toString(16).padStart(8, "0")}-` + rand;
|
|
1548
|
-
}
|
|
1549
|
-
/** Events waiting to be sent, retry flights included. */
|
|
1550
|
-
pendingCount() {
|
|
1551
|
-
let n = this.queue.length;
|
|
1552
|
-
for (const f of this.retryQueue) n += f.events.length;
|
|
1553
|
-
return n;
|
|
1554
|
-
}
|
|
1555
|
-
/**
|
|
1556
|
-
* On a re-queue, hold the total at maxQueueSize by dropping the NEWEST
|
|
1557
|
-
* queued events, as the old unshift-then-pop did. enqueue() trims the
|
|
1558
|
-
* queue alone (oldest first) and does not see waiting flights, so
|
|
1559
|
-
* between re-queues the total can stand one batch over maxQueueSize
|
|
1560
|
-
* -- the same bound the old code had, where one batch sat off the
|
|
1561
|
-
* queue in flight. A retry flight is never trimmed: dropping events
|
|
1562
|
-
* from it would change the set its batchId is bound to, and the
|
|
1563
|
-
* server answers that with a 409.
|
|
1564
|
-
*/
|
|
1565
|
-
trimToCapacity() {
|
|
1566
|
-
let retry = 0;
|
|
1567
|
-
for (const f of this.retryQueue) retry += f.events.length;
|
|
1568
|
-
while (this.queue.length > 0 && retry + this.queue.length > this.config.maxQueueSize) {
|
|
1569
|
-
this.queue.pop();
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
flushOnUnload() {
|
|
1573
|
-
this.reclaimInFlight();
|
|
1574
|
-
if (typeof fetch !== "function") return;
|
|
1575
|
-
while (this.retryQueue.length > 0) {
|
|
1576
|
-
const flight = this.retryQueue[0];
|
|
1577
|
-
const size = utf8Length(flight.json);
|
|
1578
|
-
if (size > KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes) return;
|
|
1579
|
-
this.retryQueue.shift();
|
|
1580
|
-
flight.dispatched = true;
|
|
1581
|
-
this.postKeepalive(flight.json, size);
|
|
1582
|
-
}
|
|
1583
|
-
if (this.queue.length === 0) return;
|
|
1584
|
-
const budget = KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes;
|
|
1585
|
-
const envelope = this.payload([], this.mintBatchId());
|
|
1586
|
-
let bytes = this.envelopeBytes;
|
|
1587
|
-
let count = 0;
|
|
1588
|
-
for (const event of this.queue) {
|
|
1589
|
-
const cost = this.eventBytes(event) + (count === 0 ? 0 : 1);
|
|
1590
|
-
if (bytes + cost > budget) break;
|
|
1591
|
-
bytes += cost;
|
|
1592
|
-
count++;
|
|
1593
|
-
}
|
|
1594
|
-
if (count === 0) return;
|
|
1595
|
-
envelope.events = this.queue.splice(0, count);
|
|
1596
|
-
const json = JSON.stringify(envelope);
|
|
1597
|
-
this.postKeepalive(json, utf8Length(json));
|
|
1598
|
-
}
|
|
1599
|
-
/** One fire-and-forget keepalive POST, accounted against the quota. */
|
|
1600
|
-
postKeepalive(json, size) {
|
|
1601
|
-
try {
|
|
1602
|
-
this.inflightKeepaliveBytes += size;
|
|
1603
|
-
fetch(this.config.endpoint, {
|
|
1604
|
-
method: "POST",
|
|
1605
|
-
headers: {
|
|
1606
|
-
"Content-Type": "application/json",
|
|
1607
|
-
"X-API-Key": this.config.apiKey
|
|
1608
|
-
},
|
|
1609
|
-
body: json,
|
|
1610
|
-
keepalive: true
|
|
1611
|
-
}).then((response) => response.arrayBuffer()).catch(() => {
|
|
1612
|
-
}).finally(() => {
|
|
1613
|
-
this.inflightKeepaliveBytes -= size;
|
|
1614
|
-
});
|
|
1615
|
-
} catch {
|
|
1616
|
-
this.inflightKeepaliveBytes -= size;
|
|
1617
|
-
}
|
|
1618
|
-
}
|
|
1619
|
-
/* -------------------------------------------------------------- */
|
|
1620
|
-
/* Event handlers */
|
|
1621
|
-
/* -------------------------------------------------------------- */
|
|
1622
|
-
handleOnline = () => {
|
|
1623
|
-
this.online = true;
|
|
1624
|
-
void this.flush(this.rushDeferred);
|
|
1625
|
-
};
|
|
1626
|
-
handleOffline = () => {
|
|
1627
|
-
this.online = false;
|
|
1628
|
-
};
|
|
1629
|
-
handleUnload = () => {
|
|
1630
|
-
this.flushOnUnload();
|
|
1631
|
-
this.disarmWhenDrained();
|
|
1632
|
-
};
|
|
1633
|
-
handleVisibility = () => {
|
|
1634
|
-
if (document.visibilityState === "hidden") {
|
|
1635
|
-
void this.flush(true);
|
|
1636
|
-
}
|
|
1637
|
-
};
|
|
1638
|
-
/* -------------------------------------------------------------- */
|
|
1639
|
-
/* Accessors */
|
|
1640
|
-
/* -------------------------------------------------------------- */
|
|
1641
|
-
/** Events waiting to be sent, including those in flights waiting to be re-sent. */
|
|
1642
|
-
get queueSize() {
|
|
1643
|
-
return this.pendingCount();
|
|
1644
|
-
}
|
|
1645
|
-
};
|
|
1646
|
-
|
|
1647
|
-
// src/recorder.ts
|
|
1648
|
-
function uuid() {
|
|
1649
|
-
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
1650
|
-
return crypto.randomUUID();
|
|
1651
|
-
}
|
|
1652
|
-
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
1653
|
-
const r = Math.random() * 16 | 0;
|
|
1654
|
-
return (c === "x" ? r : r & 3 | 8).toString(16);
|
|
1655
|
-
});
|
|
1656
|
-
}
|
|
1657
|
-
function gatherMetadata() {
|
|
1658
|
-
const w = typeof window !== "undefined" ? window : void 0;
|
|
1659
|
-
return {
|
|
1660
|
-
url: w?.location?.href ?? "",
|
|
1661
|
-
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "",
|
|
1662
|
-
viewport: {
|
|
1663
|
-
width: w?.innerWidth ?? 0,
|
|
1664
|
-
height: w?.innerHeight ?? 0
|
|
1665
|
-
},
|
|
1666
|
-
referrer: typeof document !== "undefined" ? document.referrer : "",
|
|
1667
|
-
language: typeof navigator !== "undefined" ? navigator.language : "",
|
|
1668
|
-
devicePixelRatio: w?.devicePixelRatio ?? 1,
|
|
1669
|
-
timestamp: Date.now()
|
|
1670
|
-
};
|
|
1671
|
-
}
|
|
1672
|
-
var rrwebImport = null;
|
|
1673
|
-
function loadRRWeb() {
|
|
1674
|
-
if (!rrwebImport) {
|
|
1675
|
-
rrwebImport = import("rrweb").then(
|
|
1676
|
-
(rrweb) => rrweb.record,
|
|
1677
|
-
() => {
|
|
1678
|
-
rrwebImport = null;
|
|
1679
|
-
return void 0;
|
|
1680
|
-
}
|
|
1681
|
-
);
|
|
1682
|
-
}
|
|
1683
|
-
return rrwebImport;
|
|
1684
|
-
}
|
|
1685
|
-
var KeployCaptureRecorder = class {
|
|
1686
|
-
/*
|
|
1687
|
-
* TWO GATES, AND WHAT EACH ONE HOLDS.
|
|
1688
|
-
*
|
|
1689
|
-
* `phase` is the lifecycle; the two flags are the two independent
|
|
1690
|
-
* reasons an active session is not emitting everything. They are
|
|
1691
|
-
* independent on purpose: a visibilitychange used to call resume()
|
|
1692
|
-
* unconditionally, so a tab coming back into view silently undid a
|
|
1693
|
-
* pause the integrator had asked for with KeployCapture.pause(). Now
|
|
1694
|
-
* a hidden tab and a manual pause each shut their own gate, and only
|
|
1695
|
-
* their own transition reopens it.
|
|
1696
|
-
*
|
|
1697
|
-
* THE TWO GATES HOLD DIFFERENT EVENTS, and collapsing them into one
|
|
1698
|
-
* was a regression of its own:
|
|
1699
|
-
*
|
|
1700
|
-
* sessionOpen — phase "active" and not userPaused. This gate holds
|
|
1701
|
-
* EVERY event. That is what pause() promises and what a session
|
|
1702
|
-
* that has ended means.
|
|
1703
|
-
*
|
|
1704
|
-
* getState() === "recording" — sessionOpen and not hidden. The DOM
|
|
1705
|
-
* gate. It decides where rrweb may start (record() emits its Meta
|
|
1706
|
-
* and FullSnapshot synchronously, so starting into a shut gate
|
|
1707
|
-
* loses both for good) and whether rrweb's events are emitted.
|
|
1708
|
-
*
|
|
1709
|
-
* A hidden tab therefore pauses DOM emission and NOT the network
|
|
1710
|
-
* exchanges the page makes. Gating those on `hidden` too meant a user
|
|
1711
|
-
* who clicked Submit and switched tab had the click recorded with no
|
|
1712
|
-
* mock for its request, and a page init()'d in a background tab
|
|
1713
|
-
* recorded none of its load-time API calls — in both cases the
|
|
1714
|
-
* request had already been issued and the page was still doing the
|
|
1715
|
-
* work. The DOM is the part that genuinely is not happening while
|
|
1716
|
-
* nobody is looking, and the mutations that are get their baseline
|
|
1717
|
-
* back from the full snapshot taken when the gate reopens (see
|
|
1718
|
-
* openDomGate()).
|
|
1719
|
-
*/
|
|
1720
|
-
phase = "idle";
|
|
1721
|
-
userPaused = false;
|
|
1722
|
-
hidden = false;
|
|
1723
|
-
/**
|
|
1724
|
-
* A dom event has been dropped since the DOM gate last shut — i.e.
|
|
1725
|
-
* the recording has a hole that only a new baseline can close.
|
|
1726
|
-
*
|
|
1727
|
-
* Set in emitEvent, which is the single place a dom event is
|
|
1728
|
-
* dropped, and cleared by the baseline that closes it. Without it
|
|
1729
|
-
* openDomGate() re-serialised the document on EVERY transition: a
|
|
1730
|
-
* visitor who alt-tabs thirty times on a page that mutates nothing
|
|
1731
|
-
* while hidden paid thirty FullSnapshots of a document that had not
|
|
1732
|
-
* changed. A snapshot of a real page is large — transport.ts's own
|
|
1733
|
-
* measurement is 236 KB for one — and any event over
|
|
1734
|
-
* KEEPALIVE_QUOTA_BYTES (64 KiB) is sent the moment it is queued as
|
|
1735
|
-
* a full drain, so each one is also an upload of its own.
|
|
1736
|
-
*/
|
|
1737
|
-
droppedWhileShut = false;
|
|
1738
|
-
sessionId = null;
|
|
1739
|
-
metadata = null;
|
|
1740
|
-
config;
|
|
1741
|
-
onEvent = null;
|
|
1742
|
-
onSessionEnd = null;
|
|
1743
|
-
rrwebStopFn = null;
|
|
1744
|
-
/** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */
|
|
1745
|
-
rrwebRecord = null;
|
|
1746
|
-
/** Set the moment rrweb's start is requested, so it is requested once. */
|
|
1747
|
-
rrwebRequested = false;
|
|
1748
|
-
/**
|
|
1749
|
-
* Counts start() calls. Both awaits below — start()'s on startRRWeb()
|
|
1750
|
-
* and startRRWeb()'s on the import — resume into whatever session is
|
|
1751
|
-
* current by then, and compare this against the value they captured
|
|
1752
|
-
* before yielding: a continuation of a superseded session does
|
|
1753
|
-
* nothing. See startRRWeb().
|
|
1754
|
-
*/
|
|
1755
|
-
generation = 0;
|
|
1756
|
-
sessionTimer = null;
|
|
1757
|
-
visibilityHandler = null;
|
|
1758
|
-
constructor(config) {
|
|
1759
|
-
this.config = config;
|
|
1760
|
-
}
|
|
1761
|
-
/* -------------------------------------------------------------- */
|
|
1762
|
-
/* Lifecycle */
|
|
1763
|
-
/* -------------------------------------------------------------- */
|
|
1764
|
-
async start(onEvent, onSessionEnd = null) {
|
|
1765
|
-
if (this.phase === "active") return this.sessionId;
|
|
1766
|
-
const sampleRate = this.config.sampleRate ?? 1;
|
|
1767
|
-
if (Math.random() > sampleRate) {
|
|
1768
|
-
this.phase = "stopped";
|
|
1769
|
-
return "";
|
|
1770
|
-
}
|
|
1771
|
-
this.onEvent = onEvent;
|
|
1772
|
-
this.onSessionEnd = onSessionEnd;
|
|
1773
|
-
let produced;
|
|
1774
|
-
try {
|
|
1775
|
-
produced = this.config.sessionIdGenerator ? this.config.sessionIdGenerator() : uuid();
|
|
1776
|
-
} catch (threw) {
|
|
1777
|
-
this.phase = "stopped";
|
|
1778
|
-
throw new SessionIdRefusal({
|
|
1779
|
-
sessionId: null,
|
|
1780
|
-
received: describeReceived({ threw })
|
|
1781
|
-
});
|
|
1782
|
-
}
|
|
1783
|
-
if (!isValidSessionId(produced)) {
|
|
1784
|
-
this.phase = "stopped";
|
|
1785
|
-
throw new SessionIdRefusal({
|
|
1786
|
-
sessionId: typeof produced === "string" ? produced : null,
|
|
1787
|
-
received: describeReceived({ returned: produced })
|
|
1788
|
-
});
|
|
1789
|
-
}
|
|
1790
|
-
this.sessionId = produced;
|
|
1791
|
-
this.metadata = gatherMetadata();
|
|
1792
|
-
this.phase = "active";
|
|
1793
|
-
this.userPaused = false;
|
|
1794
|
-
this.droppedWhileShut = false;
|
|
1795
|
-
this.hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
|
|
1796
|
-
this.rrwebRequested = false;
|
|
1797
|
-
const generation = ++this.generation;
|
|
1798
|
-
if (typeof document !== "undefined") {
|
|
1799
|
-
this.visibilityHandler = () => {
|
|
1800
|
-
this.hidden = document.visibilityState === "hidden";
|
|
1801
|
-
if (this.getState() === "recording") this.openDomGate();
|
|
1802
|
-
};
|
|
1803
|
-
document.addEventListener("visibilitychange", this.visibilityHandler);
|
|
1804
|
-
}
|
|
1805
|
-
await this.startRRWeb();
|
|
1806
|
-
if (generation !== this.generation || this.phase !== "active") return "";
|
|
1807
|
-
const maxDuration = this.config.maxSessionDuration ?? 6e5;
|
|
1808
|
-
this.sessionTimer = setTimeout(() => {
|
|
1809
|
-
this.stop();
|
|
1810
|
-
this.onSessionEnd?.();
|
|
1811
|
-
}, maxDuration);
|
|
1812
|
-
return this.sessionId;
|
|
1813
|
-
}
|
|
1814
|
-
stop() {
|
|
1815
|
-
if (this.phase !== "active") return;
|
|
1816
|
-
if (this.rrwebStopFn) {
|
|
1817
|
-
this.rrwebStopFn();
|
|
1818
|
-
this.rrwebStopFn = null;
|
|
1819
|
-
}
|
|
1820
|
-
this.rrwebRecord = null;
|
|
1821
|
-
if (this.sessionTimer) {
|
|
1822
|
-
clearTimeout(this.sessionTimer);
|
|
1823
|
-
this.sessionTimer = null;
|
|
1824
|
-
}
|
|
1825
|
-
if (this.visibilityHandler && typeof document !== "undefined") {
|
|
1826
|
-
document.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
1827
|
-
this.visibilityHandler = null;
|
|
1828
|
-
}
|
|
1829
|
-
this.phase = "stopped";
|
|
1830
|
-
}
|
|
1831
|
-
/** Close the gate until resume(). A visibility change cannot reopen it. */
|
|
1832
|
-
pause() {
|
|
1833
|
-
if (this.phase !== "active") return;
|
|
1834
|
-
this.userPaused = true;
|
|
1835
|
-
}
|
|
1836
|
-
/**
|
|
1837
|
-
* Reopen the manual pause. A hidden tab still keeps the gate shut.
|
|
1838
|
-
*
|
|
1839
|
-
* And start rrweb if it has been waiting for this — the same way the
|
|
1840
|
-
* visibilitychange that shows the tab does. A pause() before rrweb's
|
|
1841
|
-
* import landed (init() and pause() in one tick behind a consent
|
|
1842
|
-
* gate) meant the import resolved into a shut gate; the decision
|
|
1843
|
-
* there read `hidden` alone, so record() went ahead, Meta and
|
|
1844
|
-
* FullSnapshot were dropped, and with nothing here to start it
|
|
1845
|
-
* again, the session stayed snapshotless for good.
|
|
1846
|
-
*/
|
|
1847
|
-
resume() {
|
|
1848
|
-
if (this.phase !== "active") return;
|
|
1849
|
-
this.userPaused = false;
|
|
1850
|
-
if (this.getState() === "recording") this.openDomGate();
|
|
1851
|
-
}
|
|
1852
|
-
/**
|
|
1853
|
-
* The DOM gate has just reopened: give the recording a baseline.
|
|
1854
|
-
*
|
|
1855
|
-
* rrweb HAS NO PAUSE, so while the gate was shut it went on observing
|
|
1856
|
-
* and emitEvent dropped what it emitted. Every incremental event
|
|
1857
|
-
* rrweb produces names its nodes by the ids of the last FullSnapshot
|
|
1858
|
-
* — an `add` introduces an id and the `attributes`, `texts` and
|
|
1859
|
-
* `removes` after it refer to it — so the events from here on refer
|
|
1860
|
-
* to nodes the recording never showed. The flow engine resolves those
|
|
1861
|
-
* ids against the node map it builds from the snapshot
|
|
1862
|
-
* (flow-engine/src/extractor.ts) and selectorFromNode answers `body`
|
|
1863
|
-
* for an id it cannot find: a click on a button added while the tab
|
|
1864
|
-
* was hidden becomes a click on `body` in the generated test, and it
|
|
1865
|
-
* passes. Nothing anywhere said the recording had a hole.
|
|
1866
|
-
*
|
|
1867
|
-
* So a reopened gate re-serialises the document and re-numbers
|
|
1868
|
-
* rrweb's mirror. Two ways in, and exactly one of them fires:
|
|
1869
|
-
*
|
|
1870
|
-
* - rrweb has not started (hidden or paused since init, where
|
|
1871
|
-
* starting it would have emitted Meta and FullSnapshot into the
|
|
1872
|
-
* shut gate). Start it now; the snapshot record() takes inside
|
|
1873
|
-
* that call IS the baseline.
|
|
1874
|
-
* - rrweb is running. takeFullSnapshot(), which also throws before
|
|
1875
|
-
* record() has run — inside a visibilitychange handler that would
|
|
1876
|
-
* be an exception in the integrator's document.
|
|
1877
|
-
*/
|
|
1878
|
-
openDomGate() {
|
|
1879
|
-
if (!this.rrwebStopFn) {
|
|
1880
|
-
this.droppedWhileShut = false;
|
|
1881
|
-
void this.startRRWeb();
|
|
1882
|
-
return;
|
|
1883
|
-
}
|
|
1884
|
-
if (!this.droppedWhileShut) return;
|
|
1885
|
-
const takeFullSnapshot = this.rrwebRecord?.takeFullSnapshot;
|
|
1886
|
-
if (!takeFullSnapshot) return;
|
|
1887
|
-
try {
|
|
1888
|
-
takeFullSnapshot.call(this.rrwebRecord);
|
|
1889
|
-
this.droppedWhileShut = false;
|
|
1890
|
-
} catch {
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
/**
|
|
1894
|
-
* The id of the session that is LIVE, or null when none is.
|
|
1895
|
-
*
|
|
1896
|
-
* Null once the session has ended, including when the
|
|
1897
|
-
* maxSessionDuration timer ended it — this used to keep answering
|
|
1898
|
-
* with the id of a session its own timer had stopped, so an
|
|
1899
|
-
* integrator tagging their logs with it went on tagging them with a
|
|
1900
|
-
* session that had finished ten minutes earlier. A pause does not
|
|
1901
|
-
* end a session, so this keeps answering through one.
|
|
1902
|
-
*/
|
|
1903
|
-
getSessionId() {
|
|
1904
|
-
return this.phase === "active" ? this.sessionId : null;
|
|
1905
|
-
}
|
|
1906
|
-
/**
|
|
1907
|
-
* The SESSION gate: a live session the integrator has not paused.
|
|
1908
|
-
*
|
|
1909
|
-
* Deliberately not derived from getState(), which is the narrower DOM
|
|
1910
|
-
* gate and answers "paused" for a hidden tab.
|
|
1911
|
-
*/
|
|
1912
|
-
get sessionOpen() {
|
|
1913
|
-
return this.phase === "active" && !this.userPaused;
|
|
1914
|
-
}
|
|
1915
|
-
/**
|
|
1916
|
-
* The DOM gate, as a public state.
|
|
1917
|
-
*
|
|
1918
|
-
* "recording" means rrweb may run and its events are emitted; a
|
|
1919
|
-
* hidden tab reads "paused" here while the session itself is still
|
|
1920
|
-
* open and still recording the exchanges the page makes. This is the
|
|
1921
|
-
* meaning the state has always had — every caller of it decides
|
|
1922
|
-
* something about rrweb — and it is the only one it can have while
|
|
1923
|
-
* one enum stands for two independent gates.
|
|
1924
|
-
*/
|
|
1925
|
-
getState() {
|
|
1926
|
-
if (this.phase === "idle") return "idle";
|
|
1927
|
-
if (this.phase === "stopped") return "stopped";
|
|
1928
|
-
return this.userPaused || this.hidden ? "paused" : "recording";
|
|
1929
|
-
}
|
|
1930
|
-
getMetadata() {
|
|
1931
|
-
return this.metadata;
|
|
1932
|
-
}
|
|
1933
|
-
/* -------------------------------------------------------------- */
|
|
1934
|
-
/* rrweb integration */
|
|
1935
|
-
/* -------------------------------------------------------------- */
|
|
1936
|
-
async startRRWeb() {
|
|
1937
|
-
if (this.rrwebRequested) return;
|
|
1938
|
-
this.rrwebRequested = true;
|
|
1939
|
-
const generation = this.generation;
|
|
1940
|
-
const rrwebRecord = await loadRRWeb();
|
|
1941
|
-
if (!rrwebRecord) return;
|
|
1942
|
-
if (generation !== this.generation) return;
|
|
1943
|
-
if (this.getState() !== "recording") {
|
|
1944
|
-
this.rrwebRequested = false;
|
|
1945
|
-
return;
|
|
1946
|
-
}
|
|
1947
|
-
this.rrwebRecord = rrwebRecord;
|
|
1948
|
-
this.rrwebStopFn = rrwebRecord(this.rrwebOptions()) ?? null;
|
|
1949
|
-
}
|
|
1950
|
-
/**
|
|
1951
|
-
* Everything the SDK's privacy configuration means to rrweb.
|
|
1952
|
-
*
|
|
1953
|
-
* NO `maskAllInputs`. MEASURED in rrweb 2.0.0-alpha.20's record()
|
|
1954
|
-
* (rrweb.js:13778-13795): `maskAllInputs: true` DISCARDS the
|
|
1955
|
-
* maskInputOptions object it was handed and substitutes a fixed map
|
|
1956
|
-
* of 16 input types, and neither `hidden` nor `file` is among them —
|
|
1957
|
-
* so the SDK's own map was dead in balanced and strict, and a CSRF
|
|
1958
|
-
* token, a session id or an internal record id in `<input
|
|
1959
|
-
* type="hidden">` was serialised in the clear in every mode.
|
|
1960
|
-
* Leaving `maskAllInputs` unset makes rrweb use the map below
|
|
1961
|
-
* verbatim (the `_maskInputOptions !== void 0` branch of the same
|
|
1962
|
-
* expression), which is the only way to name a type rrweb's fixed
|
|
1963
|
-
* map omits.
|
|
1964
|
-
*
|
|
1965
|
-
* The map is the ONLY statement of what each mode masks. Three
|
|
1966
|
-
* things are held to it and none of them keeps a second copy:
|
|
1967
|
-
* dom-masking.test.ts drives one case per entry through real rrweb
|
|
1968
|
-
* and asserts the serialised `value`, readme.test.ts holds the npm
|
|
1969
|
-
* page's privacy table to it, and readme.test.ts also requires every
|
|
1970
|
-
* input type the HTML spec has to be either in it or named in the
|
|
1971
|
-
* page's carve-out. Before that, thirteen of its rows were untested:
|
|
1972
|
-
* MEASURED, flipping `email`, `select`, `month`, `tel` and `number`
|
|
1973
|
-
* to `false` left the whole SDK suite green.
|
|
1974
|
-
*/
|
|
1975
|
-
rrwebOptions() {
|
|
1976
|
-
const privacyMode = this.config.privacyMode ?? "balanced";
|
|
1977
|
-
const privacy = this.config.privacy ?? {};
|
|
1978
|
-
const maskSelectors = [
|
|
1979
|
-
...this.config.maskSelectors ?? [],
|
|
1980
|
-
...privacy.maskSelectors ?? []
|
|
1981
|
-
];
|
|
1982
|
-
const unmaskSelectors = [
|
|
1983
|
-
...this.config.unmaskSelectors ?? [],
|
|
1984
|
-
...privacy.unmaskSelectors ?? []
|
|
1985
|
-
];
|
|
1986
|
-
const typed = privacyMode !== "off";
|
|
1987
|
-
const maskInputOptions = {
|
|
1988
|
-
color: typed,
|
|
1989
|
-
date: typed,
|
|
1990
|
-
"datetime-local": typed,
|
|
1991
|
-
email: typed,
|
|
1992
|
-
file: typed,
|
|
1993
|
-
month: typed,
|
|
1994
|
-
number: typed,
|
|
1995
|
-
range: typed,
|
|
1996
|
-
search: typed,
|
|
1997
|
-
tel: typed,
|
|
1998
|
-
text: typed,
|
|
1999
|
-
time: typed,
|
|
2000
|
-
url: typed,
|
|
2001
|
-
week: typed,
|
|
2002
|
-
textarea: typed,
|
|
2003
|
-
select: typed,
|
|
2004
|
-
password: true,
|
|
2005
|
-
hidden: true
|
|
2006
|
-
};
|
|
2007
|
-
const unmask = unmaskSelectors.join(",");
|
|
2008
|
-
const maskTextFn = unmask ? (text, element) => {
|
|
2009
|
-
try {
|
|
2010
|
-
if (element?.closest(unmask)) return text;
|
|
2011
|
-
} catch {
|
|
2012
|
-
}
|
|
2013
|
-
return text.replace(/[\S]/g, "*");
|
|
2014
|
-
} : void 0;
|
|
2015
|
-
return {
|
|
2016
|
-
// Gated inside emitEvent, like every other emitter.
|
|
2017
|
-
emit: (event) => this.emitEvent("dom", event),
|
|
2018
|
-
maskTextSelector: privacyMode === "strict" ? "*" : maskSelectors.join(",") || void 0,
|
|
2019
|
-
...maskTextFn ? { maskTextFn } : {},
|
|
2020
|
-
blockSelector: privacy.blockSelectors?.join(",") || void 0,
|
|
2021
|
-
maskInputOptions
|
|
2022
|
-
};
|
|
2023
|
-
}
|
|
2024
|
-
/* -------------------------------------------------------------- */
|
|
2025
|
-
/* Event emission */
|
|
2026
|
-
/* -------------------------------------------------------------- */
|
|
2027
|
-
/**
|
|
2028
|
-
* Emit an event to the registered callback. This is also called
|
|
2029
|
-
* externally by the main KeployCapture orchestrator for network
|
|
2030
|
-
* events.
|
|
2031
|
-
*
|
|
2032
|
-
* THE GATES ARE HERE, so every emitter faces the same two. They used
|
|
2033
|
-
* to sit only in rrweb's emit callback, which meant "paused" and
|
|
2034
|
-
* "stopped" applied to DOM events and to nothing else.
|
|
2035
|
-
*/
|
|
2036
|
-
emitEvent(type, data) {
|
|
2037
|
-
if (type === "dom" && this.phase === "active" && this.getState() !== "recording") {
|
|
2038
|
-
this.droppedWhileShut = true;
|
|
2039
|
-
}
|
|
2040
|
-
if (!this.sessionOpen) return;
|
|
2041
|
-
if (type === "dom" && this.hidden) return;
|
|
2042
|
-
if (!this.onEvent || !this.sessionId) return;
|
|
2043
|
-
const event = {
|
|
2044
|
-
id: uuid(),
|
|
2045
|
-
sessionId: this.sessionId,
|
|
2046
|
-
timestamp: Date.now(),
|
|
2047
|
-
type,
|
|
2048
|
-
data
|
|
2049
|
-
};
|
|
2050
|
-
this.onEvent(event);
|
|
2051
|
-
}
|
|
2052
|
-
};
|
|
2053
|
-
|
|
2054
|
-
// src/identity.ts
|
|
2055
|
-
function mintSessionNonce() {
|
|
2056
|
-
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
2057
|
-
if (!c || typeof c.getRandomValues !== "function") return null;
|
|
2058
|
-
const bytes = new Uint8Array(16);
|
|
2059
|
-
c.getRandomValues(bytes);
|
|
2060
|
-
let out = "";
|
|
2061
|
-
for (const b of bytes) out += b.toString(16).padStart(2, "0");
|
|
2062
|
-
return out;
|
|
2063
|
-
}
|
|
2064
|
-
function currentOrigin() {
|
|
2065
|
-
if (typeof window === "undefined" || !window.location) return null;
|
|
2066
|
-
const origin = window.location.origin;
|
|
2067
|
-
if (typeof origin !== "string" || origin === "" || origin === "null") {
|
|
2068
|
-
return null;
|
|
2069
|
-
}
|
|
2070
|
-
return origin;
|
|
2071
|
-
}
|
|
2072
|
-
var CaptureIdentityBuilder = class {
|
|
2073
|
-
captureId;
|
|
2074
|
-
nonce;
|
|
2075
|
-
t0WallMs;
|
|
2076
|
-
origins;
|
|
2077
|
-
constructor(captureId, now = Date.now()) {
|
|
2078
|
-
this.captureId = captureId;
|
|
2079
|
-
this.nonce = mintSessionNonce();
|
|
2080
|
-
this.t0WallMs = now;
|
|
2081
|
-
const origin = currentOrigin();
|
|
2082
|
-
this.origins = origin === null ? [] : [origin];
|
|
2083
|
-
}
|
|
2084
|
-
/**
|
|
2085
|
-
* The identity, or the reason there is none.
|
|
2086
|
-
*
|
|
2087
|
-
* FAILS CLOSED on every incomplete case, matching Validate() on the Go
|
|
2088
|
-
* side: an identity missing the nonce or the origins is not a weaker
|
|
2089
|
-
* identity, it is one that would make the joiner confident about a
|
|
2090
|
-
* pairing it cannot actually establish.
|
|
2091
|
-
*/
|
|
2092
|
-
/*
|
|
2093
|
-
* IDENTITY AND JOINABILITY ARE DIFFERENT THINGS.
|
|
2094
|
-
*
|
|
2095
|
-
* This used to refuse the whole identity when no usable document origin
|
|
2096
|
-
* existed — a sandboxed iframe, a data: or file: URL — so those captures
|
|
2097
|
-
* sent `captureIdentity: null`. The server then had no token to tell one
|
|
2098
|
-
* run from another, and two runs sharing a session id merged their
|
|
2099
|
-
* events into one file at 200 OK. The guard that was supposed to stop
|
|
2100
|
-
* that could only fire when BOTH runs identified themselves, so the
|
|
2101
|
-
* degraded case — where the data is least trustworthy — was the one that
|
|
2102
|
-
* slipped through.
|
|
2103
|
-
*
|
|
2104
|
-
* The origin is what makes a capture JOINABLE to backend traffic. The
|
|
2105
|
-
* nonce is what makes it IDENTIFIABLE, and mintSessionNonce succeeds in
|
|
2106
|
-
* every browser that can run rrweb. So the identity is always sent when
|
|
2107
|
-
* a CSPRNG exists, `appOrigins` may be empty, and "can this be joined?"
|
|
2108
|
-
* is a question about that array rather than about the identity's
|
|
2109
|
-
* existence.
|
|
2110
|
-
*/
|
|
2111
|
-
build() {
|
|
2112
|
-
if (this.nonce === null) return { refusal: "no-csprng" };
|
|
2113
|
-
return {
|
|
2114
|
-
identity: {
|
|
2115
|
-
captureId: this.captureId,
|
|
2116
|
-
sessionNonce: this.nonce,
|
|
2117
|
-
t0WallMs: this.t0WallMs,
|
|
2118
|
-
// A copy, so a caller cannot mutate the builder's array through
|
|
2119
|
-
// an identity it was handed.
|
|
2120
|
-
appOrigins: [...this.origins]
|
|
2121
|
-
}
|
|
2122
|
-
};
|
|
2123
|
-
}
|
|
2124
|
-
};
|
|
2125
|
-
|
|
2126
|
-
// src/index.ts
|
|
2127
|
-
var KeployCapture = class _KeployCapture {
|
|
2128
|
-
static instance = null;
|
|
2129
|
-
recorder;
|
|
2130
|
-
network;
|
|
2131
|
-
transport;
|
|
2132
|
-
config;
|
|
2133
|
-
started = false;
|
|
2134
|
-
identity = null;
|
|
2135
|
-
constructor(config) {
|
|
2136
|
-
this.config = config;
|
|
2137
|
-
this.recorder = new KeployCaptureRecorder(config);
|
|
2138
|
-
this.network = new NetworkInterceptor(
|
|
2139
|
-
config.privacy ?? {},
|
|
2140
|
-
config.maxBodySize ?? 524288,
|
|
2141
|
-
[config.endpoint]
|
|
2142
|
-
);
|
|
2143
|
-
const transportConfig = {
|
|
2144
|
-
endpoint: config.endpoint,
|
|
2145
|
-
apiKey: config.apiKey,
|
|
2146
|
-
batchSize: config.batchSize ?? 50,
|
|
2147
|
-
batchInterval: config.batchInterval ?? 5e3,
|
|
2148
|
-
maxQueueSize: config.maxQueueSize ?? 5e3,
|
|
2149
|
-
...config.onError !== void 0 ? { onError: config.onError } : {},
|
|
2150
|
-
// A terminal rejection ends the CAPTURE, through the same path
|
|
2151
|
-
// the recorder's onSessionEnd takes. See endCapture().
|
|
2152
|
-
onCaptureEnd: () => this.endCapture()
|
|
2153
|
-
};
|
|
2154
|
-
this.transport = new Transport(transportConfig);
|
|
2155
|
-
}
|
|
2156
|
-
/* -------------------------------------------------------------- */
|
|
2157
|
-
/* Static API */
|
|
2158
|
-
/* -------------------------------------------------------------- */
|
|
2159
|
-
/**
|
|
2160
|
-
* Initialise and start capturing. This is the **only** call users need.
|
|
2161
|
-
*
|
|
2162
|
-
* ```ts
|
|
2163
|
-
* import { KeployCapture } from '@keploy/capture-sdk';
|
|
2164
|
-
* KeployCapture.init({ endpoint: '…', apiKey: '…' });
|
|
2165
|
-
* ```
|
|
2166
|
-
*/
|
|
2167
|
-
static async init(config) {
|
|
2168
|
-
if (_KeployCapture.instance) {
|
|
2169
|
-
return _KeployCapture.instance;
|
|
2170
|
-
}
|
|
2171
|
-
const capture = new _KeployCapture(config);
|
|
2172
|
-
_KeployCapture.instance = capture;
|
|
2173
|
-
try {
|
|
2174
|
-
await capture.start();
|
|
2175
|
-
} catch (err) {
|
|
2176
|
-
if (_KeployCapture.instance === capture) _KeployCapture.instance = null;
|
|
2177
|
-
throw err;
|
|
2178
|
-
}
|
|
2179
|
-
return capture;
|
|
2180
|
-
}
|
|
2181
|
-
/**
|
|
2182
|
-
* Stop all recording and flush remaining events.
|
|
2183
|
-
*
|
|
2184
|
-
* Resolves once the final flush has settled; awaiting it is optional.
|
|
2185
|
-
*/
|
|
2186
|
-
static stop() {
|
|
2187
|
-
const instance = _KeployCapture.instance;
|
|
2188
|
-
_KeployCapture.instance = null;
|
|
2189
|
-
return instance ? instance.stop() : Promise.resolve();
|
|
2190
|
-
}
|
|
2191
|
-
/**
|
|
2192
|
-
* Pause recording: no event of any kind — DOM or network — is
|
|
2193
|
-
* emitted until {@link resume}. The tab going hidden and visible in
|
|
2194
|
-
* between does not end the pause.
|
|
2195
|
-
*/
|
|
2196
|
-
static pause() {
|
|
2197
|
-
_KeployCapture.instance?.pause();
|
|
2198
|
-
}
|
|
2199
|
-
/** Resume recording after {@link pause}. A hidden tab stays paused until it is visible. */
|
|
2200
|
-
static resume() {
|
|
2201
|
-
_KeployCapture.instance?.resume();
|
|
2202
|
-
}
|
|
2203
|
-
/** Current session ID (empty string if not recording). */
|
|
2204
|
-
static getSessionId() {
|
|
2205
|
-
return _KeployCapture.instance?.recorder.getSessionId() ?? "";
|
|
2206
|
-
}
|
|
2207
|
-
/** Get the singleton instance (null if not initialised). */
|
|
2208
|
-
static getInstance() {
|
|
2209
|
-
return _KeployCapture.instance;
|
|
2210
|
-
}
|
|
2211
|
-
/**
|
|
2212
|
-
* The browser half of the offline backend join, exactly as it was
|
|
2213
|
-
* SENT — or the reason there isn't one, or null before a capture has
|
|
2214
|
-
* started.
|
|
2215
|
-
*
|
|
2216
|
-
* Rebuilding here is safe because the builder is IMMUTABLE: everything
|
|
2217
|
-
* it holds is assigned once in its constructor, so this returns the
|
|
2218
|
-
* same value start() handed the transport. An earlier version of the
|
|
2219
|
-
* builder accumulated origins, which would have made these two diverge
|
|
2220
|
-
* — and this method's docstring also claimed it could be consulted
|
|
2221
|
-
* "BEFORE the run", which was never true, since nothing is minted
|
|
2222
|
-
* until start().
|
|
2223
|
-
*
|
|
2224
|
-
* Three distinguishable answers, deliberately: `null` is "no capture
|
|
2225
|
-
* has started", `{refusal}` is "this capture cannot be joined and here
|
|
2226
|
-
* is why", `{identity}` is the value the server received.
|
|
2227
|
-
*/
|
|
2228
|
-
static getCaptureIdentity() {
|
|
2229
|
-
const builder = _KeployCapture.instance?.identity;
|
|
2230
|
-
return builder ? builder.build() : null;
|
|
2231
|
-
}
|
|
2232
|
-
/* -------------------------------------------------------------- */
|
|
2233
|
-
/* Instance methods */
|
|
2234
|
-
/* -------------------------------------------------------------- */
|
|
2235
|
-
async start() {
|
|
2236
|
-
if (this.started) return;
|
|
2237
|
-
this.started = true;
|
|
2238
|
-
let held = [];
|
|
2239
|
-
const handleEvent = (event) => {
|
|
2240
|
-
if (held) held.push(event);
|
|
2241
|
-
else this.transport.enqueue(event);
|
|
2242
|
-
};
|
|
2243
|
-
let sessionId;
|
|
2244
|
-
try {
|
|
2245
|
-
sessionId = await this.recorder.start(
|
|
2246
|
-
handleEvent,
|
|
2247
|
-
() => this.endCapture()
|
|
2248
|
-
);
|
|
2249
|
-
} catch (err) {
|
|
2250
|
-
if (!(err instanceof SessionIdRefusal)) throw err;
|
|
2251
|
-
this.refuse(err);
|
|
2252
|
-
return;
|
|
2253
|
-
}
|
|
2254
|
-
if (!sessionId) {
|
|
2255
|
-
this.started = false;
|
|
2256
|
-
return;
|
|
2257
|
-
}
|
|
2258
|
-
const metadata = this.recorder.getMetadata();
|
|
2259
|
-
this.identity = new CaptureIdentityBuilder(sessionId);
|
|
2260
|
-
const built = this.identity.build();
|
|
2261
|
-
this.transport.start(
|
|
2262
|
-
sessionId,
|
|
2263
|
-
metadata,
|
|
2264
|
-
"identity" in built ? built.identity : null
|
|
2265
|
-
);
|
|
2266
|
-
const first = held;
|
|
2267
|
-
held = null;
|
|
2268
|
-
for (const event of first) this.transport.enqueue(event);
|
|
2269
|
-
if (this.config.networkCapture !== false) {
|
|
2270
|
-
this.network.start((netEvent) => {
|
|
2271
|
-
this.recorder.emitEvent("network", netEvent);
|
|
2272
|
-
});
|
|
2273
|
-
}
|
|
2274
|
-
}
|
|
2275
|
-
stop() {
|
|
2276
|
-
this.recorder.stop();
|
|
2277
|
-
this.network.stop();
|
|
2278
|
-
this.started = false;
|
|
2279
|
-
return this.transport.stop();
|
|
2280
|
-
}
|
|
2281
|
-
/**
|
|
2282
|
-
* The recorder refused to start: the configured sessionIdGenerator
|
|
2283
|
-
* did not produce a session id -- a string outside the server's
|
|
2284
|
-
* rule, a non-string, or a throw (KUI_E_SESSION_ID_INVALID). Nothing
|
|
2285
|
-
* has been sent and nothing is patched, but the singleton is set, so
|
|
2286
|
-
* this takes the path a server rejection takes and in the same order
|
|
2287
|
-
* -- the console line, the capture ended and the singleton released,
|
|
2288
|
-
* THEN onError -- so a handler that fixes the generator and calls
|
|
2289
|
-
* init() again gets a fresh capture, not this dead one.
|
|
2290
|
-
*/
|
|
2291
|
-
refuse(err) {
|
|
2292
|
-
console.error(err.message);
|
|
2293
|
-
this.endCapture();
|
|
2294
|
-
try {
|
|
2295
|
-
this.config.onError?.(err);
|
|
2296
|
-
} catch {
|
|
2297
|
-
}
|
|
2298
|
-
}
|
|
2299
|
-
/**
|
|
2300
|
-
* A subsystem ended this capture on its own. ONE path, two callers:
|
|
2301
|
-
*
|
|
2302
|
-
* - the recorder, when `maxSessionDuration` elapses;
|
|
2303
|
-
* - the transport, when the server answers a batch with a terminal
|
|
2304
|
-
* 4xx — a revoked key, a key for another app, or a second run
|
|
2305
|
-
* claiming a live session id. That one used to stop the transport
|
|
2306
|
-
* alone, so rrweb kept recording, fetch and XHR stayed patched and
|
|
2307
|
-
* the session timer stayed armed for a capture that could never
|
|
2308
|
-
* post another byte.
|
|
2309
|
-
*
|
|
2310
|
-
* The singleton is released either way, so a later init() starts a
|
|
2311
|
-
* NEW session rather than handing back a finished or dead one — which
|
|
2312
|
-
* is the whole recovery path after a key is rotated.
|
|
2313
|
-
*/
|
|
2314
|
-
endCapture() {
|
|
2315
|
-
void this.stop();
|
|
2316
|
-
if (_KeployCapture.instance === this) _KeployCapture.instance = null;
|
|
2317
|
-
}
|
|
2318
|
-
/*
|
|
2319
|
-
* pause()/resume() touch the recorder only. Its gate is what every
|
|
2320
|
-
* emitter honours, so there is nothing else to switch; the network
|
|
2321
|
-
* interceptor stays installed for the life of the capture rather
|
|
2322
|
-
* than being unpatched and re-patched around each pause.
|
|
2323
|
-
*/
|
|
2324
|
-
pause() {
|
|
2325
|
-
this.recorder.pause();
|
|
2326
|
-
}
|
|
2327
|
-
resume() {
|
|
2328
|
-
this.recorder.resume();
|
|
2329
|
-
}
|
|
2330
|
-
};
|
|
2331
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
2332
|
-
0 && (module.exports = {
|
|
2333
|
-
CaptureError,
|
|
2334
|
-
CaptureIdentityBuilder,
|
|
2335
|
-
IngestRejection,
|
|
2336
|
-
KeployCapture,
|
|
2337
|
-
KeployCaptureRecorder,
|
|
2338
|
-
NetworkInterceptor,
|
|
2339
|
-
PrivacyEngine,
|
|
2340
|
-
SDK_ERRORS,
|
|
2341
|
-
SDK_WARNINGS,
|
|
2342
|
-
SESSION_ID_MAX_LENGTH,
|
|
2343
|
-
SESSION_ID_PATTERN,
|
|
2344
|
-
SESSION_ID_RULE,
|
|
2345
|
-
SessionIdRefusal,
|
|
2346
|
-
Transport,
|
|
2347
|
-
codeForStatus,
|
|
2348
|
-
currentOrigin,
|
|
2349
|
-
defaultPrivacyConfig,
|
|
2350
|
-
describeValue,
|
|
2351
|
-
isValidSessionId,
|
|
2352
|
-
mintSessionNonce,
|
|
2353
|
-
parseServerError
|
|
2354
|
-
});
|
|
1
|
+
Object.create;var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=(Object.getPrototypeOf,Object.prototype.hasOwnProperty),s={};((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})(s,{CaptureDeclined:()=>Kr,CaptureError:()=>Br,CaptureIdentityBuilder:()=>mo,DomRecorderRefusal:()=>jr,IngestRejection:()=>Ur,KeployCapture:()=>bo,KeployCaptureRecorder:()=>go,NetworkInterceptor:()=>Ss,PrivacyConflict:()=>Wr,PrivacyEngine:()=>yr,PrivacyRouteRefusal:()=>Mr,SDK_ERRORS:()=>Er,SDK_WARNINGS:()=>Ir,SESSION_ID_MAX_LENGTH:()=>vr,SESSION_ID_PATTERN:()=>mr,SESSION_ID_RULE:()=>wr,SessionIdRefusal:()=>Pr,StrictAttributesRefusal:()=>qr,Transport:()=>_s,codeForStatus:()=>Cr,currentOrigin:()=>vo,defaultPrivacyConfig:()=>dr,describeValue:()=>Lr,isValidSessionId:()=>br,mintSessionNonce:()=>yo,parseServerError:()=>Dr}),module.exports=(e=s,((e,s,o,a)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let l of r(s))!i.call(e,l)&&l!==o&&t(e,l,{get:()=>s[l],enumerable:!(a=n(s,l))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var o=/%[0-7][\da-f]|%(?:c[2-9a-f]|d[\da-f])%[89ab][\da-f]|%e0%[ab][\da-f]%[89ab][\da-f]|%e[1-9a-ce-f](?:%[89ab][\da-f]){2}|%ed%[89][\da-f]%[89ab][\da-f]|%f0%[9ab][\da-f](?:%[89ab][\da-f]){2}|%f[1-3](?:%[89ab][\da-f]){3}|%f4%8[\da-f](?:%[89ab][\da-f]){2}/gi;function a(e){return e.includes("%")?e.replace(o,e=>decodeURIComponent(e)):e}var l=new Set(["password","passwd","pwd","secret","token","accesstoken","refreshtoken","idtoken","authorization","auth","apikey","clientsecret","privatekey","session","sessionid","cookie","ssn","socialsecuritynumber","creditcard","cardnumber","cvv","cvc","pin","passphrase","pass1","pass2","currentpass","rpkey","codeverifier","rawkey","apikeyauth","setcookie","proxyauthorization","samlresponse","confirmkey","tokenhash","clerkticket","nonce","hmac","loginhash","magiclink","phpsessid","oauthverifier","sig","sid","sessid","csrf","xsrf","bearer","authentication","credentials","pass","tokenid","authkey","secretkey","accesskey","clientkey","signingkey","sessionkey","subscriptionkey","functionskey","factorcode","jwtassertion","samlassertion","clientassertion","secretaccesskey","accesskeysecret"]),u=new Set(["invitecode","invitationcode","authcode","authorizationcode","verificationcode","verifycode","confirmationcode","confirmcode","resetcode","mfacode","smscode","otpcode","totpcode","twofactorcode","2facode","logincode","passcode","oobcode","linkcode"]),c=new Set(["cardexpiry","cardexpiration","cardexpirydate","cardexpirationdate","cardexp","cardexpdate","cardexpmonth","cardexpyear","ccexp","ccexpiry","ccexpiration","ccexpdate","ccexpmonth","ccexpyear","creditcardexpiry","creditcardexpiration","expmonth","expyear","expirymonth","expiryyear","expirationmonth","expirationyear"]),d=/(?:password(?:\d|confirm|confirmation|new|old|repeat|again|verify|retype)?|passwd|secret|token|apikey|privatekey|passphrase|signature|sessionid|jwt|otp|credential|curl)$/,h=new Set(["pagetoken","nextpagetoken","prevpagetoken","previouspagetoken","pagingtoken","paginationtoken","nexttoken","prevtoken","previoustoken","continuationtoken","nextcontinuationtoken","cursortoken","synctoken","nextsynctoken","startingtoken","starttoken","skiptoken","deltatoken","resumptiontoken","scrolltoken","aftertoken","beforetoken"]),f=new Set(["auth","session","cookie","pin","sig"]);function p(e,t){return a(e).split("key"===t?/[[\]]+/:/[[\].]+/).map(e=>e.toLowerCase().replace(/[-_$+\s]/g,"")).filter(e=>""!==e)}function g(e,t){return!(h.has(e)||"page"===t&&f.has(e))&&(l.has(e)||u.has(e)||c.has(e)||d.test(e))}function y(e,t){return v(p(e,t),t)}function v(e,t){return e.some(e=>g(e,t))||e.length>1&&g(e.join(""),t)}var m=/(&|;(?=[^;&=#]+=|end$))/;function w(e){let t=e.replace(/\+/g," ");if(!/%/.test(t))return t;if(/%(?![0-9A-Fa-f]{2})/.test(t))return e;try{return decodeURIComponent(t)}catch{return e}}var b=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/)[^?#]*[?#]./i,k=/[&;?#][^&;=?#]+=/;function S(e,t,n){let r=e.indexOf("#"),i=-1===r?e:e.slice(0,r),s=i.indexOf("?"),o=-1===s?i:i.slice(0,s),a=-1===s?null:i.slice(s+1),l=-1===r?null:e.slice(r+1),u=A(o,t)+(null===a?"":`?${I(a,t,n,o)}`)+(null===l?"":`#${T(l,t,n,o)}`);return u===e?e:u}function x(e,t=!1){if(t){let t=e.search(/\s/);return-1===t?e.length:t}let n=0,r=0,i=0;for(let t=0;t<e.length;t++){let s=e[t];if(/[\s,;"'<>\\`]/.test(s))return t;if("("===s)n++;else if("["===s)r++;else if("{"===s)i++;else{if(")"===s&&0===n--)return t;if("]"===s&&0===r--)return t;if("}"===s&&0===i--)return t}}return e.length}function E(e,t){let n=e;for(let e=0;e<4;e++){let e=a(n);if(e===n)break;n=e}for(let e of n.matchAll(/(?:^|[?&;#])([^?&;#=/\s]+)=/g))if(y(e[1],t))return!0;return!1}function I(e,t,n=0,r=""){let i=e.split(t.whole?/(&)/:m),s=i.filter((e,t)=>t%2==0),o={path:r,pairs:s,depth:n};return s.map(e=>{let r=e.indexOf("=");if(-1===r)return!0===t.bare?.(e)?"[REDACTED]":e;let i=e.slice(0,r),s=e.slice(r+1);if(""===s)return e;let l=w(s),u=()=>`${i}=[REDACTED]`,c=t.before?.(i,s,o)??null;if(null!==c)return`${i}=${c}`;if(t.strict||(t.whole?function(e){let t=[],n=e.split(m);for(let e=0;e<n.length;e+=2){let r=n[e].indexOf("=");r>0&&t.push(n[e].slice(0,r))}return t}(e):[i]).some(e=>y(e,t.kind))||!0===t.value?.(i,s,l)){if(!0!==t.spaced)return u();let e=x(s,t.form),n=s.slice(e);return`${i}=${0!==e||t.form?"[REDACTED]":""}${t.tail?.(n)??n}`}if(n>=1&&(b.test(l)||k.test(l)))return"page"===t.kind||E(l,t.kind)?u():e;let d=function(e,t,n){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?R(e,t,n+1):e.startsWith("/")?S(e,t,n+1):k.test(e)?/[?#]/.test(e)?S(e,t,n+1):I(e,t,n+1):null}(l,t,n);return null!==d&&d!==l?t.whole?u():!0!==t.raw?`${i}=${encodeURIComponent(d)}`:s===l?`${i}=${d}`:encodeURIComponent(l)===s?`${i}=${encodeURIComponent(d)}`:u():a(l)!==l&&E(l,t.kind)?u():e}).map((e,t)=>(0===t?"":i[2*t-1])+e).join("")}function A(e,t){let n=e.split("/"),r=n.map(e=>e.split(";")[0]);return n.map((n,i)=>{if(!0===t.segment?.(n))return"[REDACTED]";let s=n.indexOf(";"),o=r[i],a=!0===t.head?.(e,o,i,r)?"[REDACTED]":o;return-1===s?a:a+n.slice(s).replace(/;([^;=]+)=([^;]*)/g,(e,n,r)=>{let i=!0===t.spaced?x(r,t.form):r.length;return i>0&&y(n,t.kind)?`;${n}=[REDACTED]${r.slice(i)}`:e})}).join("/")}function T(e,t,n,r=""){let i=e.indexOf("?");if(-1!==i){let s=e.slice(0,i);return`${A(s,t)}?${I(e.slice(i+1),t,n,`${r}/${s}`)}`}let s=e.indexOf("=");if(-1!==s&&!e.slice(0,s).includes("/"))return I(e,t,n,r);let o=-1===s?null:/^([^&;]*)([&;])/.exec(e);return null!==o?`${A(o[1],t)}${o[2]}${I(e.slice(o[0].length),t,n,`${r}/${o[1]}`)}`:A(e,t)}function R(e,t,n){if(t.whole||!0===t.raw||!_.test(e))return C(e,t,n);let r;try{r=new URL(e)}catch{return C(e,t,n)}let i=r.search.slice(1),s=r.hash.slice(1),o=A(r.pathname,t),a=r.search?I(i,t,n,r.pathname):"",l=r.hash?T(s,t,n,r.pathname):"";return o===r.pathname&&a===i&&l===s&&""===r.username&&""===r.password?e:`${r.protocol}//${r.host}`+o+(r.search?`?${a}`:"")+(r.hash?`#${l}`:"")}var _=/^(?:https?:|[a-z][a-z0-9+.-]*:[/\\]{2})/i;function C(e,t,n){let r=/^([a-z][a-z0-9+.-]*:)([/\\]*)([^/\\?#]*)/i.exec(e),[i,s,o,a]=r,l=""===o?-1:a.lastIndexOf("@"),u=s+o+a.slice(l+1)+S(e.slice(i.length),t,n);return u===e?e:u}function O(e,t){let n,r=e.length-e.trimStart().length,i=e.length-e.trimEnd().length,s=e.slice(r,e.length-i);return/^(?:javascript|vbscript|data|blob):/i.test(s)?e:(n=/^[a-z][a-z0-9+.-]*:/i.test(s)?R(s,t,0):S(s,t,0),n===s?e:e.slice(0,r)+n+e.slice(e.length-i))}var $=/[a-z][a-z0-9+.-]{0,31}:[/\\]{2}|(?<attr>\bcontent\s*=\s*(?:["']\s*)?\d[\d.]*\s*[;,]\s*url\s*=\s*["']?|\b(?:href|src|action|formaction|poster|cite|data|background|longdesc|content|data-src|data-href|xlink:href)\s*=\s*["']?|(?<![\w:.-])[\w:.-]{1,40}\s*=\s*["'](?=\.{0,2}\/|[?#]|[a-z][a-z0-9+.-]{0,31}:\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):)|\burl\(\s*["']?)(?=[^\s"'<>])/gi,D=/[\s"'<>\\^`{|}]/,N=/[a-z][a-z0-9+.-]{0,31}:\/\//iy;function z(e,t,n,r){let i=t,s=0,o=0;for(;i<e.length;i++){let t=e[i];if(D.test(t)||r&&","===t&&(N.lastIndex=i+1,N.test(e)))break;if(n)if("("===t)s++;else if("["===t)o++;else if(")"===t||"]"===t){if(0===(")"===t?s:o))break;")"===t?s--:o--}}return function(e,t,n){let r=0,i=0;for(let s=t;s<n;s++){let t=e[s];"("===t?r++:")"===t?r--:"["===t?i++:"]"===t&&i--}for(;n>t;){let t=e[n-1];if(")"===t){if(r>=0)break;r++}else if("]"===t){if(i>=0)break;i++}else if(!".,;:!?".includes(t))break;n--}return n}(e,t,i)}var L=/url\(\s*["']?/iy;function B(e){return{kind:"param",strict:e,whole:!0}}var U={left:"the page left or the capture stopped before redaction was ready","code-failed":"the redaction code could not load"},P="[REDACTED]",q=/^[A-Za-z]+(?:[-_][A-Za-z]+)*$/,j=/^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/,M=new Set(["code","devicecode"]);function K(e){return y(e,"key")}new Set([...M,"state"]);var W=/[a-zA-Z0-9.-]{1,253}\.[a-zA-Z]{2,63}/y;function F(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||46===e||95===e||37===e||43===e||45===e}var H=/(?<![A-Za-z0-9])(?:kep_[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprse]-[A-Za-z0-9-]{10,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36,}|whsec_[A-Za-z0-9+/=]{24,}|(?:AKIA|ASIA)[0-9A-Z]{16,}|AIza[0-9A-Za-z_-]{35,})/g,Z=/\b\d{3}-\d{2}-\d{4}\b/g,V=/(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g,J=/(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,X=/(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![\d.])/g;function G(e){if(e.length<13||e.length>19)return!1;let t="4"===e[0]&&(13===e.length||16===e.length||19===e.length),n=/^(5[1-5]|2[2-7])/.test(e)&&16===e.length,r=/^3[47]/.test(e)&&15===e.length,i=/^6(?:011|5)/.test(e)&&16===e.length,s=/^(?:35|3[068])/.test(e)&&e.length>=14&&e.length<=19;return!!(t||n||r||i||s)&&function(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let i=e.charCodeAt(r)-48;if(i<0||i>9)return!1;n&&(i*=2,i>9&&(i-=9)),t+=i,n=!n}return t%10==0}(e)}function Q(e,t,n){for(let r of e.matchAll(t))""!==r[0]&&n.push([r.index,r.index+r[0].length])}function Y(e,t){if(0===t.length)return e;t.sort((e,t)=>e[0]-t[0]||t[1]-e[1]);let n="",r=0,[i,s,o]=t[0];for(let a=1;a<=t.length;a++){let l=t[a];void 0!==l&&l[0]<s?(l[1]>s&&(s=l[1]),o=void 0):(n+=e.slice(r,i)+(o??P),r=s,void 0!==l&&([i,s,o]=l))}return n+e.slice(r)}function ee(e,t=[]){if(!e)return e;let n=[];return function(e,t,n){Q(e,J,n),Q(e,H,n),function(e,t){let n=0,r=e.indexOf("@");for(;-1!==r;){let i=Math.max(n,r-64),s=r;for(;s>i&&F(e.charCodeAt(s-1));)s--;if(s<r){W.lastIndex=r+1;let i=W.exec(e);if(i){n=r+1+i[0].length,t.push([s,n]),r=e.indexOf("@",n);continue}}r=e.indexOf("@",r+1)}}(e,n),Q(e,Z,n),Q(e,V,n),Q(e,X,n),function(e,t){for(let n of e.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g))G(n[0].replace(/[^0-9]/g,""))&&t.push([n.index,n.index+n[0].length])}(e,n);for(let r of t)Q(e,r,n)}(e,t,n),Y(e,n)}function te(e){return e&&Y(e,re(e))}var ne=/eyJ|kep_|gh[pousr]_|github_pat_|glpat-|xox[abprse]-|[sr]k_(?:live|test)_|sk-(?:proj|ant)-|npm_|whsec_|AKIA|ASIA|AIza/;function re(e){let t=[];return ne.test(e)&&(Q(e,J,t),Q(e,H,t)),t}JSON.stringify(P);var ie={kind:"param",strict:!1,whole:!1,raw:!0},se={...ie,spaced:!0,tail:e=>ce(e,oe)},oe={...ie,spaced:!0,list:!0},ae=/^(?=[^={}<>"'\\^`|]*(?:=|$))(?:(?:[a-z][a-z0-9+.-]*:\/|[a-z][a-z0-9-]*[+.][a-z0-9+.-]*:|localhost:\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\.{0,2}\/)[^\s?#]*[?#]|(?:[\w.~%-][\w.~%/-]*)?[?#][^\s=&#]+=|\.{0,2}\/[^\s?#;=]*;)/i,le=/^\S*/,ue=/^[^\r\n]*/gm;function ce(e,t=ie){let n=e.replace(ue,e=>ae.test(le.exec(e)[0])?O(e,t):e),r=function(e,t){let n=[];for(let[r,i]of function(e,t=!1){let n=[];$.lastIndex=0;for(let r=$.exec(e);null!==r;r=$.exec(e)){let i=r.index+(r.groups?.attr?.length??0);L.lastIndex=i;let s=void 0!==r.groups?.attr&&L.test(e);s&&(i=L.lastIndex);let o=r.groups?.attr??"",a=z(e,i,!/["']$/.test(o)||/^url\(/i.test(o)||s,t);"{"===e[a]&&a>i&&"$"===e[a-1]&&a--,a>i&&n.push([i,a]),$.lastIndex=Math.max(a,r.index+r[0].length,i+1)}return n}(e,!0===t.list)){let s=e.slice(r,i),o=O(s,t);o!==s&&n.push([r,i,o])}return n}(n,t);if(0===r.length)return he(n,t);let i="",s=0;for(let[e,t,o]of r)i+=n.slice(s,e)+o,s=t;return he(i+n.slice(s),t)}var de=/[a-z][a-z0-9+.-]{0,31}:(?:\\\/|\\u002[fF]){2}(?:[^\s"'<>\\^`{|}()[\]/]|\/(?![dgimsuvy]*(?![\w$]))|\\\/|\\u002[fF])*/gi;function he(e,t){return/:(?:\\\/|\\u002[fF])/.test(e)?e.replace(de,e=>{let n="",r=[];for(let t=0;t<e.length;){r.push(t);let i=fe.exec(e.slice(t,t+6));n+=null===i?e[t]:"/",t+=null===i?1:i[0].length}r.push(e.length);let i=O(n,t);if(i===n)return e;let s=0;for(;s<i.length&&i[s]===n[s];)s++;let o=0;for(;o<i.length-s&&o<n.length-s&&i[i.length-1-o]===n[n.length-1-o];)o++;let a=/\\\/|\\u002[fF]/.exec(e)[0];return e.slice(0,r[s])+i.slice(s,i.length-o).replace(/\//g,a)+e.slice(r[n.length-o])}):e}var fe=/^(?:\\\/|\\u002[fF])/;function pe(e){let t=ce(e,se),n=[];return function(e,t,n="text"){let r="code"===n?ve:"string"===n?me:"header"===n?we:ye,i="text"===n&&/<script/i.test(e)?function(e){let t=[],n=/<script\b/gi,r=/<\/script\s*>/gi;for(let i=n.exec(e);null!==i;i=n.exec(e)){let s=e.indexOf(">",i.index);if(-1===s)break;r.lastIndex=s+1;let o=r.exec(e),a=null===o?e.length:o.index;t.push([s+1,a]),n.lastIndex=a}return t}(e):[],s=0;r.lastIndex=0;for(let o=r.exec(e);null!==o;o=r.exec(e)){if(!y(o[2],"param"))continue;if(i.length>0&&(/^[ \t\r\f\v>]$/.test(o[1])||"#"===o[1]&&(!/[\w/%~-]/.test(e[o.index-1]??"")||e.startsWith("*/",o.index-2)||/(?:^|[^\w$/%~.-])(?:static|accessor)$/.test(e.slice(Math.max(0,o.index-9),o.index))))){for(;s<i.length&&i[s][1]<=o.index;)s++;if(s<i.length&&i[s][0]<=o.index)continue}let a=o.index+o[0].length;be.lastIndex=a;let l=be.exec(e);if(null===l)continue;"string"===n&&(ke.lastIndex=a,l=ke.exec(e)??l);let u=a+l[0].length;t.push([a,u]),r.lastIndex=u}}(t,n,"header"),Y(t,n)}var ge="...[truncated]",ye=/(^|[?&;\n>#]|(?<!\b(?:var|let|const)|[(){}])[ \t\r\f\v])([\w%-]*(?:\[[\w%-]*\][\w%-]*)*)=/g,ve=/(^|[?&;\n]|(?<=[\w/%~-])(?<!\*\/|(?:^|[^\w$/%~.-])(?:static|accessor))#)([\w%-]*(?:\[[\w%-]*\][\w%-]*)*)=/g,me=/(^|[?&]|(?<=[\w/%~-])(?<!\*\/|(?:^|[^\w$/%~.-])(?:static|accessor))#)([\w%-]*(?:\[[\w%-]*\][\w%-]*)*)=/g,we=/(^|[?&;,\s]|(?<=[\w/%~-])#)([\w%-]*(?:\[[\w%-]*\][\w%-]*)*)=/g,be=/(?:[^\s&"'`<>\\,;(){}[\]$]|\$(?!\{))+/y,ke=/[^&]+/y,Se=B(!1),xe=B(!0),Ee={scanned:0};function Ie(e){return 47===e||38===e||59===e||63===e||35===e}function Ae(e,t){let n=e.length,r=0;for(;r<=n;){let i,s=r,o=0;for(;s<n&&61!==(o=e.charCodeAt(s))&&!Ie(o);)s++;Ee.scanned+=s-r+1,i=s<n&&61===o?s>r?t(r,s):s+1:s;let a=i;for(;i<n&&!Ie(e.charCodeAt(i));)i++;if(Ee.scanned+=i-a+1,i>=n)return;r=i+1}}function Te(e,t,n){let r=t;for(;r<e.length;r++){let t=e.charCodeAt(r);if(38===t||59===t||35===t||!n&&63===t)break}return Ee.scanned+=r-t+1,r}function Re(e){let t=[];return Ae(e,(n,r)=>{let i=Te(e,r+1,!0);return t.push([e.slice(n,r),e.slice(r+1,i)]),i}),t}function _e(e,t,n=!1){let r="",i=0;return Ae(e,(s,o)=>{let a=p(e.slice(s,o),"page"),l=o+1;if(!(v(a,"page")||n&&Ye(a,e.slice(l,l+256))))return l;let u=Te(e,l,t);return r+=e.slice(i,l)+"[REDACTED]",i=u,u}),r+e.slice(i)}function Ce(e,t){let n=e.indexOf("?");return-1===n?_e(e,!1):`${_e(e.slice(0,n),!1)}?${_e(e.slice(n+1),!0,t)}`}var Oe=/^!?\//;function $e(e){return!(e.length<8)&&Number(/[a-z]/.test(e))+Number(/[A-Z]/.test(e))+Number(/\d/.test(e))>=2&&!/^[A-Z][a-z]+$/.test(e)&&!/^[A-Za-z][a-z]*(?:[-_](?:[A-Za-z][a-z]*|\d+))+$/.test(e)&&!/^[A-Za-z][a-z]{2,}(?:[A-Z][a-z]{2,})+$/.test(e)}function De(e,t=!0){return(t?/^(?:\/|[a-z][a-z\d+.-]*:\/\/)/i:/^[a-z][a-z\d+.-]*:\/\//i).test(a(e))}function Ne(e){return a(e).replace(/([a-z\d])([A-Z])/g,"$1 $2").split(/[\s\-_.]+/).filter(e=>""!==e).map(e=>e.toLowerCase())}var ze=new Set(["reset","resets","verify","unlock","activate","invite","forgot","forgotten","recover","recovery"]),Le=new Set(["passwordreset","passwordresets","resetpassword","verifyemail","emailverification","magiclink","magiclogin","emaillogin","loginlink","lostpassword","setpassword","createpassword"]),Be=new Set(["setpassword","createpassword","resetpassword","passwordreset","forgotpassword","forgottenpassword","lostpassword","verifyemail","emailverification"]),Ue=new Set(["sent","done","success","complete","new","error","expired","failed","invalid"]),Pe=new Set(["confirm","confirmation","confirmations","invites","invitation","invitations","verification","verifications","activation","activations","password","passwords","signup","login"]),qe=new Set(["email","account","registration","registrations","signup"]),je=new Set(["accept","link","new","old","sign","up","email","account","registration","admin","change","php","asp","aspx","htm","html","jsp","cgi"]),Me=e=>e.some(e=>qe.has(e))||e.join("").includes("signup");function Ke(e,t){let n=Ne(e),r=n.join("");if(Le.has(r))return 2;Pe.has(r)&&(n=[r]);let i=0;for(let e of n)if(ze.has(e))i=2;else if(Pe.has(e))i||=1;else if(!je.has(e))return 0;return 1===i&&(n.includes("accept")||n.includes("confirm")&&(Me(n)||Me(Ne(t))))?2:i}function We(e){return/^(?:\d+|[\da-f]{24}|[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12})$/i.test(e)||/^(?:[0-7][\dA-HJKMNP-TV-Z]{25}|c[a-z\d]{24})$/.test(e)}function Fe(e){if(e.length%4==1||!/^[\w-]+$/.test(e))return!1;try{return/^[\x20-\x7e]+$/.test(atob(e.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((e.length+3)%4)))}catch{return!1}}function He(e){return e.length<=4||Ze(e)}function Ze(e){return Ne(e).every(e=>e.startsWith("confirm")||"accept"===e||"edit"===e)}function Ve(e,t){let n=e[t]??"";return Be.has(Ne(e[t-1]??"").join(""))&&!Ze(n)&&!Ue.has(n.toLowerCase())&&!/\.[A-Za-z][A-Za-z\d]{0,4}$/.test(n)&&!(We(n)&&""!==(e[t+1]??""))}var Je=new Set(["cb","auth","sso","signin","authorize","authorized","redirect"]);function Xe(e){return Ne(e).some(e=>e.startsWith("invit"))}function Ge(e,t){return/^(?:rp|resetpass)$/.test(t)||e.some(e=>e.some(e=>0!==Ke(e,"")))}function Qe(e){return e.find(([e])=>p(e,"page").includes("action"))?.[1]??""}function Ye(e,t){return e.some(e=>/^(?:key|t|hash|code)$/.test(e))&&!De(t,!1)}function et(e){let t=Ne(e);return t.length>0&&t.every(e=>"accept"===e||"join"===e)}var tt="a route is `/`-separated segments from the path's start, each a literal, `*` (any one segment) or `:name` (the value it names), with no `?` or `#`; a secret route names at least one `:name`, a keep route has at least one literal";function nt(e,t=!1){if("string"!=typeof e||!/^\/[^?#]*$/.test(e))return null;let n=e.split("/").filter(e=>""!==e),r=e=>/^:\w+$/.test(e);return n.every(e=>"*"===e||r(e)||!/[:*]/.test(e))&&n.some(e=>t?"*"!==e&&!r(e):r(e))?n:null}var rt={secret:[],keep:[]},it=new Set,st=0;function ot(e,t){return"*"===e||":"===e[0]||a(t).toLowerCase()===a(e).toLowerCase()}function at(e,t){let n=[];return e.every((e,r)=>{let i=t[r];return void 0!==i&&(":"===e[0]&&n.push([i,t[r-1]??"",r]),ot(e,i))})?n:null}function lt(e,t){return rt.keep.some(n=>t<n.length&&"*"!==n[t]&&":"!==n[t][0]&&n.slice(0,t+1).every((t,n)=>ot(t,e[n])))}function ut(e){let t=!1,n=new Set;for(let r of rt.keep){let i=at(r,e);if(null!==i){0===i.length&&(t||=r.length===e.length&&!r.includes("*"));for(let[e]of i)n.add(e)}}let r=[];for(let t of rt.secret)for(let[n,i,s]of at(t,e)??[])!lt(e,s)&&ct(n)&&r.push([n,i]);return{secret:r,kept:n,own:t}}function ct(e){let t=e;for(let e=0;e<=dt;e++){let e=a(t);if(e===t)return/[\p{L}\p{N}]/u.test(t);t=e}return!1}var dt=16;function ht(e){let t=e.indexOf("#"),n=[e.slice(0,-1===t?e.length:t).replace(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*/i,"")],r=-1===t?"":e.slice(t+1);return Oe.test(r)&&n.push(r.replace(/^!/,"")),n.map(e=>e.split(/[?#]/)[0].split("/").map(e=>e.split(";")[0]))}function ft(e,t,n){let r=e.get(t);void 0===r&&e.set(t,r=new Set),r.add(function(e){return wt(a(e))}(n))}function pt(e,t,n,r,i,s){let o=ht(e);for(let e of o){let o=e.length,{secret:l,kept:u,own:c}=ut(e.filter(e=>""!==e));for(let[e,s]of l)n.add(e),ft(r,e,s),0===t&&ft(i,e,s);for(let t=0;t<o;t++){let i=Ke(e[t],e[t-1]??"");if(0===i)continue;let l=Xe(e[t]),d=e[t+1];Ve(e,t+1)&&!u.has(d)&&!c&&(n.add(d),$e(a(d))||(r.has(d)||s.add(d),ft(r,d,e[t])));let h="",f="",p=t+1;for(;p<o;p++){let t=e[p],n=e[p+1]??"";if(We(t)||(2===i||n.length>=16&&$e(n))&&Fe(t)){f=t;continue}if(t.length>=(2===i?16:20)&&$e(t)){h=t;break}if(l&&$e(t)){f=t;continue}let r=Ke(t,e[p-1]);if(r>i)i=r,f="";else{if(""!==f&&et(t)){h=f;break}if(!He(t))break}}""===h&&2===i&&p===o&&(h=f),""!==h&&!u.has(h)&&!c&&n.add(h),t=""===h?p-1:p}}let l=Re(e).map(([e,t])=>[p(e,"page"),t]),u=e=>l.find(([t])=>t.includes(e))?.[1]??"",c=Ge(o,u("action")),d=""!==u("organization"),h=u("code"),f=u("state"),g=!De(h)&&(h.length>=10&&$e(f)&&!/^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/.test(f)&&!De(f)||h.length>=20&&$e(h)&&o.some(e=>e.some(e=>/callback|oauth/i.test(e)||[...Ne(e),Ne(e).join("")].some(e=>Je.has(e)))));for(let[e,o]of l){let l=g&&(e.includes("code")||e.includes("state"));if((l||v(e,"page")||c&&Ye(e,o)||d&&e.includes("invitation")||e.includes("ticket")&&/^(?:ST|PT|TGT)-/.test(o))&&!De(o,l)){n.add(o);continue}let u=a(o);t<2&&(/[?#=]/.test(u)||De(u))&&pt(u,t+1,n,r,i,s)}}function gt(e){try{return new URL(e).origin}catch{return""}}function yt(e){return mt(e)[0]}var vt=["",[],!1,null];function mt(e){if(vt[0]===e)return[vt[1],vt[2],vt[3]];let t=new Set,n=new Map,r=new Map,i=new Set,s=e.indexOf("#"),o=-1===s?e:e.slice(0,s),l=-1===s?"":e.slice(s+1),u=Oe.test(l),c=o.length+(u?l.length:0)>65536;if(c)for(let i of ht(e))for(let[e,s]of ut(i.filter(e=>""!==e)).secret)t.add(e),ft(n,e,s),ft(r,e,s);else pt(e,0,t,n,r,i);let d=c,h=gt(e),f=new Set,p=[],g=0,y=(e,t)=>null!==t&&!0===r.get(e)?.has(t)||(g<32?(g++,!0):(d=!0,!1));for(let e of[...r.keys(),...[...t].filter(e=>!r.has(e))]){let t=n.get(e),r=void 0===t?void 0:[...t].filter(t=>y(e,t));if(0===r?.length||void 0===r&&!y(e,null))break;if(void 0!==r){let t=a(e),n=t.length>=6&&!i.has(e),s=[];for(let t=e,n=0;n<Nt;n++)s.push(t=encodeURIComponent(t));for(let i of new Set([e,t,...s,encodeURIComponent(t),t.replace(/[\u0080-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)])){if(""===i)continue;let e=!h.includes(i),t=e&&$e(i)&&!De(i,!1);if(n&&t&&p.push({kind:0,value:i}),n&&e)p.push({kind:1,value:i});else for(let e of r)p.push({kind:2,value:i,before:e})}continue}f.add(e);for(let t=e.lastIndexOf("/"),n=0;t>0&&n<4;t=e.lastIndexOf("/",t-1),n++)f.add(e.slice(0,t));f.add(encodeURIComponent(e));for(let t of[e,e.replace(/\+/g," ")])try{let e=decodeURIComponent(t);f.add(e),f.add(encodeURIComponent(e));for(let t=e.lastIndexOf("/"),n=0;t>0&&n<4;t=e.lastIndexOf("/",t-1),n++)f.add(e.slice(0,t))}catch{}}for(let e of f)$e(e)&&!De(e,!1)&&!h.includes(e)&&p.push({kind:0,value:e});return p.sort((e,t)=>t.value.length-e.value.length),vt=[e,p,d,en(p)],[p,d,vt[3]]}function wt(e){if(!/[A-Z]/.test(e))return e;if(qt.lowered+=e.length,!/[^\0-\x7f]/.test(e))return e.toLowerCase();let t=new Uint16Array(Math.min(e.length,bt)),n="";for(let r=0;r<e.length;r+=bt){let i=Math.min(bt,e.length-r);for(let n=0;n<i;n++){let i=e.charCodeAt(r+n);t[n]=i>=65&&i<=90?i+32:i}n+=String.fromCharCode(...t.subarray(0,i))}return n}var bt=8192;function kt(e,t){let n=new Int32Array(t.length);for(let e=1,r=0;e<t.length;e++){for(;r>0&&t.charCodeAt(e)!==t.charCodeAt(r);)r=n[r-1];t.charCodeAt(e)===t.charCodeAt(r)&&r++,n[e]=r}let r=[];for(let i=0,s=0;i<e.length;i++){for(;s>0&&e.charCodeAt(i)!==t.charCodeAt(s);)s=n[s-1];e.charCodeAt(i)===t.charCodeAt(s)&&s++,s===t.length&&(r.push(i-s+1),s=n[s-1])}return r}var St=1/0,xt=0;function Et(e){let t=St;St=1/0;try{return e()}finally{St=t}}function It(e){if(xt+e>St)throw new rn(xt+e,St)}function At(e,t,n="[redacted]"){if(e.includes(t))return!0;if(!/[[\]]/.test(t))return!1;let r=t.split(n),i=r[0],s=i.lastIndexOf("[");s>=0&&n.startsWith(i.slice(s))&&(r[0]=i.slice(0,s));let o=r[r.length-1],a=o.indexOf("]");return a>=0&&n.endsWith(o.slice(0,a+1))&&(r[r.length-1]=o.slice(a+1)),r.every(t=>e.includes(t))}var Tt=10;function Rt(e,t){let n=e=>e.length>Tt&&/[[\]]/.test(e);if(e.plain.some(e=>n(e)&&At(t,e,"[REDACTED]")))return!0;let r=wt(t);return[...e.bounded,...e.words.map(({value:e})=>e)].some(e=>n(e)&&At(r,e))}function _t(e,t,n,r,i=!1){let s=[],o=0,a=Tt-n.length;for(let l of kt(t,n))l<o||!r(l,l+n.length)||(s.push(l),o=l+n.length,i&&It(e.length+s.length*a));if(0===s.length)return[e,()=>t];let l,u=(e,t)=>{let r=[],i=0;for(let t of s)r.push(e.slice(i,t)),i=t+n.length;return r.push(e.slice(i)),r.join(t)};return[u(e,"[REDACTED]"),()=>l??=u(t,"[redacted]")]}var Ct=/[A-Za-z0-9]/,Ot=/(?:%(?:25)*[\da-f]{2}|(?:\\|%(?:25)*5c)(?:[nrtbf]|u[\da-f]{4}))$/i;function $t(e,t,n){return(0===t||!Ct.test(e[t-1])||Ot.test(e.slice(Math.max(0,t-16),t)))&&(n===e.length||!Ct.test(e[n]))}var Dt=[["%25252f",3],["%252f",2],["%2f",1],["\\/",0],["/",0]],Nt=Math.max(...Dt.map(([,e])=>e)),zt=/[/\\?#\s"<>`{}|^[\]]/,Lt=/[!$&'()*+,;=:@]/,Bt=64;function Ut(e,t,n){return Dt.find(([r,i])=>i<=n&&t>=r.length&&e.startsWith(r,t-r.length))}function Pt(e,t,n){if(";"===e[t])return!0;for(let r=1;r<=n;r++)if(e.startsWith(`%${"25".repeat(r-1)}3b`,t))return!0;return!1}var qt={pieces:0,strings:0,scanned:0,lowered:0};function jt(e,t,n,r){if(n!==e.length&&/[a-z0-9_~-]/.test(e[n]))return!1;let i=Ut(e,t,3);if(void 0===i)return!1;let[s,o]=i,l=function(e,t,n){let r=t;for(;;){let t=Ut(e,r,n);if(void 0===t)return r;r-=t[0].length,qt.scanned++}}(e,t-s.length,o);return(l===t-s.length||!function(e,t){return 0===t||zt.test(e[t-1])||Lt.test(e[t-1])||/(?::|%(?:25)*3a)$/.test(e.slice(Math.max(0,t-9),t))}(e,l))&&(!!r.befores.has("")||0!==r.longest&&function(e,t,n,r){let i=t;for(;i>0&&!zt.test(e[i-1])&&void 0===Ut(e,i,n);)i--;qt.scanned+=t-i;let s=t,o="",l=!1;for(let u=t;u>=i;u--){if(u<t&&Pt(e,u,n)&&(s=u,o="",l=!1),l||u!==i&&!Lt.test(e[u-1]))continue;let c=e.slice(u,s);for(let e=0;e<=n;e++)c=a(c);if(qt.pieces++,o=wt(c)+o,s=u,o.length>r.longest)l=!0;else if(r.lengths.has(o.length)&&r.befores.has(o))return!0}return!1}(e,l,o,r))}function Mt(e,t){if(!Kt(e,t))return e;if(/^[ \t\n\r]*[{[]/.test(e)){let n=Vt(e,t);if(null!==n)return n}return Yt(e,t)}function Kt(e,t){return!!Wt(e,t)||e.includes("\\")&&Wt(Ft(e),t)}function Wt(e,t){if(t.plain.some(t=>e.includes(t)))return!0;if(0===t.bounded.length&&0===t.words.length)return!1;let n=wt(e);return t.bounded.some(e=>n.includes(e))||t.words.some(({value:e})=>n.includes(e))}function Ft(e){return e.replace(/\\+u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\\+\//g,"/")}var Ht=/"(?:[^"\\]|\\[\s\S])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}]/g,Zt=/[ \t\n\r]*:/y;function Vt(e,t){try{JSON.parse(e)}catch{return null}let n=function(e,t){let n=wt(e),r=e.includes("\\")?wt(Ft(e)):n,i=e=>n.includes(wt(e))||n.includes(wt(function(e){return JSON.stringify(e).slice(1,-1).replace(/[\u0080-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(e)))||r.includes(wt(e));return{...t,plain:t.plain.filter(i),bounded:t.bounded.filter(i),words:t.words.filter(({value:e})=>i(e))}}(e,t),r=[],i=[];for(let t of e.matchAll(Ht)){let n=t[0];"{"===n?(i.push(r.length),r.push(new Set)):"}"===n?i.pop():'"'===n[0]&&i.length>0&&(Zt.lastIndex=t.index+n.length,Zt.test(e)&&r[i[i.length-1]].add(JSON.parse(n)))}let s=xt,o="",a=0,l=0,u=[];for(let t of e.matchAll(Ht)){let i=t[0];if("{"===i){u.push(new Set(r[l++]));continue}if("}"===i){u.pop();continue}let c=i;if('"'===i[0]){let r,l=JSON.parse(i);xt=s+o.length+(t.index-a);try{r=Mt(l,n)}finally{xt=s}Zt.lastIndex=t.index+i.length;let d=Zt.test(e)?u[u.length-1]:void 0;if(void 0!==d&&r!==l){let e=r;for(let t=2;d.has(r);t++)r=`${e}#${t}`;d.add(r)}r!==l&&(c=JSON.stringify(r))}else Et(()=>Yt(i,n))!==i&&(c='"[REDACTED]"');c!==i&&(o+=e.slice(a,t.index)+c,a=t.index+i.length,It(o.length))}return o+e.slice(a)}function Jt(e){let t="",n=[],r=0;for(let i of e.matchAll(/\\+u([0-9a-fA-F]{4})|\\+\//g))t+=e.slice(r,i.index),n.push(t.length,i.index+i[0].length),t+=void 0===i[1]?"/":String.fromCharCode(parseInt(i[1],16)),r=i.index+i[0].length;return{text:t+e.slice(r),escapes:n}}function Xt(e,t){let n=0,r=e.length/2;for(;n<r;){let i=n+r>>1;e[2*i]<t?n=i+1:r=i}if(0===n)return t;let i=2*(n-1);return e[i+1]+(t-e[i]-1)}function Gt(e,t,n=!1){let r=[],i=[],s=(e,t,s)=>{let o=new Int32Array(e.length),a=0,l=t>Tt,u=-1,c=-1;for(let r of e)!n&&s(r)?o[a++]=r:l&&(r<c||(u>=0&&i.push(u,c),u=r),c=r+t);u>=0&&i.push(u,c),a>0&&r.push({at:o.subarray(0,a),length:t})};for(let n of t.plain)s(kt(e,n),n.length,()=>!0);let o=wt(e);for(let n of t.bounded)s(kt(o,n),n.length,t=>$t(e,t,t+n.length));for(let e of t.words)s(kt(o,e.value),e.value.length,t=>jt(o,t,t+e.value.length,e));return{lists:r,slack:Qt(i)}}function Qt(e){if(0===e.length)return 0;let t=Array.from({length:e.length/2},(e,t)=>t).sort((t,n)=>e[2*t]-e[2*n]),n=0,r=e[2*t[0]],i=e[2*t[0]+1],s=()=>{i-r>Tt&&(n+=i-r-Tt)};for(let n of t){let t=e[2*n],o=e[2*n+1];t<i?o>i&&(i=o):(s(),r=t,i=o)}return s(),n}function Yt(e,t){e=function(e,t){let n=St!==1/0&&xt+Tt*e.length>St,{text:r,escapes:i}=e.includes("\\")?Jt(e):{text:e,escapes:[]},s=Gt(r,t),{lists:o}=s;if(0===o.length)return e;let a=n&&!Rt(t,e),l=s.slack+(a&&i.length>0?Gt(e,t,!0).slack:0),u=new Int32Array(o.length),c=e=>o[e].at[u[e]],d=[],h=(e,t)=>{let n=d[e];d[e]=d[t],d[t]=n},f=e=>{for(;;){let t=2*e+1,n=e;if(t<d.length&&c(d[t])<c(d[n])&&(n=t),t+1<d.length&&c(d[t+1])<c(d[n])&&(n=t+1),n===e)return;h(e,n),e=n}};for(let e=0;e<o.length;e++)d.push(e);for(let e=(d.length>>1)-1;e>=0;e--)f(e);let p=[],g=0,y=!1,v=0;for(;d.length>0;){let t=d[0],n=c(t),r=Xt(i,n),s=Xt(i,n+o[t].length);if(u[t]=u[t]+1,u[t]>=o[t].at.length&&(d[0]=d[d.length-1],d.pop()),d.length>0&&f(0),!(s<=g)){if(y&&r<=g){g=s;continue}v+=r-g+Tt,a&&It(v-l),p.push(e.slice(g,r),"[REDACTED]"),g=s,y=!0}}return a&&It(v+e.length-g-l),p.push(e.slice(g)),p.join("")}(e,t);for(let n of t.plain)e.includes(n)&&(e=e.split(n).join("[REDACTED]"));let n=wt(e),r=()=>n,i=[...t.bounded,...t.words.map(({value:e})=>e)],s=new Array(i.length);for(let e=i.length-1,t=!0;e>=0;e--){let r=i[e];t=t&&(r.length<=Tt||!At(n,r)),s[e]=t}let o=0;for(let n of t.bounded){if(r().includes(n)){let t=e;[e,r]=_t(e,r(),n,(e,n)=>$t(t,e,n),s[o])}o++}for(let n of t.words){if(r().includes(n.value)){let t=r();[e,r]=_t(e,t,n.value,(e,r)=>jt(t,e,r,n),s[o])}o++}return e}function en(e){if(0===e.length)return null;let t=(e,t)=>t.length-e.length,n=[],r=[],i=new Map;for(let t of e){let e=wt(t.value);if(0===t.kind)n.push(t.value);else if(1===t.kind)r.push(e);else{let n=i.get(e);void 0===n&&i.set(e,n=new Set),n.add(t.before.length>Bt?"":t.before)}}n.sort(t),r.sort(t);let s=[...i].map(([e,t])=>{let n=new Set([...t].filter(e=>""!==e).map(e=>e.length));return{value:e,befores:t,lengths:n,longest:0===n.size?0:Math.max(...n)}}).sort((e,t)=>t.value.length-e.value.length);return{json:n.map(e=>JSON.stringify(e).slice(1,-1)),jsonLower:[...r,...s.flatMap(({value:e})=>Dt.map(([t])=>t+e))].map(e=>JSON.stringify(e).slice(1,-1)),plain:n,bounded:r,words:s}}var tn=new Set(["type","rel","method","enctype","autocomplete","inputmode","enterkeyhint","dir","role","crossorigin","referrerpolicy","loading","decoding","fetchpriority","contenteditable","draggable","spellcheck","translate"]),nn=class{constructor(e){this.page=e}styles=new Map;texts=new Map;gone(e){return void 0===this.page||!this.page.present(e)}get size(){let e=0;for(let t of this.styles.values())e+=t.size;return this.styles.size+this.texts.size+e}addText(e,t){this.dropText(e),this.texts.set(e,t),this.styles.get(t)?.add(e),this.page?.note(e)}dropText(e){let t=this.texts.get(e);void 0!==t&&this.styles.get(t)?.delete(e),this.texts.delete(e)&&this.page?.forget(e)}drop(e){let t=this.styles.get(e);if(void 0!==t)for(let e of t)this.texts.delete(e)&&this.page?.forget(e);this.styles.delete(e)&&this.page?.forget(e),this.dropText(e)}observe(e){if(!ln(e)||!ln(e.data))return;let t=e.data;if(2===e.type){for(let e of[...this.styles.keys(),...this.texts.keys()])this.page?.forget(e);return this.styles.clear(),this.texts.clear(),void this.walk(t.node,null)}if(3!==e.type||0!==t.source)return;let n=Array.isArray(t.removes)?t.removes:[];for(let e of n)ln(e)&&"number"==typeof e.id&&this.gone(e.id)&&this.drop(e.id);let r=Array.isArray(t.adds)?t.adds.filter(ln):[];for(let e of r)this.walk(e.node,null);for(let e of r){let t=e.node;ln(t)&&3===t.type&&"number"==typeof t.id&&("number"==typeof e.parentId&&this.styles.has(e.parentId)?this.addText(t.id,e.parentId):this.dropText(t.id))}n.length>0&&void 0!==this.page&&this.prune()}prune(){for(let e of this.styles.keys())this.gone(e)&&this.drop(e);for(let e of this.texts.keys())this.gone(e)&&this.dropText(e)}walk(e,t){let n=[[e,t]],r=new Set;for(;n.length>0;){let[e,t]=n.pop();if(r.has(e)||(r.add(e),!ln(e)||"number"!=typeof e.id))continue;let i=e.id,s=2===e.type&&"string"==typeof e.tagName&&"style"===e.tagName.toLowerCase();if(s&&!this.styles.has(i)&&(this.styles.set(i,new Set),this.page?.note(i)),3===e.type&&null!==t&&this.addText(i,t),Array.isArray(e.childNodes))for(let t of e.childNodes)n.push([t,s?i:null])}}recordsIn(e){let t=new Set;if(!ln(e)||!ln(e.data))return t;let n=e.data,r=[];if(2===e.type)r.push(n.node);else if(3===e.type&&0===n.source){if(Array.isArray(n.adds))for(let e of n.adds)ln(e)&&r.push(e.node);if(Array.isArray(n.texts))for(let e of n.texts)ln(e)&&"number"==typeof e.id&&this.texts.has(e.id)&&t.add(e)}for(;r.length>0;){let e=r.pop();ln(e)&&(3===e.type&&"number"==typeof e.id&&this.texts.has(e.id)&&t.add(e),Array.isArray(e.childNodes)&&r.push(...e.childNodes))}return t}},rn=class extends Error{constructor(e,t){super(`the scrubbed event passed ${t} units (at least ${e})`),this.atLeast=e,this.cap=t,this.name="ScrubOverCap"}};function sn(e,t){if(0===t.length)return 0;let n=new Int32Array(t.length);for(let e=1,r=0;e<t.length;e++){for(;r>0&&t.charCodeAt(e)!==t.charCodeAt(r);)r=n[r-1];t.charCodeAt(e)===t.charCodeAt(r)&&r++,n[e]=r}let r=0;for(let i=0,s=0;i<e.length;i++){for(;s>0&&e.charCodeAt(i)!==t.charCodeAt(s);)s=n[s-1];e.charCodeAt(i)===t.charCodeAt(s)&&s++,s===t.length&&(r++,s=n[s-1])}return r}function on(e,t,n){if(St===1/0||xt+e.length<=St||"body"===t||"text"===t&&/^[ \t\n\r]*[{[]/.test(e)||"css"===t&&e.includes("\\"))return;if(!e.includes("\\")&&function(e,t){let n=e=>e.length>Tt;if(e.plain.some(e=>n(e)&&At(t,e,"[REDACTED]"))||e.plain.some(e=>t.includes(e)))return!1;let r=[...e.bounded,...e.words.map(({value:e})=>e)],i=r.filter(n),s=r.filter(e=>/[^a-z0-9]/.test(e));if(0===i.length&&0===s.length)return!0;let o=wt(t);return!i.some(e=>At(o,e))&&!s.some(e=>o.includes(e))}(n,e))return void It(e.length);let r=function(e,t){if(Rt(t,e))return null;let n=e.includes("\\"),r=n?Jt(e).text:e,i=n?[r,e]:[r],s=r.length;for(let e of i){let n=wt(e);for(let n of t.plain)s-=sn(e,n)*n.length;for(let e of t.bounded)s-=sn(n,e)*e.length;for(let{value:e}of t.words)s-=sn(n,e)*e.length}return s}(e,n);null!==r&&It(r)}function an(e,t,n="custom",r,i){if("dom"===n&&r?.observe(e),null===t)return e;let s;try{s=JSON.stringify(e)}catch{return e}let o=s;if(void 0===o||!function(e,t){if(t.json.some(t=>e.includes(t)))return!0;let n=wt(e);if(t.jsonLower.some(e=>n.includes(e)))return!0;if(!e.includes("\\"))return!1;let r=Ft(e);if(t.plain.some(e=>r.includes(e)))return!0;let i=wt(r);return t.bounded.some(e=>i.includes(e))||t.words.some(({value:e})=>i.includes(e))}(o,t))return e;let a=JSON.parse(o);if("string"==typeof a)return qt.strings++,g(0,()=>(on(a,"text",t),Mt(a,t)));let l="dom"===n&&void 0!==r?r.recordsIn(a):new Set,u="dom"===n&&ln(a)&&3===a.type&&ln(a.data)&&13===a.data.source,c=(e,t,r,i,s)=>"network"===n?!s||"method"!==t&&"type"!==t?!s||"requestBody"!==t&&"responseBody"!==t?"text":"body":"keep":"dom"!==n?"text":"tagName"===t||u&&"property"===t||i&&tn.has(t)?"keep":r||i&&"style"===t||"_cssText"===t||"rule"===t||("replace"===t||"replaceSync"===t)&&8===e.source||u&&"value"===t||("textContent"===t||"value"===t)&&l.has(e)?"css":"text",d=new Map,h=![...t.plain,...t.bounded,...t.words.map(e=>e.value)].some(e=>e.includes("#")),f=0,p=e=>{if(f+=e.length,void 0!==i&&f>i)throw new rn(f,i);return e};function g(e,t){St=i??1/0,xt=e;try{return t()}finally{St=1/0,xt=0}}let y=(e,n)=>{if("keep"===n)return e;if("text"===n&&h){let t=e.indexOf("#");if(t>0&&!/^[ \t\n\r]*[{[]/.test(e))return y(e.slice(0,t),n)+y(e.slice(t),n)}on(e,n,t);let r=function(e,t){let n=`${e}\0${t}`;if(n.length<=16383)return n;let r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619);return`${e}\x01${t.length}\0${r>>>0}`}(n,e),i=d.get(r),s=i?.find(([t])=>t===e);if(void 0!==s)return s[1];qt.strings++;let o="css"===n?function(e,t){if(!Kt(e,t))return e;for(let n of t.plain)e.includes(n)&&(e=e.split(n).join("[REDACTED]"));let n="",r=0;return function(e,t){let n=e.length,r={},i=(t,i)=>{let s=r[i]??=new Int32Array(n+2).fill(-2),o=[],a=t,l=-1;for(;!(a>=n);){if(-2!==s[a]){l=s[a];break}o.push(a),qt.scanned++;let t=e[a];if(t===i){l=a+1;break}a+="\\"===t?2:1}for(let e of o)s[e]=l;return l},s=-1,o=t=>{for(s<t&&(s=t);s<n&&!")\"'".includes(e[s]);)qt.scanned++,s++;return s},a=t=>{let r=t;for(;r<n&&/\s/.test(e[r]);)qt.scanned++,r++;return r},l=0;for(;l<n;){qt.scanned++;let r=e[l];if("/"===r&&"*"===e[l+1]){let r=e.indexOf("*/",l+2),i=r<0?n:r+2;qt.scanned+=i-l,t(l,i),l=i;continue}if(("u"===r||"U"===r)&&"url("===e.slice(l,l+4).toLowerCase()){let n=a(l+4),r=e[n],s=-1;if('"'===r||"'"===r){let t=i(n+1,r);if(t>=0){let n=a(t);")"===e[n]&&(s=n+1)}}else{let t=o(l+4);")"===e[t]&&(s=t+1)}if(s>=0){t(l,s),l=s;continue}}if('"'===r||"'"===r){let e=i(l+1,r);if(e>=0){t(l,e),l=e;continue}}l++}}(e,(i,s)=>{let o=e.slice(i,s);n+=e.slice(r,i)+(o.startsWith("/*")?function(e,t){let n=e.length>=4&&e.endsWith("*/");return`/*${Yt(e.slice(2,n?-2:void 0),t)}${n?"*/":""}`}(o,t):Yt(o,t)),It(n.length),r=s}),n+e.slice(r)}(e,t):"body"===n?function(e,t){return Kt(e,t)?Vt(e,t)??Yt(e,t):e}(e,t):Mt(e,t);return void 0!==i?i.push([e,o]):d.set(r,[[e,o]]),o},v=[{node:a,css:!1,attributes:!1,names:"custom"===n,root:!0}];for(;v.length>0;){let{node:e,css:r,attributes:i,names:s,root:o}=v.pop();if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=e[t];"string"==typeof i?e[t]=p(g(f,()=>y(i,r?"css":"text"))):null!==i&&"object"==typeof i&&v.push({node:i,css:r,attributes:!1,names:"custom"===n,root:!1})}else if(ln(e))for(let a of Object.keys(e)){let l=e[a];if("dom"===n&&s&&!a.startsWith("rr_")&&"_cssText"!==a&&t.plain.some(e=>a.includes(e))){delete e[a];continue}let u=c(e,a,r,i,o);if("string"==typeof l)e[a]=p(g(f,()=>y(l,u)));else if(null!==l&&"object"==typeof l){let e="dom"===n&&"attributes"===a;v.push({node:l,css:"css"===u,attributes:e,names:"custom"===n||e||"dom"===n&&i&&"style"===a||"network"===n&&o&&("requestHeaders"===a||"responseHeaders"===a),root:!1})}if(!s||a.startsWith("rr_")||"_cssText"===a)continue;let d=a;for(let e of t.plain)d.includes(e)&&(d=d.split(e).join("[REDACTED]"));if(d===a)continue;let h=e[a];delete e[a];let m=d;for(let t=2;Object.prototype.hasOwnProperty.call(e,m);t++)m=`${d}#${t}`;e[m]=h}}return a}function ln(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function un(e){if(e)for(let[t,n]of Object.entries(e))if("content-type"===t.toLowerCase())return n}var cn=[{name:"phone_us",pattern:/(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g},{name:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g},{name:"ipv4",pattern:/\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g}],dn=["authorization","cookie","set-cookie","x-api-key","x-auth-token","proxy-authorization"];function hn(e){return p(e,"page").join("")}var fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pn=/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/,gn=/(?:^|-)[A-Za-z]{3,}-(?:[A-Za-z0-9]+-)*[A-Za-z]{3,}(?:-|$)/;function yn(e){return!!pn.test(e)||!(e.length<32||fn.test(e)||gn.test(e))&&/^[A-Za-z0-9_\-.~+/=]+$/.test(e)&&/[0-9]/.test(e)&&/[A-Za-z]/.test(e)}var vn=/@|\d[\d .()-]{5,}\d|\d\.\d|eyJ/;function mn(e){return e.split("/").some(e=>{if(/callback|oauth/i.test(e))return!0;let t=Ne(e);return[...t,t.join("")].some(e=>Je.has(e))})}var wn=new Set(["code","state","accesstoken","idtoken","refreshtoken"]);function bn(e,t){let n=new Map;for(let t of e){let e=t.indexOf("=");if(-1===e)continue;let r=hn(w(t.slice(0,e)));if(!wn.has(r))continue;let i=n.get(r),s=w(t.slice(e+1));void 0===i?n.set(r,[s]):i.push(s)}let r=e=>n.get(e)??[],i=new Set,s=r("code").filter(e=>""!==e&&!De(e)),o=r("state").filter(e=>""!==e&&!function(e){return!!q.test(e)&&(e.length<=16||j.test(e)||/^[A-Za-z][a-z]+(?:[-_][A-Za-z][a-z]+)+$/.test(e))}(e)&&!De(e));return s.length>0&&(t||o.length>0)&&(i.add("code"),i.add("state"),i.add("sessionstate")),(r("accesstoken").length>0||r("idtoken").length>0||r("refreshtoken").length>0)&&(i.add("state"),i.add("sessionstate")),i}var kn=[],Sn=!1,xn=!1;function En(e,t,n){let r=xn;xn=e;try{return jn(t,n)}finally{xn=r}}var In,An=/reset|verif|confirm|activat|invit|magic|log-?in|passw|unlock|forgot|recover|sign-?up/i,Tn=new Set(["href","xlink:href","src","action","formaction","srcset","poster","cite","data","data-src","data-href","background","longdesc"]),Rn=new Set(["title","alt","placeholder","label","content","summary","abbr","aria-label","aria-description","aria-valuetext","aria-placeholder","aria-roledescription","aria-braillelabel","aria-brailleroledescription"]),_n=new Set(["input","textarea","select"]),Cn=/^(?:style|_csstext|srcset|data-srcset|imagesrcset|ping|srcdoc)$/,On=/^[^\s"'`<>{}]*$/;function $n(e,t,n,r,i=!1){if(!("content"===e?In?.(e,n,i,r):Cn.test(e)||In?.(e,n,i)||Tn.has(e)&&On.test(a(t))))return/[^*\s]/.test(t)?"":t}var Dn=/^(\s*[\d.]*\s*[;,]\s*(?:url\s*=\s*)?)(['"]?)(.*?)(\2\s*)$/is,Nn=/[?#;@]|eyJ/;function zn(e){return Nn.test(e)||Sn&&An.test(e)}var Ln=new WeakMap;function Bn(e){return(t,n,r)=>{let i=function(e){let t=Ln.get(e.pairs);return void 0===t&&(t={oauth:bn([...e.pairs],mn(e.path))},Ln.set(e.pairs,t)),t}(r);if(i.oauth.has(hn(w(t)))||Ye(p(t,"page"),n)&&(i.linkPage??=function(e,t){let n=t.map(e=>{let t=e.indexOf("=");return-1===t?[e,""]:[e.slice(0,t),e.slice(t+1)]});return Ge([e.split("/").map(e=>e.split(";")[0])],Qe(n))}(r.path,[...r.pairs])))return"[REDACTED]";let s=e?0:function(e){let t=0,n=null;for(let r of kn)if(!(r.length<=t||"/"!==e.charAt(r.length))){if(e.startsWith(r)){t=r.length;continue}null===n&&(n=wt(e)),n.startsWith(r)&&(t=r.length)}return t}(n);if(s>0){let e=w(n.slice(s));if(!vn.test(e)||ee(e)===e)return`[REDACTED]${n.slice(s)}`}return null}}function Un(e){let t,n=null;return{kind:"page",strict:e,whole:!1,before:Bn(e),value:(e,t,n)=>{let r=p(e,"key");return!(!/[[\]]/.test(a(e))&&/ids?$/.test(r[0]??""))&&(function(e){return!!yn(e)||!/^(?:https?:|\/)[^\s"<>\\^`{|}[\]]*$/i.test(e)&&function(e){return e.split(/[^A-Za-z0-9_\-.~+/=]+/)}(e).some(yn)}(n)||yn(t))||vn.test(n)&&ee(n)!==n},bare:e=>yn(e)||yn(w(e)),segment:e=>pn.test(e),head:(e,r,i,s)=>!!Sn&&(s!==t&&(t=s,n=An.test(e)?function(e){let t=new Set,n=e.startsWith("/")?e:`/${e}`;for(let e of yt(`https://link.invalid${n}`))t.add(e.value);return t}(e):null),null!==n&&n.has(r)&&(function(e){let t=a(e);return!!fn.test(t)||t.split(/[-_.~]+/).some($e)}(r)||xn&&Ve(s,i)))}}var Pn=Un(!1),qn=Un(!0);function jn(e,t){return zn(e)?O(e,t?qn:Pn):e}var Mn=/(?:[A-Za-z0-9_-]|[\u0080-\uffff]|\\(?:[0-9A-Fa-f]{1,6}[ \t\n]?|[^\n0-9A-Fa-f]))+/y;function Kn(e,t){return Mn.lastIndex=t,Mn.test(e)?Mn.lastIndex:t}function Wn(e){return e.replace(/\\(?:([0-9A-Fa-f]{1,6})[ \t\n]?|([\s\S]))/g,(e,t,n)=>{if(void 0===t)return"\n"===n?"":n??"";let r=parseInt(t,16);return 0===r||r>1114111||r>=55296&&r<=57343?"\ufffd":String.fromCodePoint(r)})}function Fn(e,t){if(!/url\(|["'\\]/i.test(e)||!zn(e)&&!e.includes("\\"))return e;let n=e.length,r=/[\t\n\f\r ]/,i="",s=0,o=(n,r,o)=>{let a=e.slice(n,r),l=a.includes("\\")?Wn(a):a,u=jn(l,t);u!==l&&(i+=e.slice(s,n)+(l===a?u:function(e,t){return e.replace(t?/[\\"'\n]/g:/[\\"'()\s]/g,e=>/\s/.test(e)?`\\${e.charCodeAt(0).toString(16)} `:`\\${e}`)}(u,o)),s=r)},a=0;for(;a<n;){let t=e[a];if("/"===t&&"*"===e[a+1]){let t=e.indexOf("*/",a+2);a=-1===t?n:t+2}else if(e.startsWith("\x3c!--",a))a+=4;else if('"'===t||"'"===t){let r=a+1;for(;r<n&&e[r]!==t&&"\n"!==e[r];)r+="\\"===e[r]?2:1;r=Math.min(r,n),o(a+1,r,!0),a=r+1}else{let t=Kn(e,a);if(t===a){a++;continue}if("("!==e[t]||"url"!==Wn(e.slice(a,t)).toLowerCase()){a=t;continue}let i=t+1;for(;i<n&&r.test(e[i]);)i++;if('"'===e[i]||"'"===e[i]){a=i;continue}let s=i;for(;s<n&&")"!==e[s];)s+="\\"===e[s]?2:1;s=Math.min(s,n);let l=s;for(;l>i&&r.test(e[l-1]);)l--;o(i,l,!1),a=s+1}}return 0===s?e:i+e.slice(s)}var Hn={Tab:"\t",NewLine:"\n",excl:"!",quot:'"',QUOT:'"',num:"#",dollar:"$",percnt:"%",amp:"&",AMP:"&",apos:"'",lpar:"(",rpar:")",ast:"*",midast:"*",plus:"+",comma:",",period:".",sol:"/",colon:":",semi:";",lt:"<",LT:"<",equals:"=",gt:">",GT:">",quest:"?",commat:"@",lsqb:"[",lbrack:"[",bsol:"\\",rsqb:"]",rbrack:"]",Hat:"^",lowbar:"_",UnderBar:"_",grave:"`",DiacriticalGrave:"`",lcub:"{",lbrace:"{",verbar:"|",vert:"|",VerticalLine:"|",rcub:"}",rbrace:"}",nbsp:"\xa0",NonBreakingSpace:"\xa0"};function Zn(e,t){let n=e.replace(/&/g,"&");return'"'===t?n.replace(/"/g,"""):"'"===t?n.replace(/'/g,"'"):n.replace(/[\s"'`>]/g,e=>`&#${e.charCodeAt(0)};`)}var Vn=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes"]),Jn=/(^|[\s/"'])(href|xlink:href|src|action|formaction|poster|cite|data|background|longdesc|data-src|data-href|srcset|imagesrcset|data-srcset|ping|content|style|srcdoc)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;function Xn(e,t,n=[],r="",i=!1){let s=[kn,Sn];kn=n,Sn=!0;try{Gn(e,t,r,i)}finally{[kn,Sn]=s}}function Gn(e,t,n="",r=!1){for(let i of Object.keys(e)){let s=e[i],o=i.toLowerCase();if(t&&("checked"===o||"selected"===o)){delete e[i];continue}if("string"!=typeof s){"style"===o&&ln(s)&&Qn(s,t);continue}let a=(t?$n(o,s,n,e,r):void 0)??Yn(o,tr(o,s,t,n),n);a!==s&&(e[i]=a)}}function Qn(e,t){let n=e=>Yn("style",Fn(e,t),"");for(let t of Object.keys(e)){let r=e[t];if("string"==typeof r){let i=n(r);i!==r&&(e[t]=i)}else if(Array.isArray(r)&&"string"==typeof r[0]){let i=n(r[0]);i!==r[0]&&(e[t]=[i,...r.slice(1)])}}}function Yn(e,t,n){return e.startsWith("rr_")?t:function(e,t){return"value"===e?""!==t&&!_n.has(t):Rn.has(e)||e.startsWith("data-")&&!Tn.has(e)&&"data-srcset"!==e}(e,n)&&vn.test(t)?ee(t):te(t)}function er(e){return te(e)}function tr(e,t,n,r){let i=t;return"srcset"===e||"data-srcset"===e||"imagesrcset"===e?i=function(e,t){if(!zn(e))return e;let n=e.split(",").map(e=>{let n=/^(\s*)(\S+)([\s\S]*)$/.exec(e);return null===n?e:n[1]+jn(n[2],t)+n[3]}).join(",");return n===e?e:n}(t,n):"style"===e||"_csstext"===e?i=Fn(t,n):"ping"===e?i=t.replace(/\S+/g,e=>jn(e,n)):"srcdoc"===e?i=function(e,t){if(!t&&!zn(e)&&!/url\(/i.test(e))return e;let n=e.length,r=/[\t\n\f\r ]/,i=[],s=new Set,o=(n,r,s,o,a="")=>{let l=function(e){return e.includes("&")?e.replace(/&(?:#(\d+);?|#[xX]([0-9A-Fa-f]+);?|([A-Za-z][A-Za-z0-9]*);|(amp|AMP|lt|LT|gt|GT|quot|QUOT)(?![A-Za-z0-9=]))/g,(e,t,n,r,i)=>{if(void 0!==t||void 0!==n){let e=void 0!==t?Number(t):parseInt(n,16);return 0===e||e>1114111||e>=55296&&e<=57343?"\ufffd":String.fromCodePoint(e)}return Hn[r??i??""]??e}):e}(e.slice(r,s)),u=(t?$n(n,l,a):void 0)??tr(n,l,t,"");u!==l&&i.push([r,s,Zn(u,o)])},a=(t,i,a="")=>{let l=t;for(;;){for(;l<n&&(r.test(e[l])||"/"===e[l]);)l++;if(l>=n||">"===e[l])return l;let t=l;for(l++;l<n&&!r.test(e[l])&&!"/>=".includes(e[l]);)l++;let u=e.slice(t,l).toLowerCase(),c=l;for(;c<n&&r.test(e[c]);)c++;if("="!==e[c]){l=c;continue}for(c++;c<n&&r.test(e[c]);)c++;let d='"'===e[c]||"'"===e[c]?e[c]:"",h=""===d?c:c+1,f=h;if(""!==d)f=e.indexOf(d,h),-1===f&&(f=n),l=Math.min(f+1,n);else{for(;f<n&&!r.test(e[f])&&">"!==e[f];)f++;l=f}i&&(s.add(`${h}:${f}`),o(u,h,f,d,a))}},l=(n,r)=>{let s=e.slice(n,r);t&&/\S/.test(s)&&i.push([n,r,s.replace(/\S/g,"*")])},u=0,c=e.indexOf("<");for(;-1!==c&&c<n;){let s,o=!0;if(e.startsWith("\x3c!--",c))if(e.startsWith(">",c+4))s=c+5;else if(e.startsWith("->",c+4))s=c+6;else{let t=/--!?>/g;t.lastIndex=c+4;let r=t.exec(e);s=null===r?n:r.index+r[0].length,l(c+4,null===r?n:r.index)}else if("!"===e[c+1]||"?"===e[c+1]){let t=e.indexOf(">",c+2);s=-1===t?n:t+1,/^<!doctype/i.test(e.slice(c,c+9))||l(c+2,-1===t?n:t)}else if("/"===e[c+1]&&/[A-Za-z]/.test(e[c+2]??"")){let t=c+2;for(;t<n&&!r.test(e[t])&&!"/>".includes(e[t]);)t++;s=a(t,!1)+1}else if(/[A-Za-z]/.test(e[c+1]??"")){let o=c+1;for(;o<n&&!r.test(e[o])&&!"/>".includes(e[o]);)o++;let u=e.slice(c+1,o).toLowerCase(),d=a(o,!0,u);if(s=d+1,Vn.has(u)&&d<n){let r=new RegExp(`</${u}[\\t\\n\\f\\r />]`,"gi");r.lastIndex=d+1;let o=r.exec(e),a=null===o?n:o.index;if("style"===u){let n=e.slice(d+1,a),r=Fn(n,t);r!==n&&i.push([d+1,a,r])}else l(d+1,a);s=a}}else s=c+1,o=!1;o&&(l(u,c),u=s),c=e.indexOf("<",s)}l(u,n),i.sort((e,t)=>e[0]-t[0]);let d=i.length,h=new RegExp(Jn.source,"gi"),f=0,p=0;for(let t=h.exec(e);null!==t;t=h.exec(e)){let e=t[3]??t[4]??t[5]??"",n=t.index+t[0].length-(void 0===t[5]?1:0),r=n-e.length;for(h.lastIndex=r;f<d&&i[f][1]<=r;)f++;if(s.has(`${r}:${n}`)||f<d&&i[f][0]<n||r<p)continue;let a=void 0!==t[3]?'"':void 0!==t[4]?"'":"",l=i.length;o(t[2].toLowerCase(),r,n,a),i.length>l&&(p=n)}if(0===i.length)return e;i.sort((e,t)=>e[0]-t[0]);let g="",y=0;for(let[t,n,r]of i)g+=e.slice(y,t)+r,y=n;return g+e.slice(y)}(t,n):"content"===e?i=function(e,t){if(!zn(e))return e;let n=Dn.exec(e);if(null!==n&&""!==n[3]){let r=En(!0,n[3],t);return r===n[3]?e:n[1]+n[2]+r+n[4]}return/^\s*https?:\/\//i.test(e)?jn(e,t):e}(t,n):Tn.has(e)?i=En(function(e,t){return"href"===e||"xlink:href"===e?""===t||"a"===t||"area"===t:"action"===e||"formaction"===e}(e,r),t,n):nr.test(t)&&(i=En(!1,t,n)),i}var nr=/^(?:(?:[a-z][a-z0-9+.-]{0,31}:\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\.{0,2}\/)[^\s?#;]*[?#;]|[?#])\S*$/i;function rr(e,t,n=[]){let r=[kn,Sn];kn=n,Sn=!0;try{return Fn(e,t)}finally{[kn,Sn]=r}}function ir(e){let t=e.map(e=>e.textContent).join(""),n=re(t).sort((e,t)=>e[0]-t[0]),r=0,i=0;for(let s of e){let e=i+s.textContent.length,o="",a=i;for(;r<n.length&&n[r][0]<e;){let[i,s]=n[r];if(i>=a&&(o+=`${t.slice(a,i)}[REDACTED]`),a=Math.max(a,Math.min(s,e)),s>e)break;r++}s.textContent=o+t.slice(a,e),i=e}}function sr(e){let t=e;return 3===t?.type&&"string"==typeof t.textContent}function or(e){let t=[];for(let n of e)sr(n)?t.push(n):5!==n?.type&&(t.length>1&&ir(t),t=[]);t.length>1&&ir(t)}function ar(e,t,n=[]){let r=[kn,Sn];kn=n,Sn=!0;try{!function(e,t){let n=[e],r=new Set;for(;n.length>0;){let e=n.pop();if(null===e||"object"!=typeof e||r.has(e))continue;if(r.add(e),"string"==typeof e.textContent){let n=!0===e.isStyle?Fn(e.textContent,t):t&&5===e.type?"":er(e.textContent);n!==e.textContent&&(e.textContent=n)}let i=e.attributes;if(null!==i&&"object"==typeof i&&Gn(i,t,"string"==typeof e.tagName?e.tagName.toLowerCase():"",!0===e.isSVG),Array.isArray(e.childNodes)){or(e.childNodes);for(let t of e.childNodes)n.push(t)}}}(e,t)}finally{[kn,Sn]=r}}function lr(e,t,n){switch(e){case"location":case"content-location":return n(t);case"link":return t.replace(/<([^>]*)>/g,(e,t)=>`<${n(t)}>`);case"refresh":{let e=/^\s*(?:\d[\d.]*\s*[;,]\s*)?url\s*=\s*/i.exec(t);if(null===e)return pe(t);let r=t.slice(e[0].length),i=/^(["'])(.*)\1$/.exec(r);return i?`${e[0]}${i[1]}${n(i[2])}${i[1]}`:`${e[0]}${n(r)}`}}return pe(t)}var ur=new Set(["accept","accept-encoding","accept-ranges","age","cache-control","connection","content-encoding","content-language","content-length","content-type","date","etag","expires","keep-alive","last-modified","pragma","transfer-encoding","vary"]);function cr(e){if(e.startsWith("access-control-"))return!1;if(K(e))return!0;let t=e.split(/[-_\s]+/).filter(e=>""!==e);t.length>1&&/^v?\d+$/.test(t[t.length-1])&&t.pop();let n=t[t.length-1]??"",r=t[t.length-2]??"";return K(n)||""!==r&&K(r+n)}function dr(){return{maskSelectors:[],unmaskSelectors:[],blockSelectors:[],maskNetworkBodies:!1,sensitiveHeaders:[...dn],piiPatterns:[],secretRoutes:[],keepRoutes:[]}}function hr(e,t){let n=Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e)),r={...e,...n};if(n.sensitiveHeaders){let t=new Set;r.sensitiveHeaders=[...dn,...e.sensitiveHeaders,...n.sensitiveHeaders].filter(e=>{let n=e.toLowerCase();return!t.has(n)&&(t.add(n),!0)})}return r}function fr(e){return e.map(({pattern:e})=>e.flags.includes("g")?new RegExp(e.source,e.flags):new RegExp(e.source,e.flags+"g"))}var pr={},gr="[MASKED]",yr=class{config;builtinPatterns;userPatterns;strict;constructor(e={},t="balanced"){this.strict="strict"===t,this.config=this.settle(hr(dr(),e)),this.builtinPatterns=fr(cn),this.userPatterns=fr(this.config.piiPatterns)}settle(e){return this.strict?{...e,maskNetworkBodies:!0}:e}maskText(e){if(!e)return e;let t=ee(e,this.userPatterns);for(let e of this.builtinPatterns)t=t.replace(e,"[REDACTED]");return t}maskUrl(e){if(!e)return e;let t=e.indexOf("#");return function(e,t=!1){return O(e,t?xe:Se)}(-1===t?e:e.slice(0,t),this.strict)}maskNetworkData(e,t){let n={...e};n.requestHeaders=this.maskHeaders(e.requestHeaders),n.responseHeaders=this.maskHeaders(e.responseHeaders);let r=this.bodyJob(e),i=r&&(t??pr.redact?.(r)??{requestBody:e.requestBody?gr:null,responseBody:e.responseBody?gr:null});return n.requestBody=i?i.requestBody:e.requestBody?gr:null,n.responseBody=i?i.responseBody:e.responseBody?gr:null,n.url=this.maskUrl(e.url),n}bodyJob(e){return this.config.maskNetworkBodies?null:{requestBody:e.requestBody,responseBody:e.responseBody,requestType:un(e.requestHeaders),responseType:un(e.responseHeaders),patterns:this.userPatterns}}getConfig(){return this.config}updateConfig(e){this.config=this.settle(hr(this.config,e)),this.userPatterns=fr(this.config.piiPatterns)}maskHeaders(e){let t={},n=new Set(this.config.sensitiveHeaders.map(e=>e.toLowerCase()));for(let[r,i]of Object.entries(e)){let e=r.toLowerCase();n.has(e)||cr(e)||this.strict&&!ur.has(e)?t[r]="[REDACTED]":t[r]=this.maskText(lr(e,i,e=>this.maskUrl(e)))}return t}},vr=200,mr=/^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/,wr="must be 1-200 characters of letters, digits, dot, dash and underscore, with no empty dot-separated segment";function br(e){return"string"==typeof e&&e.length>0&&e.length<=200&&mr.test(e)}var kr=["status","serverMessage","endpoint","sessionId"],Sr=["issues"];function xr(e){let t={};for(let n of Object.keys(e)){let r=e[n],i="https://keploy.io/docs/ui-capture/errors#"+n.toLowerCase().replace(/_/g,"-");t[n]={summary:r.summary,remedy:{command:null,manual:i,docs:i},evidence:r.evidence,optionalEvidence:r.optionalEvidence??[]}}return t}var Er=xr({KUI_E_INGEST_KEY_REJECTED:{summary:"The ingest server refused the SDK's API key (401 or 403). Capture has stopped.",evidence:kr,optionalEvidence:Sr},KUI_E_INGEST_ENDPOINT_NOT_FOUND:{summary:"The ingest server answered 404 or 405: nothing at `endpoint` accepts a POST. Capture has stopped.",evidence:kr,optionalEvidence:Sr},KUI_E_SESSION_CONFLICT:{summary:"The ingest server answered 409: this session id is already claimed, or a batchId was re-used. Capture has stopped.",evidence:kr,optionalEvidence:Sr},KUI_E_INGEST_REJECTED:{summary:"The ingest server refused a batch with a terminal 4xx (400, 413 or 415). Capture has stopped.",evidence:kr,optionalEvidence:Sr},KUI_E_SESSION_ID_INVALID:{summary:"The configured `sessionIdGenerator` did not produce a session id the ingest server would accept. Capture did not start.",evidence:["sessionId","received","rule"]},KUI_E_DOM_RECORDER_UNAVAILABLE:{summary:"The capture SDK could not load rrweb, the library it records the page with. The capture ended before anything was sent.",evidence:["reason"]},KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE:{summary:"Under strict, the capture SDK could not load its attribute allow-list. The capture ended before anything was recorded or sent.",evidence:["reason"]},KUI_E_PRIVACY_ROUTE_INVALID:{summary:"A route in `privacy.secretRoutes` or `privacy.keepRoutes` is not one the SDK can match. Capture did not start.",evidence:["option","received","rule"]},KUI_E_CAPTURE_DECLINED:{summary:"The browser sent Do Not Track or Global Privacy Control, and `honorPrivacySignals` is on. Capture did not start; nothing was recorded or sent.",evidence:["signal"]},KUI_E_PRIVACY_CONFLICT:{summary:'`privacyMode: "strict"` records no body, and `privacy.maskNetworkBodies` is `false`, which asks for them. Capture did not start.',evidence:["privacyMode","option"]}}),Ir=xr({KUI_E_EVENT_UNSERIALISABLE:{summary:"The SDK dropped one captured event because it could not be serialised to JSON. The capture continues without it.",evidence:["eventId","eventType","reason"]},KUI_E_EVENT_OVERSIZED:{summary:"The SDK dropped one captured event that alone is over the ingest server's decoded cap (`evidence.cap` bytes). The capture continues without it.",evidence:["eventId","eventType","bytes","cap"]},KUI_E_EVENT_OVERSIZED_SCRUBBING:{summary:"The SDK dropped one captured event whose scrub of the page URL's credentials passed the ingest server's decoded cap (`evidence.cap` bytes). The capture continues without it.",evidence:["eventType","atLeast","cap"]},KUI_E_NAVIGATION_UNWRAPPED:{summary:"The page made a History or Navigation API method the SDK wraps (`evidence.method`) impossible to replace and put back, so the SDK wrapped none of them. The capture continues.",evidence:["method"]},KUI_E_REQUEST_TERM_FAILED:{summary:"The SDK recorded a request without its canonical-key.v2 term (computing it threw: `evidence.reason`), or body:* (its term code did not load). The page's request was unaffected.",evidence:["method","reason"]},KUI_E_BODY_WORKER_UNAVAILABLE:{summary:"No body worker or chunk (`evidence.part`): no worker, a body over 64 KiB is recorded cut; no chunk, one the main thread redacts keeps nothing; tests over them are unproven.",evidence:["part","reason"]}});function Ar(e){return e.replace(/\s+/g," ").trim()}function Tr(e,t){let{code:n,...r}=e;return`[keploy] ${n}: dropped an event: ${Ar(t)} The capture continues; any further such events in this capture are dropped silently. evidence=${_r(r)}`}function Rr(e,t){let{code:n,...r}=e;return`[keploy] ${n}: ${Ar(t)} evidence=${_r(r)}`}function _r(e){try{return JSON.stringify(e)}catch{let t={};for(let[n,r]of Object.entries(e))t[n]="string"==typeof r||"number"==typeof r?r:Lr(r);return JSON.stringify(t)}}function Cr(e){return 401===e||403===e?"KUI_E_INGEST_KEY_REJECTED":404===e||405===e?"KUI_E_INGEST_ENDPOINT_NOT_FOUND":409===e?"KUI_E_SESSION_CONFLICT":e>=400&&e<500&&429!==e?"KUI_E_INGEST_REJECTED":null}var Or={message:null,issues:null},$r=500;function Dr(e){if(null===e)return Or;let t=e.trim();if(""===t)return Or;try{let e=JSON.parse(t);if(null!==e&&"object"==typeof e){let t=e;if("string"==typeof t.error){let e=t.error.trim();return{message:""===e?null:e.slice(0,$r),issues:zr(t.issues)}}}}catch{}return{message:t.slice(0,$r),issues:null}}var Nr=100;function zr(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(t.length===Nr)break;if(null===n||"object"!=typeof n)continue;let{path:e,message:r}=n;"string"!=typeof e||"string"!=typeof r||t.push({path:e.slice(0,$r),message:r.slice(0,$r)})}return t.length>0?t:null}function Lr(e){if("string"==typeof e)return e;if(e instanceof Error)return`${e.name}: ${e.message}`;if("function"==typeof e)return`[function ${e.name}]`;if("object"!=typeof e||null===e)return String(e);try{return JSON.stringify(e)}catch{let t=e.constructor;return`[${"string"==typeof t?.name?t.name:"object"} not JSON-serialisable]`}}var Br=class extends Error{code;status;serverMessage;issues;remedy;evidence;constructor(e,t,n,r,i){super(t),this.name="CaptureError",this.code=e,this.remedy=Er[e].remedy,this.status=n,this.serverMessage=r.message,this.issues=r.issues,this.evidence=i}},Ur=class extends Br{constructor(e){let{message:t,issues:n}=e.server,r=`[keploy] capture stopped: the server rejected this batch with ${e.status} and will reject the rest, so capture has stopped (${e.code}). ${null===t?"(no response body)":t}`;if(null!==n){let e=n.slice(0,5).map(e=>`${""===e.path?"body":e.path}: ${e.message}`).join("; "),t=n.length-5;r+=` -- ${e}${t>0?` (+${t} more)`:""}`}super(e.code,r,e.status,e.server,{status:e.status,serverMessage:t,endpoint:e.endpoint,sessionId:e.sessionId,...null!==n?{issues:n}:{}})}},Pr=class extends Br{constructor(e){super("KUI_E_SESSION_ID_INVALID",`[keploy] capture did not start: sessionIdGenerator ${null!==e.sessionId?`returned ${JSON.stringify(e.sessionId)}, which the ingest server would refuse`:e.received.startsWith("threw ")?e.received:`returned ${e.received}, which is not a session id`} (KUI_E_SESSION_ID_INVALID). A session id ${wr}.`,null,Or,{sessionId:e.sessionId,received:e.received,rule:wr})}},qr=class extends Br{constructor(e){super("KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE",`[keploy] capture ended before anything was recorded: privacyMode "strict" could not load its attribute allow-list (KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE): ${e.reason}. What to do: ${Er.KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE.remedy.docs}`,null,Or,{reason:e.reason})}},jr=class extends Br{constructor(e){super("KUI_E_DOM_RECORDER_UNAVAILABLE",`[keploy] capture ended before anything was sent: rrweb, the library the SDK records the page with, could not be loaded (KUI_E_DOM_RECORDER_UNAVAILABLE): ${e.reason}. What to do: ${Er.KUI_E_DOM_RECORDER_UNAVAILABLE.remedy.docs}`,null,Or,{reason:e.reason})}},Mr=class extends Br{constructor(e){super("KUI_E_PRIVACY_ROUTE_INVALID",`[keploy] capture did not start: privacy.${e.option} has ${e.received}, which is no route (KUI_E_PRIVACY_ROUTE_INVALID). ${tt}.`,null,Or,{option:e.option,received:e.received,rule:tt})}},Kr=class extends Br{constructor(e){super("KUI_E_CAPTURE_DECLINED",`[keploy] capture did not start: the browser sent ${"doNotTrack"===e?"Do Not Track":"Global Privacy Control"}, and honorPrivacySignals is on (KUI_E_CAPTURE_DECLINED). Nothing was recorded or sent.`,null,Or,{signal:e})}},Wr=class extends Br{constructor(){super("KUI_E_PRIVACY_CONFLICT",'[keploy] capture did not start: privacyMode "strict" records no request or response body, and privacy.maskNetworkBodies is false, which asks for them (KUI_E_PRIVACY_CONFLICT). Remove privacy.maskNetworkBodies, or use privacyMode "balanced".',null,Or,{privacyMode:"strict",option:"privacy.maskNetworkBodies"})}};function Fr(e){if("threw"in e)return`threw ${Lr(e.threw)}`;let t=e.returned;if("object"==typeof t&&null!==t){if("function"==typeof t.then)return"a Promise (sessionIdGenerator must return a string synchronously)";let e=t.constructor,n="string"==typeof e?.name?e.name:"";if(""!==n&&"Object"!==n)return`object ${n} ${Lr(t)}`}return`${typeof t} ${Lr(t)}`}var Hr,Zr,Vr,Jr=!1,Xr=!1,Gr=[],Qr=0,Yr=()=>Qr,ei=new WeakSet,ti=!1,ni=[],ri=!1,ii=[];function si(e=!0){if(!Jr)return;for(let t of ii)t(e);Jr=Xr=ti=!1,Hr=Zr=Vr=void 0;let t=ni;ni=[],ci(),setTimeout(()=>{for(let e of t)hi(e)||e()},0)}var oi=new Set,ai=(e,t)=>new Promise((n,r)=>{let i=()=>{if(Xr&&!t)return n(void 0);let i=()=>n(void 0);oi.add(i),e.then(e=>(oi.delete(i),n(e)),e=>(oi.delete(i),r(e)))};(t||!ui(i))&&i()});function li(){for(let e of oi)e();oi.clear()}function ui(e){let t=Jr&&!Xr;return t&&Gr.push(e),t}function ci(){let e=Gr;Gr=[];for(let t of e)t()}function di(){!Jr||Xr||(Xr=!0,ni.length&&li(),ci())}function hi(e){return Jr&&(ni.push(e),Xr&&li()),Jr}function fi(e){return new Promise((t,n)=>{let r=()=>{new Promise(t=>t(e())).then(t,e=>{hi(r)||n(e)})};hi(r)||r()})}var pi=()=>globalThis.navigation;function gi(e,t,n,r){let i=Qr;setTimeout(()=>{if(!r)return void(Hr===e&&t()&&si(n));if(ti||i!==Qr||!Jr)return;let s=r.defaultPrevented||ei.has(r);if(r===Vr&&Hr===r&&(s||t()))return si(n);r!==Vr&&s||(ti=!0,di())},0)}function yi(e){let t=e.type,n=e;if("currententrychange"===t)return void(Zr&&(n.from!==pi()?.currentEntry||n.navigationType)&&ei.add(Zr));if("pageshow"===t)return void(e.isTrusted&&e.persisted&&si());Jr||(Zr=void 0);let r=Jr;"navigate"===t&&(Zr=e),!n.destination?.sameDocument&&null==n.downloadRequest&&(r||Qr++,Jr=!0,Hr=e,"navigate"!==t?setTimeout(()=>{Hr===e&&(ti=!0,di())},0):(gi(e,()=>pi()?.transition,r&&Xr,Vr=n),n.signal?.addEventListener("abort",()=>gi(Hr,()=>Zr===e,!1))))}var vi=["beforeunload","pageshow"];function mi(e,t=e){if(t&&si(),ri===e||"function"!=typeof addEventListener)return;ri=e;let n={capture:!0,passive:!0},r=(t,r)=>{for(let i of r)e?t?.addEventListener(i,yi,n):t?.removeEventListener(i,yi,n)};r(globalThis,vi),r(pi(),["navigate","currententrychange"])}var wi="3.1.0-rc.2";function bi(e){return"default"in e?e.default:e}function ki(e,t){let n=e=>{let t=bi(e),n=t.version;if(n!==wi)throw new Error(`a chunk of version ${String(n)}, not the SDK's ${wi}`);return t};return fi(e).then(n).catch(e=>t?fi(t).then(n).catch(t=>Promise.reject(new Error(`${String(e)}; beside the SDK: ${String(t)}`,{cause:e}))):Promise.reject(e))}var Si,xi,Ei,Ii,Ai=!1,Ti=!1,Ri=!1,_i=new Set,Ci=new Map,Oi=0,$i=e=>e.mark===Yr();function Di(e){(typeof requestIdleCallback<"u"?requestIdleCallback:setTimeout)(e,{timeout:1e3,valueOf:()=>0})}var Ni,zi,Li="";function Bi(e,t){if(!Li.includes(e)){Li+=e;try{console.warn(function(e,t){return Rr({code:"KUI_E_BODY_WORKER_UNAVAILABLE",part:e,reason:t},"could not run the body worker or load the body chunk (evidence.part): without the worker, a body over 64 KiB is recorded cut; without the chunk, a body the main thread must redact is recorded with nothing kept; replay reports a test over a cut body unproven. Allow worker-src 'self' in the page's CSP, use a bundler that emits the worker (or copy dist/body-worker.js beside the bundle), serve it from the page's origin, or serve the SDK's dist/ as it is. Said once per page for each part.")}(e,typeof Event<"u"&&t instanceof Event?t.message||"the worker's script did not load or run (refused by the page's CSP, a 404, or a script that does not parse)":Lr(t)))}catch{}}}function Ui(e){if(typeof navigator>"u"||!1!==navigator.onLine||function(){try{return!!navigator.serviceWorker?.controller}catch{return!1}}()||"function"!=typeof addEventListener)return!1;if(!Ni){Ni=[];let e=()=>{if(!1===navigator.onLine)return;zi?.();let e=Ni??[];Ni=void 0;for(let t of e)t()};addEventListener("online",e);let t=setInterval(e,1e3);zi=()=>{removeEventListener("online",e),clearInterval(t),zi=void 0}}return Ni.push(e),!0}function Pi(){return xi??=new Promise(e=>{let t=()=>{Ai=!1,ki(()=>import("@keploy/capture-sdk/body-redact"),void 0).then(e=>{if("function"!=typeof e.redactBodies)throw new TypeError("the body chunk has no redactBodies export");return e}).then(t=>{Si=t,pr.redact=e=>t.redactBodies(e),e()},t=>{Ti=!0,Bi("code",t),e()})};(Ai=Ui(t))||t()})}function qi(){if(Ri||void 0!==Ei)return;Ri=!0;let e=()=>{ki(()=>import("@keploy/capture-sdk/body-worker-start"),void 0).then(e=>fi(()=>e.startBodyWorker())).then(e=>{e.onmessage=({data:t})=>{Ii=e;let n=Ci.get(t.id);n&&(Ci.delete(t.id),n.owner.answered(n,t.out))},e.onerror=t=>Zi(e,t),Ei=e,Ri=!1;let t=_i;_i=new Set;for(let e of t)Hi(e)}).catch(e=>Zi(null,e))};Ui(e)||e()}function ji(){Pi(),qi()}var Mi,Ki=!1,Wi=!1;function Fi(e=!1){xi&&void 0!==Ei||(e?Ki:Wi)||(e?Ki=!0:Wi=!0,(e?Di:e=>setTimeout(e,0))(()=>{e?Ki=!1:Wi=!1,ji()}))}function Hi(e){if(!e.owner.has(e))return;let t=Ei?Ei===Ii:null===Ei&&Si;if(t||!$i(e)||!ui(()=>Hi(e))){if(!t&&(e=>Xr&&$i(e))(e))return e.owner.answered(e,Gi(e.job)),void(e.job=null);if(Ei){Ci.set(++Oi,e);try{Ei.postMessage({id:Oi,job:e.job})}catch{Ci.delete(Oi),e.owner.alone(e)}}else null===Ei?e.owner.alone(e):(_i.add(e),ji())}}function Zi(e,t){if(e&&Ei!==e)return;try{e?.terminate()}catch{}let n=[...Ci.values(),..._i].filter(e=>e.owner.has(e));Ci.clear(),Ei=void 0,_i=new Set(n),Ri=!0;let r=()=>{Ri=!1,qi()};if(!Ui(r)&&!hi(r)){Ri=!1,Ei=null,_i=new Set,Bi("worker",t);for(let e of n)e.owner.alone(e)}}function Vi(){if(Mi=void 0,Ei&&!(Ci.size>0)){try{Ei.terminate()}catch{}Ei=void 0}}var Ji=()=>{Mi&&(Ci.clear(),Vi())};function Xi(e=!0,t=()=>!1){if(e&&Ni&&(zi?.(),Ni=void 0,Ai&&(xi=void 0),void 0===Ei&&(Ri=!1),_i=new Set),t()&&void 0!==Ii&&Ei===Ii&&Jr)return Mi=t,void addEventListener("pagehide",Ji);Vi()}function Gi(e){let t=e=>e&&function(e,t){return`${function(e,t){return`[Body cut: 0 of ${t} characters kept, unverified]\n`}(0,e)}[Body not captured: ${U[t]}]\n`}(e.length,Ti?"code-failed":"left");return{requestBody:t(e.requestBody),responseBody:t(e.responseBody)}}function Qi(e,t,n=t){try{return Si.redactBodies(e,t,n)}catch{return null}}function Yi(e){return(e?.requestBody?.length??0)+(e?.responseBody?.length??0)}ii.push(e=>{e&&Ei&&Ei!==Ii&&Zi(Ei,"left"),Mi&&!Mi()&&Vi()});var es=class{held=new Map;redact(e,t,n,r=Yr()){let i={job:e,owner:this,after:n,mark:r};this.held.set(i,t),e&&(e.requestBody||e.responseBody)?typeof requestIdleCallback>"u"&&(i.sent=!0,Hi(i)):i.out={requestBody:e?e.requestBody:null,responseBody:e?e.responseBody:null},Promise.resolve(n).then(()=>Di(()=>{this.held.has(i)&&(void 0!==i.out?this.answer(i,i.out):i.sent||Hi(i))}))}holds(){return this.held.size>0}has(e){return this.held.has(e)}answered(e,t){this.held.has(e)&&(e.out=t,Promise.resolve(e.after).then(()=>Di(()=>this.answer(e,t))))}answer(e,t){let n=this.held.get(e);n&&(this.held.delete(e),_i.delete(e),e.job=null,n(t))}alone(e){Promise.all([Pi(),e.after]).then(()=>Di(()=>{if(!this.held.has(e))return;let t=e.job;this.answer(e,Si?Qi(t,65536):Gi(t))}))}now(e){let t=65536;for(let n of e?[!0,!1]:[!0])for(let e of[...this.held.keys()]){if(void 0!==e.out){this.answer(e,e.out);continue}let r=e.job;if(!r){this.answer(e,{requestBody:null,responseBody:null});continue}let i=Yi(r);if(n&&!(Si&&i<=t))continue;let s=Math.min(r.requestBody?.length??0,t);this.answer(e,Si?Qi(r,s,t-s):Gi(r)),t-=n?i:t}}},ts=/^[\t\n\r ]*\{/,ns=/[^\t\n\r ]/;var rs,is=!1;function ss(e){try{let t=typeof document<"u"?document.baseURI:void 0;return new URL(e,t).href}catch{return e}}function os(e){let t={};if(!e)return t;if(e instanceof Headers)e.forEach((e,n)=>{t[n]=e});else if(Array.isArray(e))for(let[n,r]of e)t[n]=r;else Object.assign(t,e);return t}function as(e,t){return e.length>t?e.slice(0,t)+ge:e}function ls(e){let t=e=>encodeURIComponent(e).replace(/%20/g,"+"),n=[];return e.forEach((e,r)=>{n.push("string"==typeof e?`${t(r)}=${t(e)}`:`${t(r)}=${t(`[File: ${e.name}, ${e.size} bytes]`)}`)}),n.join("&")}function us(e,t){let n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(n.byteLength>t)return`[Binary: ${n.byteLength} bytes]`;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return`[Binary: ${n.byteLength} bytes]`}}function cs(e,t){if(null==e)return null;try{if("string"==typeof e)return""===e?null:gr;if(e instanceof URLSearchParams||e instanceof FormData)return e.keys().next().done?null:gr;if(e instanceof Blob)return t||e.size>0?gr:null;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength>0?gr:null;if(t&&typeof Document<"u"&&e instanceof Document)return e.hasChildNodes()?gr:null}catch{}return gr}function ds(e){return"object"==typeof e&&null!==e&&"Request"===e[Symbol.toStringTag]}var hs=/^\s*multipart\/form-data\s*(?:;|$)/i;var fs=()=>new TextDecoder("utf-8",{ignoreBOM:!0}),ps=(e,t)=>t<4194304&&"{"!==(ns.exec(e)?.[0]??"{"),gs=async e=>fs().decode(await e.arrayBuffer());function ys(e){return e+ge}var vs=Reflect.get(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag)??{},"get"),ms=["url","redirected","type","headers"];function ws(e,t){for(let n of ms)Object.defineProperty(e,n,{get:()=>t[n],configurable:!0});let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"clone")?.value;n&&Object.defineProperty(e,"clone",{value:function(){let e=n.call(this);return ws(e,t),e},writable:!0,configurable:!0})}function bs(e,t,n){let r=e.body;if(!r)return null;let i,s,o,a=Object.getPrototypeOf(r).constructor,l=Object.getPrototypeOf(e).constructor,u=new TextDecoder,c="",d=!1,h=!1,f=!1,p=!1,g=!1,y=[],v=0,m=null,w=null,b=new Promise(e=>i=e),k=e=>{p||(p=!0,n(e))},S=()=>{if(!m||!w)return;let e=y.shift();if(e)w.enqueue(new Uint8Array(e.chunk)),v=e.textEnd;else{if(!h)return;w.close(),w.byobRequest?.respond(0)}let t=m;m=null,t()},x=()=>{g||h||f||d&&!m||(g=!0,A.read().then(e=>{if(g=!1,!f)try{if(e.done)h=!0,i(),d||k(as(c+u.decode(),t));else{let n=function(e){if("Uint8Array"===function(e){return"function"==typeof vs?Reflect.apply(vs,e,[]):void 0}(e))return e;throw new TypeError("a response body chunk is not a Uint8Array")}(e.value);n.byteLength>0&&(d||(c+=u.decode(n,{stream:!0}),c.length>t&&(d=!0,setTimeout(i,1e3),k(as(c,t)),c="")),y.push({chunk:n,textEnd:c.length}))}S(),x()}catch(e){E(e),A.cancel(e).catch(()=>{})}},e=>{g=!1,!f&&E(e)}))},E=e=>{f=!0,i(),k(ys(c)),y.length=0;try{w?.error(e)}catch{}let t=m;m=null,t?.()},I={start(e){w=e},pull:()=>new Promise(e=>{m=e,S(),x()}),cancel:e=>(f=!0,i(),k(c.slice(0,v)),y.length=0,A.cancel(e))};try{s=new a({...I,type:"bytes"},{highWaterMark:0})}catch{s=new a(I,{highWaterMark:0})}try{o=new l(s,{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return null}let A=r.getReader();return ws(o,e),x(),{page:o,cut:()=>{d||k(ys(c)),i()},done:b}}function ks(e){let t=typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"?location.href:void 0;return new URL(e,t).href}var Ss=class{callback=null;privacyEngine;maxBodySize;ignored;active=!1;inflight=new Set;unloadCuts=new Set;bodies=new es;place;admit=null;run=0;originalFetch=null;originalXhrOpen=null;originalXhrSend=null;originalXhrSetHeader=null;constructor(e={},t=524288,n=[],r="balanced"){this.privacyEngine=new yr(e,r),this.maxBodySize=t,this.ignored=new Set(n.map(ss))}ignores(e){return this.ignored.size>0&&this.ignored.has(ss(e))}start(e,t,n){this.active||(this.active=!0,this.run++,this.callback=e,this.admit=t??null,this.place=n,this.termWarned=!1,this.privacyEngine.getConfig().maskNetworkBodies||Fi(!0),this.patchFetch(),this.patchXHR())}askForCode(){this.privacyEngine.getConfig().maskNetworkBodies||Pi()}stop(){this.active&&(this.active=!1,0===this.inflight.size&&(this.callback=null),this.restoreFetch(),this.restoreXHR())}settle(e){let t,n=Promise.allSettled([...this.inflight]),r=new Promise(n=>{t=setTimeout(n,e)});return Promise.race([n,r]).then(()=>{clearTimeout(t),!this.active&&(this.cutInflight(),this.callback=null)})}cutInflight(){this.cutBodies(),this.bodies.now(!0)}cutBodies(){for(let e of[...this.unloadCuts])e()}reportDue(){this.bodies.now(!1)}hasInflight(){return this.inflight.size>0}admits(){if(!this.active)return!1;try{let e=!this.admit||this.admit();return e&&!this.privacyEngine.getConfig().maskNetworkBodies&&Fi(),e}catch{return!1}}emitFor(e,t,n,r,i){e===this.run&&this.emit(t,n,r,i)}track(e){this.inflight.add(e),e.finally(()=>{this.inflight.delete(e),!this.active&&0===this.inflight.size&&(this.callback=null)})}recordResponse(e,t){let n=Number(e.headers.get("content-length")??0);if(n>this.maxBodySize)return t(`[Response body too large: ${n} bytes]`),{page:e,cut:null};if(null===e.body)return t(""),{page:e,cut:null};let r=null;if(void 0!==e.body)try{r=bs(e,this.maxBodySize,t)}catch{return t(null),{page:e,cut:null}}if(r)return r;try{e.clone().text().then(e=>t(as(e,this.maxBodySize)),()=>t(null))}catch{t(null)}return{page:e,cut:null}}patchFetch(){if("function"!=typeof globalThis.fetch)return;let e=globalThis.fetch;this.originalFetch=e,globalThis.fetch=(t,n)=>{if(!this.active||!this.admits())return e.call(globalThis,t,n);let r;try{r=ds(t)?t.url:t instanceof URL?t.href:String(t)}catch{return e.call(globalThis,t,n)}if(this.ignores(r))return e.call(globalThis,t,n);let i,s=t;if(ds(t)&&null==n?.body)try{s=t.clone()}catch{return e.call(globalThis,t,n)}try{i=new Request(s,n)}catch{return e.call(globalThis,t,n)}let o=this.run,a=performance.now(),l=i.method,u=ks(i.url),c=os(i.headers),d=this.privacyEngine.getConfig().maskNetworkBodies,h=e.call(globalThis,t,n),f=null==n?.body&&(i.body||ds(t)&&void 0===i.body&&!/^(?:GET|HEAD)$/.test(l))?function(e,t,n=!1){if(hs.test(e.headers.get("content-type")??""))return e.formData().then(ls);let r=e.body;if(r)return async function(e,t,n){let r=e.getReader(),i=fs(),s="",o="";try{for(;;){let e=await r.read();if(e.done)return s+i.decode();let a=i.decode(e.value,{stream:!0});if(o||(o=ns.exec(a)?.[0]??""),s+=a,n&&ps(o,t))return r.cancel().catch(()=>{}),s;if(s.length>t&&(s.length>4194304||""!==o&&"{"!==o))return r.cancel().catch(()=>{}),s}}catch{return null}}(r,t,n);let i=3*t+4;return e.blob().then(async e=>{if(0===e.size)return;if(n){let n=await gs(e.slice(0,1024));if(ps(n,t))return n}let r=await gs(e.slice(0,i));return e.size>i&&/^[\t\n\r ]*(?:\{|$)/.test(r)?gs(e.slice(0,12582916)):r}).catch(()=>null)}(i,this.maxBodySize,d):null,p=null!=n?.body?d?Promise.resolve(cs(n.body,!1)):async function(e,t){if(null==e)return null;try{return"string"==typeof e?as(e,t):e instanceof URLSearchParams?as(e.toString(),t):e instanceof FormData?as(ls(e),t):e instanceof Blob?e.size>t?`[Blob: ${e.size} bytes, truncated]`:await e.text():e instanceof ArrayBuffer||ArrayBuffer.isView(e)?us(e,t):"[ReadableStream]"}catch{return"[Unreadable body]"}}(n.body,this.maxBodySize):f?f.then(e=>null==e?null:as(e,this.maxBodySize),()=>"[Unreadable body]"):Promise.resolve(null),g=null!=n?.body?this.termFor(n.body,l):f?f.then(e=>null===e?"body:*":this.termFor(e,l),()=>"body:*"):this.termFor(null,l);return Promise.resolve(h).then(e=>{if(o!==this.run||!this.admits())return e;try{let t,n="HEAD"===l||[204,205,304].includes(e.status);return this.reportWhenKnown(o,Date.now(),{method:l,url:u,requestHeaders:c,requestBody:null,responseHeaders:os(e.headers),responseBody:null,statusCode:e.status,duration:performance.now()-a,type:"fetch"},p,g,r=>n?(r(""),t={page:e,cut:null}):d?(r(function(e){return null===e.body||e.body?.locked||/^\s*0+\s*$/.test(e.headers.get("content-length")??"")?null:gr}(e)),t={page:e,cut:null}):t=this.recordResponse(e,r)),t.page}catch{return e}},e=>{throw o!==this.run||!this.admits()||this.reportWhenKnown(o,Date.now(),{method:l,url:u,requestHeaders:c,requestBody:null,responseHeaders:{},responseBody:null,statusCode:0,duration:performance.now()-a,type:"fetch"},p,g),e})}}restoreFetch(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null)}patchXHR(){if(typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,t=XMLHttpRequest.prototype.send;this.originalXhrOpen=e,this.originalXhrSend=t;let n=this.maxBodySize,r=()=>this.admits(),i=()=>this.run,s=(e,t)=>this.termFor(e,t),o=(...e)=>this.reportWhenKnown(...e),a=e=>this.ignores(e),l=()=>this.privacyEngine.getConfig().maskNetworkBodies,u=new WeakMap,c=XMLHttpRequest.prototype.setRequestHeader;this.originalXhrSetHeader=c,XMLHttpRequest.prototype.setRequestHeader=function(e,t){let n=u.get(this);return n&&(n.requestHeaders[e]=t),c.call(this,e,t)};let d=e;XMLHttpRequest.prototype.open=function(e,t,...n){let r="string"==typeof t?t:t.toString(),i=d.call(this,e,t,...n);return a(r)||u.set(this,{method:e,url:ks(r),requestHeaders:{},startTime:0}),i},XMLHttpRequest.prototype.send=function(e){let a=u.get(this);a&&(a.startTime=performance.now());let c,d=i(),h=r(),f=()=>{this.readyState<2||(c=Yr(),this.removeEventListener("readystatechange",f))};a&&h&&this.addEventListener("readystatechange",f);let p=l();return this.addEventListener("loadend",()=>{if(!a||!h||!r())return;let t=performance.now()-a.startTime,i=this.getAllResponseHeaders(),l={};if(i)for(let e of i.trim().split(/[\r\n]+/)){let t=e.indexOf(": ");t>0&&(l[e.slice(0,t)]=e.slice(t+2))}let u=null;if(p)u=function(e){if(""!==e.responseType&&"text"!==e.responseType)return gr;try{return e.responseText?gr:null}catch{return gr}}(this);else try{"string"==typeof this.responseText&&(u=as(this.responseText,n))}catch{u=`[${this.responseType} response]`}let f=p?cs(e,!0):function(e,t){if(null==e)return null;if("string"==typeof e)return as(e,t);if(e instanceof FormData)return as(ls(e),t);if(e instanceof URLSearchParams)return as(e.toString(),t);if(typeof Blob<"u"&&e instanceof Blob)return`[Blob: ${e.size} bytes]`;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return us(e,t);if(typeof Document<"u"&&e instanceof Document)try{return as((new XMLSerializer).serializeToString(e),t)}catch{return"[Unreadable body]"}return"[Unreadable body]"}(e,n);o(d,Date.now(),{method:a.method,url:a.url,requestHeaders:a.requestHeaders,requestBody:f,responseHeaders:l,responseBody:u,statusCode:this.status,duration:t,type:"xhr"},null,s(e,a.method),void 0,c)},{once:!0}),t.call(this,e)}}restoreXHR(){typeof XMLHttpRequest>"u"||(this.originalXhrOpen&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,this.originalXhrOpen=null),this.originalXhrSend&&(XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrSend=null),this.originalXhrSetHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetHeader,this.originalXhrSetHeader=null))}reportWhenKnown(e,t,n,r,i,s,o=Yr()){let a,l=r?null:{value:n.requestBody},u="object"==typeof i?null:{value:i},c=s?null:{value:n.responseBody},d=!1,h=()=>{},f=(r,i,s)=>{d||(d=!0,this.unloadCuts.delete(g),h(),this.emitFor(e,{...n,requestBody:r.value,responseBody:s.value,...void 0===i.value?{}:{requestTerm:i.value}},t,a?.done,o))},p=()=>{l&&u&&c&&f(l,u,c)},g=()=>{a?.cut?.(),f(l??{value:"[Unreadable body]"},u??{value:"body:*"},c??{value:null})};if(l&&u&&c)return p();this.unloadCuts.add(g),this.track(new Promise(e=>h=e)),r?.then(e=>{l={value:e},p()}),"object"==typeof i&&i.then(e=>{u={value:e},p()}),a=s?.(e=>{c={value:e},p()})}termWarned=!1;termFor(e,t){try{let n=function(e){return null==e||""===e?"":"string"==typeof e?e.length>4194304?"body:*":function(e){return ts.test(e)&&(e.includes('"query"')||e.includes("persistedQuery")||e.includes("\\u"))}(e)?null:"":e instanceof URLSearchParams||typeof FormData<"u"&&e instanceof FormData?"":"body:*"}(e);if(null!==n)return n;let r=globalThis.crypto?.subtle;return ai((rs||(rs=ki(()=>import("@keploy/capture-sdk/request-term"),void 0).then(e=>(is=!0,e)),rs.catch(()=>{})),rs),is).then(t=>t?t.recordTermFor(e,r):"body:*",e=>(this.termFailed(t,e),"body:*")).catch(e=>this.termFailed(t,e))}catch(e){return this.termFailed(t,e)}}termFailed(e,t){if(!this.termWarned){this.termWarned=!0;try{console.warn(function(e,t){return Rr({code:"KUI_E_REQUEST_TERM_FAILED",method:e,reason:t},"recorded a request without its term, or body:*: computing it failed; the request itself was not affected. The capture continues; any further such requests in this capture are recorded that way, silently.")}(e,Lr(t)))}catch{}}}emit(e,t,n,r){let i=this.callback;if(!i)return;let s,o,a=this.place?.();this.track(new Promise(e=>s=e));try{o=this.privacyEngine.bodyJob(e)}catch{return s()}this.bodies.redact(o,n=>{if(s(),n)try{i(this.privacyEngine.maskNetworkData(e,n),t,a)}catch{}},n,r)}},xs=wi,Es=32768;function Is(e){try{e()}catch(e){setTimeout(()=>{throw e})}}function As(e){return(new TextEncoder).encode(e).length}var Ts=10485760,Rs=16777216,_s=class{config;queue=[];retryQueue=[];batchCounter=0;flushTimer=null;current=null;sessionId=null;metadata=null;captureIdentity=null;get online(){return typeof navigator>"u"||!1!==navigator.onLine}started=!1;nextSeq=1;drainPending=!1;holding=!1;asked=0;rushDeferred=!1;wakeSender=null;inflightKeepaliveBytes=0;envelopeBytes=0;reportedUnserialisable=!1;reportedOversized=!1;reportedScrubOversized=!1;reportedNavigationUnwrapped=!1;jsonOf=new WeakMap;inFlight=null;held=0;queued=0;counted=!1;failures=0;notBefore=0;constructor(e){this.config={...e,batchSize:Math.min(e.batchSize,5e3)}}fail(e,t,n){this.discard();let r=new Ur({code:e,status:t,server:Dr(n),endpoint:this.config.endpoint,sessionId:this.sessionId??null});if(this.config.endsSessionOnly?.(e,function(e){if(null===e)return null;try{let t=JSON.parse(e)?.reason;return"string"==typeof t?t.slice(0,100):null}catch{return null}}(n))){this.stop();try{this.config.onSessionEnd?.()}catch{}}else{Is(()=>console.error(r.message)),this.stop();try{this.config.onCaptureEnd?.()}catch{}try{this.config.onError?.(r)}catch{}}}start(e,t,n=null){this.started||(this.started=!0,this.sessionId=e,this.metadata=t,this.captureIdentity=n,this.envelopeBytes=As(JSON.stringify(this.payload([],this.mintBatchId()))),this.flushTimer=setInterval(()=>{this.paced||this.flush(this.rushDeferred&&this.online)},this.config.batchInterval),typeof window<"u"&&(window.addEventListener("online",this.handleOnline),window.addEventListener("pagehide",this.handleUnload),window.addEventListener("beforeunload",this.handleUnload),document.addEventListener("visibilitychange",this.handleVisibility)))}hold(){this.holding=!0}release(){this.holding=!1,this.flush(!0)}discard(){this.queue=[],this.queued=0,this.retryQueue=[]}stop(){if(!this.started)return this.current??Promise.resolve();this.started=!1,this.holding&&this.discard(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null);let e=this.flush(!0);return typeof window<"u"&&(window.removeEventListener("online",this.handleOnline),e.finally(()=>this.disarmWhenDrained())),e}disarmWhenDrained(){this.started||this.pendingCount()>0||typeof window>"u"||(window.removeEventListener("pagehide",this.handleUnload),window.removeEventListener("beforeunload",this.handleUnload),document.removeEventListener("visibilitychange",this.handleVisibility))}enqueue(e){if(!this.started)return;let t;e.seq??=this.nextSeq++;try{let n=JSON.stringify(e),r=As(n);this.jsonOf.set(e,[n,r]),t=this.envelopeBytes+r}catch(t){return this.reportUnserialisable(e,t),void this.dropped([e])}if(t>Ts)return this.reportOversized(e,t),void this.dropped([e]);this.queue.push(e),this.held+=t,this.queued+=this.eventBytes(e);let n=[];for(;this.queue.length>this.config.maxQueueSize;){let e=this.queue.shift();this.queued-=this.eventBytes(e),n.push(e)}n.length>0&&this.dropped(n),this.fit(),!this.paced&&(t>Es?this.online?this.flush(!0):this.rushDeferred=!0:this.queue.length>=this.config.batchSize?(null!==this.current&&this.asked++,this.flush()):this.online&&this.pastShare()&&(this.counted=!0,this.flush()))}place(){return this.nextSeq++}get paced(){return performance.now()<this.notBefore}fit(){if(this.held<=Rs)return;let e=0;for(let t of this.retryQueue)e+=t.bytes;for(let t of this.queue)e+=this.eventBytes(t);let t=[];for(;e>Rs;){let n=this.retryQueue.shift();if(n)e-=n.bytes,t.push(...n.events);else{let n=this.queue.shift();e-=this.eventBytes(n),this.queued-=this.eventBytes(n),t.push(n)}}this.held=e,t.length>0&&this.dropped(t)}dropped(e){!this.online&&0===this.failures&&(this.failures=1,Is(()=>this.config.onFailing?.(!0)));let t=1/0;for(let n of e)"dom"===n.type&&(t=Math.min(t,n.seq??-1/0));let n=!1;if(t!==1/0){let r=[];for(let i of this.queue){let s=(i.seq??-1/0)>t,o="dom"===i.type?i.data?.type:void 0;s&&2===o&&(n=!0),s&&!n&&3===o?(e.push(i),this.queued-=this.eventBytes(i)):r.push(i)}this.queue=r}Is(()=>this.config.onDropped?.(e,n))}reportUnserialisable(e,t){if(this.reportedUnserialisable)return;this.reportedUnserialisable=!0;let n=t instanceof Error?t.message:String(t);console.warn(Tr({code:"KUI_E_EVENT_UNSERIALISABLE",eventId:e.id,eventType:e.type,reason:n},"it cannot be serialised to JSON."))}reportOversized(e,t){this.reportedOversized||(this.reportedOversized=!0,this.warnOversized({code:"KUI_E_EVENT_OVERSIZED",eventId:e.id,eventType:e.type,bytes:t,cap:Ts},`${t} bytes in a body, over the ingest server's ${Ts}-byte cap, so no batch could carry it.`))}reportScrubOversized(e,t,n){this.reportedScrubOversized||(this.reportedScrubOversized=!0,this.warnOversized({code:"KUI_E_EVENT_OVERSIZED_SCRUBBING",eventType:e,atLeast:t,cap:n},`scrubbing the page URL's credentials out of it was certain to write at least ${t} characters, over the ingest server's ${n}-byte cap, so no batch could carry it.`))}reportNavigationUnwrapped(e){this.reportedNavigationUnwrapped||(this.reportedNavigationUnwrapped=!0,this.warn(Rr({code:"KUI_E_NAVIGATION_UNWRAPPED",method:e},"the page made a History or Navigation API method impossible to replace and put back, so the SDK wrapped none of them. The capture continues: route changes are still recorded, with less detail, and none says that the page's script asked for it.")))}warnOversized(e,t){this.warn(Tr(e,t))}warn(e){console.warn(e)}payload(e,t){return{sessionId:this.sessionId,batchId:t,events:e,metadata:this.metadata,sdk:{name:"@keploy/capture-sdk",version:xs},captureIdentity:this.captureIdentity}}flush(e=!1){return this.holding?Promise.resolve():(e&&(this.drainPending=!0),this.current?this.current:0===this.pendingCount()||!this.online&&!this.drainPending?(this.drainPending=!1,this.failures>0&&0===this.pendingCount()&&this.online&&(this.failures=this.notBefore=0,Is(()=>this.config.onFailing?.(!1))),Promise.resolve()):(this.current=this.run(),this.current))}async run(){let e=!1;try{do{let t=this.reviveNext()??this.formFlight();if(null===t)return;this.inFlight=t;try{await this.sendWithRetry(t)}catch{return this.notBefore=performance.now()+Math.min(2e3*2**this.failures,6e4)*(1+Math.random()/2),0===this.failures++&&Is(()=>this.config.onFailing?.(!0)),this.held+=t.bytes,this.retryQueue.unshift(t),void this.trimToCapacity()}finally{this.inFlight===t&&(this.inFlight=null)}this.counted=!this.drainPending&&this.online&&this.pastShare(),e=this.asked>0&&!this.holding&&this.online&&this.queue.length>=this.config.batchSize,e&&this.asked--}while((this.drainPending||this.counted||e)&&this.pendingCount()>0)}finally{this.drainPending=!1,this.counted=!1,this.asked=0,0===this.pendingCount()&&(this.rushDeferred=!1),this.current=null,this.disarmWhenDrained()}}backoff(e){return new Promise(t=>{let n=()=>{clearTimeout(r),this.wakeSender===n&&(this.wakeSender=null),t()},r=setTimeout(n,e);this.wakeSender=n})}async sendWithRetry(e){let t=e.json,n=e.wire??=async function(e){if(typeof CompressionStream<"u"&&typeof Response<"u")try{let t=new Response(e).body.pipeThrough(new CompressionStream("gzip")),n=await new Response(t).arrayBuffer(),r=As(e);return n.byteLength<r?{body:n,bytes:n.byteLength,encoding:"gzip"}:{body:e,bytes:r,encoding:null}}catch{}return{body:e,bytes:As(e),encoding:null}}(t);for(let t=0;t<3;t++){if(e.abandoned)return;let r,i=null;try{let{body:t,bytes:s,encoding:o}=e.sent=await n;if(e.abandoned)return;let a={"Content-Type":"application/json","X-API-Key":this.config.apiKey};o&&(a["Content-Encoding"]=o);let l=!e.early&&s<=Es-this.inflightKeepaliveBytes;l&&(this.inflightKeepaliveBytes+=s),e.onWire=!0,e.dispatched=!0;try{r=await fetch(this.config.endpoint,{method:"POST",headers:a,body:t,keepalive:l});try{i=await r.text()}catch{i=null}}finally{e.onWire=!1,l&&(this.inflightKeepaliveBytes-=s)}}catch{}if(r){if(r.ok)return this.failures>0&&(this.failures=this.notBefore=0,this.drainPending=!0,Is(()=>this.config.onFailing?.(!1))),void Is(()=>this.config.onDelivered?.(e.events));let{status:t}=r,n=Cr(t);if(null!==n)return void Is(()=>this.fail(n,t,i))}if(this.failures>0||2===t)break;let s=1e3*Math.pow(2,t)*(.5+.5*Math.random());await this.backoff(s)}throw new Error("Transport: all retry attempts failed")}reclaimInFlight(){let e=this.inFlight;if(e&&!e.onWire&&!e.abandoned){if(e.abandoned=!0,this.inFlight=null,this.held+=e.bytes,e.dispatched)return this.retryQueue.unshift(e),void this.trimToCapacity();this.queue.unshift(...e.events),this.uncount(e.events,-1),this.trimToCapacity()}}reviveNext(){let e=this.retryQueue.shift();return e?{events:e.events,batchId:e.batchId,json:e.json,bytes:e.bytes,wire:e.wire,dispatched:e.dispatched,onWire:!1,abandoned:!1,early:e.early}:null}formFlight(){if(0===this.queue.length)return null;let e=this.pastShare(),t=this.counted&&!this.drainPending&&e?Es-this.inflightKeepaliveBytes:Ts;this.counted=!1;let n=0,r=this.envelopeBytes,i=0,s=Math.min(this.config.batchSize,this.queue.length);for(;i<s;){let e=this.eventBytes(this.queue[i])+(0===i?0:1);if(r+e>t)break;e>n&&(n=e),r+=e,i++}0===i&&(n=this.eventBytes(this.queue[0]),r+=n);let o=this.queue.splice(0,Math.max(i,1));this.uncount(o);let a=this.mintBatchId(),l=this.body(o,a);for(let e of o)this.jsonOf.delete(e);return{events:o,batchId:a,json:l,dispatched:!1,onWire:!1,abandoned:!1,bytes:r,early:e&&this.envelopeBytes+n<=Es}}body(e,t){return JSON.stringify(this.payload([],t)).replace('"events":[]',()=>`"events":[${e.map(e=>this.jsonOf.get(e)?.[0]??JSON.stringify(e)).join()}]`)}eventBytes(e){return this.jsonOf.get(e)?.[1]??As(JSON.stringify(e))}mintBatchId(){let e=typeof crypto<"u"?crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();this.batchCounter+=1;let t=Math.floor(4294967295*Math.random()).toString(16).padStart(8,"0");return`${Date.now().toString(16).padStart(12,"0")}-${(this.batchCounter%4294967296).toString(16).padStart(8,"0")}-`+t}uncount(e,t=1){for(let n of e)this.queued-=t*this.eventBytes(n)}pastShare(){return this.envelopeBytes+this.queued+this.queue.length>Es-this.inflightKeepaliveBytes}pendingCount(){let e=this.queue.length;for(let t of this.retryQueue)e+=t.events.length;return e}trimToCapacity(){let e=0;for(let t of this.retryQueue)e+=t.events.length;let t=[];for(;this.queue.length>0&&e+this.queue.length>this.config.maxQueueSize;){let e=this.queue.pop();this.queued-=this.eventBytes(e),t.push(e)}t.length>0&&this.dropped(t.reverse()),this.fit()}flushOnUnload(e=!1){if(this.holding||(this.reclaimInFlight(),this.queue.sort((e,t)=>e.seq-t.seq),"function"!=typeof fetch))return;for(;this.retryQueue.length>0;){let e=this.retryQueue[0],t=e.sent,n=t?t.bytes:As(e.json);if(n>Es-this.inflightKeepaliveBytes)return;this.retryQueue.shift(),e.dispatched=!0,this.postKeepalive(t?t.body:e.json,n,t?.encoding)}if(0===this.queue.length)return;let t=Es-this.inflightKeepaliveBytes-(e&&this.inFlight?.early&&this.inFlight.onWire?this.inFlight.sent?.bytes??this.inFlight.bytes:0),n=this.mintBatchId(),r=this.envelopeBytes,i=0;for(let e of this.queue){let n=this.eventBytes(e)+(0===i?0:1);if(r+n>t)break;r+=n,i++}if(0===i)return;let s=this.queue.splice(0,i);this.uncount(s);let o=this.body(s,n);this.postKeepalive(o,As(o))}postKeepalive(e,t,n){try{this.inflightKeepaliveBytes+=t,fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey,...n?{"Content-Encoding":n}:{}},body:e,keepalive:!0}).then(e=>e.arrayBuffer()).catch(()=>{}).finally(()=>{this.inflightKeepaliveBytes-=t})}catch{this.inflightKeepaliveBytes-=t}}handleOnline=()=>{try{this.config.beforeOnlineFlush?.()}catch{}this.wakeSender?.(),this.flush(this.rushDeferred)};handleUnload=e=>{if("pagehide"===e.type)try{this.config.beforeUnloadFlush?.()}catch{}this.flushOnUnload("beforeunload"===e.type),this.disarmWhenDrained()};handleVisibility=()=>{"hidden"===document.visibilityState&&(this.config.beforeHiddenFlush?.(),this.flush(!0))};get queueSize(){return this.pendingCount()}};function Cs(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}var Os=null,$s=!1;function Ds(){return Os||(Os=fi(()=>import("rrweb")).then(e=>($s=!0,{record:bi(e).record}),e=>(Os=null,{failed:Lr(e)}))),Os}var Ns=null,zs=!1;function Ls(e){return e?Promise.all([Ds(),Ns??=ki(()=>import("@keploy/capture-sdk/strict-attributes"),void 0).then(e=>{if("function"!=typeof e.kept)throw new TypeError("strict-attributes has no kept()");return function(e){In=e}(e.kept),zs=!0,null}).catch(e=>(Ns=null,Lr(e)))]).then(([e,t])=>null===t||"failed"in e?e:{failed:t,strict:!0}):Ds()}var Bs=[new Set,new Set],Us=[0,0],Ps=e=>e.strict?new qr({reason:e.failed}):new jr({reason:e.failed});function qs(){let e=document.documentElement;return{width:window.innerWidth||e?.clientWidth||document.body?.clientWidth||0,height:window.innerHeight||e?.clientHeight||document.body?.clientHeight||0}}function js(e){return e.split("#").map(e=>{let t=e.indexOf("?");return-1===t?e:e.slice(0,t)}).join("#")}var Ms=new Map,Ks="",Ws=-1,Fs=null;function Hs(e){return 2===e.kind?`2${e.before}/${e.value}`:`${e.kind}${e.value}`}function Zs(e){let t=!1;for(let n=e.length-1;n>=0;n--){let r=Hs(e[n]);Ms.delete(r)||(t=!0),Ms.set(r,e[n])}let n=new Set(e.map(Hs)),r=0;for(let e of Ms.keys())r+=e.length;for(let e of Ms.keys()){if(n.has(e)||Ms.size<=256&&r<=65536)break;Ms.delete(e),r-=e.length,t=!0}return t}var Vs=new Set;function Js(e){let t=st;if(e!==Ks||t!==Ws){let n=!1;if(""===Ks||t!==Ws){let e=globalThis.performance?.getEntriesByType?.("navigation");e?.[0]&&(n=Zs(yt(e[0].name)));for(let e of Vs)Zs(yt(e))&&(n=!0)}Ks=e,Ws=t,function(e){Vs.delete(e),Vs.add(e);let t=0;for(let e of Vs)t+=e.length;for(let n of Vs){if(n===e||Vs.size<=64&&t<=524288)break;Vs.delete(n),t-=n.length}}(e),(Zs(yt(e))||n)&&(Fs=en([...Ms.values()]))}return Fs}var Xs=new Set,Gs=null,Qs=null,Ys=null,eo=[],to=null,no=null,ro=new Map,io=!1;function so(e){let t=e,n=t.destination?.url;Ys="string"==typeof n&&"boolean"==typeof t.userInitiated?{href:n,userInitiated:t.userInitiated}:null;let r=t.destination?.key;if("replace"!==t.navigationType){if("traverse"===t.navigationType&&"string"==typeof r){let e=eo[0]===r&&!1===t.userInitiated;e||r===no?ro.set(r,(ro.get(r)??0)+1):ro.delete(r),eo=e?eo.slice(1):[],no=null}else{let n=[];if("push"===t.navigationType)try{let t=e.currentTarget;n=t.entries().slice(0,t.currentEntry.index).map(e=>e.key)}catch{}eo=eo.filter(e=>n.includes(e)),to=null,(!0!==t.userInitiated||!n.includes(no))&&(no=null),ro.clear()}io=!1}}function oo(e,t,n){if("object"==typeof t||"function"==typeof t)return null;let r=e;try{let e=0|Number(t),i=r?.entries()??[],s=null===n?Number(r?.currentEntry?.index):i.findIndex(e=>e.key===n);return s<0?null:i[s+e]?.key??null}catch{return null}}function ao(e,t){return function(...n){if(io)return Reflect.apply(e,this,n);let{next:r,now:i}=t(n);no=i,null!==i&&null!==r&&(to=r,r!==oo(Gs?.navigation??null,0,null)&&eo.push(r)),io=!0;try{return Reflect.apply(e,this,n)}catch(e){throw eo=[],no=null,e}finally{io=!1}}}function lo(e){let t=e,n=t.navigationType,r=function(){let e=Ys;return Ys=null,null!==e&&e.href===location.href?e.userInitiated:void 0}(),i=function(e){let t=e?.currentEntry?.key;if("string"!=typeof t)return;for(;eo[0]===t;)eo.shift();let n=ro.get(t)??0;return n>1?ro.set(t,n-1):ro.delete(t),n?"script":void 0}(Gs?.navigation??null);if("traverse"===n)co("traverse",r,i);else if("push"===n||"replace"===n){let e="string"==typeof t.from?.url?t.from.url:"";co(Qs??(function(e,t){return e!==t&&e.split("#")[0]===t.split("#")[0]}(e,location.href)?"hash":n),r)}}function uo(){let e=Reflect.get(window,"event")?.type;return"popstate"===e||"hashchange"===e?"traverse":"push"}function co(e,t,n){Js(location.href);for(let r of Xs)try{r(e,t,n)}catch{}}function ho([e,t,,n]){let r=Object.getOwnPropertyDescriptor(e,t);return void 0!==r&&r.value===n.value&&r.configurable===n.configurable&&(!0===r.configurable||!0===r.writable)}function fo([e,t,n]){n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}function po(e){if(typeof window>"u"||!window.history)return()=>{};Xs.add(e),function(){if(Gs)return;let e=window.history,t=e.pushState,n=e.replaceState,r=Reflect.get(window,"navigation")??null;r?.addEventListener("currententrychange",lo,{capture:!0}),r?.addEventListener("navigate",so,{capture:!0});let i=e=>t=>{let n=e(t);return{next:oo(r,n,eo.length?to:null),now:oo(r,n,null)}},s=e=>t=>{let n=e(t);return{next:n,now:n}},o=[[e,"back",i(()=>-1)],[e,"forward",i(()=>1)],[e,"go",i(e=>e[0])],[r,"back",s(()=>oo(r,-1,null))],[r,"forward",s(()=>oo(r,1,null))],[r,"traverseTo",s(e=>"string"==typeof e[0]?oo(r,0,e[0]):null)]],a=[[e,"pushState",function(...e){let n=location.href,r=Qs;Qs="push";try{t.apply(this,e)}finally{Qs=r}co(location.href===n?uo():"push")}],[e,"replaceState",function(...e){let t=location.href,r=Qs;Qs="replace";try{n.apply(this,e)}finally{Qs=r}co(location.href===t?uo():"replace")}]];for(let[e,t,n]of o){let r=e&&Reflect.get(e,t);"function"==typeof r&&a.push([e,t,ao(r,n)])}let l=a.find(([e,t])=>!function(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return void 0===n?Object.isExtensible(e):!0===n.configurable||!0===n.writable}(e,t));Gs={navigation:r,methods:l?[]:a.map(([e,t,n])=>function(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);return Object.defineProperty(e,t,!1===r?.configurable?{value:n}:{value:n,writable:!0,enumerable:r?.enumerable??!0,configurable:!0}),[e,t,r,Object.getOwnPropertyDescriptor(e,t)]}(e,t,n)),refused:l?`${l[0]===e?"history":"navigation"}.${l[1]}`:null}}();let t=()=>{Js(location.href),e("traverse")};return window.addEventListener("popstate",t,{capture:!0}),window.addEventListener("hashchange",t,{capture:!0}),()=>{Xs.delete(e),window.removeEventListener("popstate",t,{capture:!0}),window.removeEventListener("hashchange",t,{capture:!0}),function(){if(Gs&&!(Xs.size>0)&&Gs.methods.every(ho)){for(let e of Gs.methods)fo(e);Gs.navigation?.removeEventListener("currententrychange",lo,{capture:!0}),Gs.navigation?.removeEventListener("navigate",so,{capture:!0}),Ys=null,eo=[],no=null,ro.clear(),Gs=null}}()}}var go=class e{phase="idle";userPaused=!1;hidden=!1;droppedWhileShut=!1;baselineLost=!1;retakeTimer=null;retakeAtOnce=!1;retakeDelay=5e3;outage=!1;failing(e){this.outage=e,null!==this.retakeTimer&&clearTimeout(this.retakeTimer),this.retakeTimer=null,!e&&this.baselineLost&&this.rebaseline(!1)}lost(e,t){t||!e.some(e=>"dom"===e.type)||(this.baselineLost=!0,this.rebaseline(e.some(e=>"dom"===e.type&&2===e.data?.type)))}rebaseline(e){if(this.outage)return;if(null!==this.retakeTimer){if(!e||!this.retakeAtOnce)return;clearTimeout(this.retakeTimer)}this.retakeAtOnce=!e;let t=e?this.retakeDelay:0;e&&(this.retakeDelay=Math.min(2*this.retakeDelay,6e4)),this.retakeTimer=setTimeout(()=>{if(this.retakeTimer=null,!this.baselineLost||"recording"!==this.getState())return;let e=this.rrwebRecord?.takeFullSnapshot;if(e){this.droppedWhileShut=!1;try{e.call(this.rrwebRecord)}catch{this.droppedWhileShut=!0}}},t)}delivered(e){e.some(e=>"dom"===e.type&&2===e.data?.type)&&(this.retakeDelay=5e3)}styles=new nn({note:e=>{let t=this.rrwebRecord?.mirror?.getNode(e);t&&this.styleNodes.set(e,t)},present:e=>this.inPage(e),forget:e=>{this.styleNodes.delete(e)}});styleNodes=new Map;sessionId=null;metadata=null;config;onEvent=null;onSessionEnd=null;onScrubOversized=null;onRRWeb=null;landing=!1;onlineRetry=null;onlinePoll=null;rrwebStopFn=null;rrwebRecord=null;rrwebRequested=!1;generation=0;sessionTimer=null;visibilityHandler=null;stopNavigation=null;lastHref="";seenHref="";constructor(e){this.config=e}async start(e,t=null,n=!1,r=null,i=null,s=null){if("active"===this.phase)return this.sessionId;"stopping"===this.phase&&this.stop();let o={secretRoutes:[],keepRoutes:[]};for(let e of["secretRoutes","keepRoutes"]){let t=this.config.privacy?.[e]??[];if(!Array.isArray(t))throw this.phase="stopped",new Mr({option:e,received:Fr({returned:t})});for(let n of t){let t=nt(n,"keepRoutes"===e);if(null===t)throw this.phase="stopped",new Mr({option:e,received:Fr({returned:n})});o[e].push(t)}}!function(e,t){for(let[n,r]of[[rt.secret,e],[rt.keep,t]])for(let e of r){let t=`${n===rt.keep}${e.join("/")}`;it.has(t)||(it.add(t),n.push(e),st++,vt=["",[],!1,null])}}(o.secretRoutes,o.keepRoutes);let a,l=this.config.sampleRate??1;if(Math.random()>l)return this.phase="stopped","";this.onEvent=e,this.onSessionEnd=t,this.onScrubOversized=r,this.onRRWeb=i;try{a=this.config.sessionIdGenerator?this.config.sessionIdGenerator():Cs()}catch(e){throw this.phase="stopped",new Pr({sessionId:null,received:Fr({threw:e})})}if(!br(a))throw this.phase="stopped",new Pr({sessionId:"string"==typeof a?a:null,received:Fr({returned:a})});this.sessionId=a,this.metadata=function(e){let t=typeof window<"u"?window:void 0,n=t?.location?.href??"",r=""===n?null:Js(n);return{url:an(e(n),r),userAgent:typeof navigator<"u"?navigator.userAgent:"",viewport:{width:t?.innerWidth??0,height:t?.innerHeight??0},referrer:typeof document<"u"&&document.referrer?an(e(document.referrer),r):"",language:typeof navigator<"u"?navigator.language:"",devicePixelRatio:t?.devicePixelRatio??1,timestamp:Date.now()}}(this.scrubUrl),this.phase="active",this.userPaused=n,this.droppedWhileShut=!1,this.hidden=typeof document<"u"&&"hidden"===document.visibilityState,this.rrwebRequested=!1;let u=++this.generation;typeof document<"u"&&(this.visibilityHandler=()=>{this.hidden="hidden"===document.visibilityState,"recording"===this.getState()&&this.openDomGate()},document.addEventListener("visibilitychange",this.visibilityHandler)),this.seenHref=typeof location<"u"?location.href:"",this.lastHref=typeof location<"u"?this.scrubUrl(location.href):"",this.stopNavigation=po((e,t,n)=>this.navigated(e,t,n));let c=await this.startRRWeb();if(u!==this.generation||"active"!==this.phase)return"";if(null!==c&&typeof window<"u")throw this.stop(),Ps(c);let d=this.config.maxSessionDuration??6e5;return this.sessionTimer=setTimeout(()=>{try{this.onSessionEnd?.()}finally{"active"===this.phase&&this.stop()}},d),Gs?.refused&&s?.(Gs.refused),this.sessionId}stopDom(){"active"===this.phase&&(this.phase="stopping"),this.rrwebStopFn&&(this.rrwebStopFn(),this.rrwebStopFn=null),this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}stop(){if("active"===this.phase||"stopping"===this.phase){null!==this.onlineRetry&&(window.removeEventListener("online",this.onlineRetry),this.onlineRetry=null,this.stopOnlinePoll()),this.landing=!1;for(let e of Bs)e.delete(this);this.stopDom(),this.rrwebRecord=null,this.retakeTimer&&(clearTimeout(this.retakeTimer),this.retakeTimer=null),this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.stopNavigation?.(),this.stopNavigation=null,this.phase="stopped"}}navigated(e,t,n){if("active"!==this.phase)return;this.seenHref=location.href;let r=this.scrubUrl(location.href);js(r)!==js(this.lastHref)&&(this.lastHref=r,this.emitEvent("dom",{type:4,data:{href:r,...qs(),cause:e,...void 0===t?{}:{userInitiated:t},...void 0===n?{}:{initiator:n}},timestamp:Date.now()}))}recordedRRWebEvent(e){if("object"!=typeof e||null===e)return e;let t=e,n=t.data?.href;return 4!==t.type||"string"!=typeof n?e:(this.lastHref=this.scrubUrl(n),{...t,data:{...t.data,href:this.lastHref}})}isUserPaused(){return this.userPaused}pause(){"active"===this.phase&&(this.userPaused=!0)}resume(){"active"===this.phase&&(this.userPaused=!1,"recording"===this.getState()&&this.openDomGate())}openDomGate(){if(!this.rrwebStopFn){this.droppedWhileShut=!1;let e=this.generation;return void this.startRRWeb().then(t=>{null!==t?this.refuseLate(e,t):this.landedBeforeTheRetry(e)})}if(!this.droppedWhileShut&&!this.baselineLost)return;let e=this.rrwebRecord?.takeFullSnapshot;if(e){if(this.outage)return void(this.baselineLost=!0);this.droppedWhileShut=!1;try{e.call(this.rrwebRecord)}catch{this.droppedWhileShut=!0}}}getSessionId(){return"active"===this.phase?this.sessionId:null}get sessionOpen(){return"active"===this.phase&&!this.userPaused}getState(){return"idle"===this.phase?"idle":"stopped"===this.phase||"stopping"===this.phase?"stopped":this.userPaused||this.hidden?"paused":"recording"}getMetadata(){return this.metadata}async startRRWeb(){if(this.rrwebRequested)return null;this.rrwebRequested=!0;let t=this.generation;if(!this.loaded()&&typeof window<"u"&&!1===navigator.onLine&&!function(){try{return!!navigator.serviceWorker?.controller}catch{return!1}}())return this.rrwebRequested=!1,this.retryWhenOnline(t),null;let n=+("strict"===this.config.privacyMode);if(Us[n])return Bs[n].add(this),this.land();let r=Ls(n>0),i=await ai(r,this.loaded());if(!i)return t===this.generation&&"active"===this.phase&&(Bs[n].add(this),this.land(),Us[n]||e.whenLanded(n,r)),null;if(t!==this.generation)return null;if("failed"in i)return this.rrwebRequested=!1,i;let s=i.record;return"recording"!==this.getState()?(this.rrwebRequested=!1,null):(this.rrwebRecord=s,this.rrwebStopFn=s(this.rrwebOptions())??null,null)}retryWhenOnline(e){if(null!==this.onlineRetry)return;let t=()=>{if(window.removeEventListener("online",t),this.stopOnlinePoll(),this.onlineRetry=null,e===this.generation&&"active"===this.phase){if(!1===navigator.onLine)return void this.retryWhenOnline(e);Ls("strict"===this.config.privacyMode).then(t=>this.loadedLate(e,t))}};this.onlineRetry=t,window.addEventListener("online",t,{once:!0}),this.onlinePoll=setInterval(()=>{!1!==navigator.onLine&&t()},1e3)}static whenLanded(e,t){Us[e]++,t.then(t=>{Us[e]--;let n=[...Bs[e]];Bs[e].clear();for(let e of n)e.landing&&e.loadedLate(e.generation,t)})}land(){return this.rrwebRequested=!1,this.landing=!0,null}loadedLate(e,t){if(e===this.generation&&"active"===this.phase){if(this.landing=!1,"failed"in t)return void this.refuseLate(e,t);this.startRRWeb(),this.onRRWeb?.(null)}}stopOnlinePoll(){null!==this.onlinePoll&&(clearInterval(this.onlinePoll),this.onlinePoll=null)}refuseLate(e,t){e!==this.generation||"active"!==this.phase||(this.stop(),this.onRRWeb?.(Ps(t)))}landedBeforeTheRetry(e){e!==this.generation||"active"!==this.phase||!this.loaded()||null===this.onlineRetry||(window.removeEventListener("online",this.onlineRetry),this.onlineRetry=null,this.stopOnlinePoll(),this.onRRWeb?.(null))}loaded(){return $s&&(zs||"strict"!==this.config.privacyMode)}awaitingRRWeb(){return null!==this.onlineRetry||this.landing}rrwebOptions(){let e=this.config.privacyMode??"balanced",t=this.config.privacy??{},n=[...this.config.maskSelectors??[],...t.maskSelectors??[]],r=[...this.config.unmaskSelectors??[],...t.unmaskSelectors??[]],i="off"!==e,s={color:i,date:i,"datetime-local":i,email:i,file:i,month:i,number:i,range:i,search:i,tel:i,text:i,time:i,url:i,week:i,textarea:i,select:i,password:!0,hidden:!0},o='[contenteditable]:not([contenteditable="false"])',a=[...n,...i?[o]:[]].join(","),l=r.join(","),u=l?(e,t)=>{try{if(i&&t?.closest(o))return e.replace(/[\S]/g,"*");if(t?.closest(l))return e}catch{}return e.replace(/[\S]/g,"*")}:void 0;return{emit:e=>this.emitEvent("dom",e,e=>this.recordedRRWebEvent(e)),maskTextSelector:"strict"===e?"*":a||void 0,...u?{maskTextFn:u}:{},blockSelector:t.blockSelectors?.join(",")||void 0,maskInputOptions:s,userTriggeredOnInput:!0}}inPage(e){let t=this.rrwebRecord?.mirror;if(void 0===t)return!0;let n=this.styleNodes.get(e)??t.getNode(e);if(!n||!n.isConnected)return!1;for(let e=n.ownerDocument;null!==e&&e!==document;){let t=e.defaultView?.frameElement??null;if(null===t||!t.isConnected)return!1;e=t.ownerDocument}return!0}noticeUnheardMove(e){if(!(typeof location>"u"||location.href===this.seenHref)){if(4===e?.type)return void(this.seenHref=location.href);this.navigated(uo())}}scrubUrl=e=>function(e,t=!1){return e&&O(e,t?qn:Pn)}(function(e){let[,t,n]=mt(e);if(t)return`${gt(e)}/[REDACTED]`;let r=e.indexOf("#"),i=Ge(ht(e),Qe(Re(e))),s=Ce(-1===r?e:e.slice(0,r),i);if(-1!==r){let t=e.slice(r+1).split("#")[0];Oe.test(t)&&(s+=`#${Ce(t,i)}`)}return null===n?s:Mt(s,n)}(e),"strict"===(this.config.privacyMode??"balanced"));scrubDomUrls(e,t){let n=e;if(null===n||"object"!=typeof n)return e;let r=n.data;if(null===r||"object"!=typeof r)return e;let i="strict"===(this.config.privacyMode??"balanced"),s=null===t?[]:[...t.plain,...t.bounded];if(2===n.type&&ar(r.node,i,s),3===n.type&&0===r.source){if(Array.isArray(r.adds)){!function(e){let t=new Map;for(let n of e){let e=n?.node?.type;(3===e||5===e)&&t.set(n.node.id,n)}let n=new Set;for(let e of t.values())n.add(t.get(e.nextId));for(let e of t.values()){if(n.has(e))continue;let r=[];for(let n=e;n;n=t.get(n.nextId))sr(n.node)&&r.push(n.node);r.length>1&&ir(r)}}(r.adds);for(let e of r.adds)null!==e&&"object"==typeof e&&ar(e.node,i,s)}if(Array.isArray(r.attributes))for(let e of r.attributes){let t=e?.attributes;if(null!==t&&"object"==typeof t){let n=i?this.rrwebRecord?.mirror?.getNode(e.id??-1):null;Xn(t,i,s,n?.localName??"","http://www.w3.org/2000/svg"===n?.namespaceURI)}}if(Array.isArray(r.texts)){let e=this.styles.recordsIn(n);for(let t of r.texts)"string"==typeof t?.value&&(t.value=e.has(t)?rr(t.value,i,s):er(t.value))}}if(3===n.type&&(8===r.source||15===r.source)){let e=[...Array.isArray(r.adds)?r.adds:[],...Array.isArray(r.styles)?r.styles.flatMap(e=>Array.isArray(e?.rules)?e.rules:[]):[]];for(let t of e)null!==t&&"string"==typeof t?.rule&&(t.rule=rr(t.rule,i,s));"string"==typeof r.replace&&(r.replace=rr(r.replace,i,s)),"string"==typeof r.replaceSync&&(r.replaceSync=rr(r.replaceSync,i,s))}if(3===n.type&&5===r.source&&"string"==typeof r.text&&(r.text=i?r.text.replace(/\S/g,"*"):er(r.text)),3===n.type&&9===r.source&&"string"==typeof r.fontSource&&(r.fontSource=rr(r.fontSource,i,s)),3===n.type&&13===r.source){let e=r.set;null!==e&&"string"==typeof e?.value&&(e.value=rr(e.value,i,s))}return e}acceptsNetwork(){return this.sessionOpen}emitEvent(e,t,n,r=!1,i,s){if("dom"===e&&"active"===this.phase&&"recording"!==this.getState()&&(this.droppedWhileShut=!0),(r?"active"!==this.phase&&"stopping"!==this.phase:!this.sessionOpen)||"dom"===e&&this.hidden||!this.onEvent||!this.sessionId)return;this.noticeUnheardMove("dom"===e?t:null);let o=n?n(t):t,a="dom"===e&&null!==o&&"object"==typeof o?o.type:void 0;if(this.baselineLost&&3===a)return;let l=o;if(typeof location<"u")try{"dom"===e&&(l=this.scrubDomUrls(o,Js(location.href))),l=an(l,Js(location.href),e,this.styles,Ts)}catch(t){return"dom"===e&&(this.baselineLost=!0,this.rebaseline(2===a)),void(t instanceof rn&&this.onScrubOversized?.(e,t.atLeast,t.cap))}2===a&&(this.baselineLost=!1,null!==this.retakeTimer&&(clearTimeout(this.retakeTimer),this.retakeTimer=null));let u={id:Cs(),sessionId:this.sessionId,timestamp:i??Date.now(),type:e,data:l,seq:s};this.onEvent(u)}};function yo(){let e=typeof crypto<"u"?crypto:void 0;if(!e||"function"!=typeof e.getRandomValues)return null;let t=new Uint8Array(16);e.getRandomValues(t);let n="";for(let e of t)n+=e.toString(16).padStart(2,"0");return n}function vo(){if(typeof window>"u"||!window.location)return null;let e=window.location.origin;return"string"!=typeof e||""===e||"null"===e?null:e}var mo=class{captureId;nonce;t0WallMs;origins;constructor(e,t=Date.now()){this.captureId=e,this.nonce=yo(),this.t0WallMs=t;let n=vo();this.origins=null===n?[]:[n]}build(){return null===this.nonce?{refusal:"no-csprng"}:{identity:{captureId:this.captureId,sessionNonce:this.nonce,t0WallMs:this.t0WallMs,appOrigins:[...this.origins]}}}},wo=!1,bo=class e{static instance=null;recorder;network;transport;config;started=!1;identity=null;constructor(e){this.config=e,this.recorder=new go(e),this.network=new Ss(e.privacy??{},e.maxBodySize??524288,[e.endpoint],e.privacyMode);let t={endpoint:e.endpoint,apiKey:e.apiKey,batchSize:e.batchSize??50,batchInterval:e.batchInterval??5e3,maxQueueSize:e.maxQueueSize??5e3,...void 0!==e.onError?{onError:e.onError}:{},onCaptureEnd:()=>this.endCapture(),endsSessionOnly:(t,n)=>!0===e.continuous&&void 0===e.sessionIdGenerator&&("KUI_E_SESSION_CONFLICT"===t&&"session_completed"===n||"KUI_E_INGEST_REJECTED"===t&&"session_full"===n),onSessionEnd:()=>this.endSession(),onDropped:(e,t)=>this.recorder.lost(e,t),onDelivered:e=>this.recorder.delivered(e),onFailing:e=>this.recorder.failing(e),beforeUnloadFlush:()=>this.network.cutInflight(),beforeHiddenFlush:()=>this.network.reportDue(),beforeOnlineFlush:()=>this.network.reportDue()};this.transport=new _s(t)}static async init(t){if(e.instance)return e.instance;let n=e.nextSessionPaused;return e.cancelNextSession(),e.nextSessionPaused=!1,e.begin(t,n)}static async begin(t,n,r=!1){let i=new e(t);e.instance=i;try{await i.start(n,r)}catch(t){throw e.instance===i&&(e.instance=null),t}return i}static stop(){e.cancelNextSession(),e.nextSessionPaused=!1;let t=e.instance;e.instance=null;let n=Promise.all(e.ending),r=new Promise(e=>{let t=setTimeout(e,1e4);n.then(()=>{clearTimeout(t),e()})});return t||r.then(()=>{!e.instance&&!e.restartPending&&(mi(!1),Xi())}),Promise.all([t?t.stop():void 0,r]).then(()=>{})}static pause(){e.instance?.pause(),null===e.instance&&e.restartPending&&(e.nextSessionPaused=!0)}static resume(){e.instance?.resume(),e.nextSessionPaused=!1}static getSessionId(){return e.instance?.recorder.getSessionId()??""}static getInstance(){return e.instance}static getCaptureIdentity(){let t=e.instance?.identity;return t?t.build():null}async start(t,n=!1){if(this.started)return;if(this.started=!0,"strict"===this.config.privacyMode&&!1===this.config.privacy?.maskNetworkBodies)return void this.refuse(new Wr);let r=!1!==this.config.honorPrivacySignals?function(){try{if(typeof navigator>"u")return null;let e=navigator;if(!0===e.globalPrivacyControl)return"globalPrivacyControl";if("1"===e.doNotTrack||"yes"===e.doNotTrack||typeof window<"u"&&"1"===window.doNotTrack||"1"===e.msDoNotTrack)return"doNotTrack"}catch{}return null}():null;if(null!==r)return void this.decline(new Kr(r));let i,s=[],o=e=>{s?s.push(e):this.transport.enqueue(e)};try{mi(!0,!n);let e=this.recorder.start(o,()=>!0===this.config.continuous&&void 0===this.config.sessionIdGenerator?this.endSession():this.endCapture(),t,(e,t,n)=>this.transport.reportScrubOversized(e,t,n),e=>{null===e?this.transport.release():this.refuse(e)},e=>this.transport.reportNavigationUnwrapped(e));!1!==this.config.networkCapture&&null!==this.recorder.getSessionId()&&this.network.askForCode(),i=await e}catch(e){if(!(e instanceof Pr||e instanceof jr||e instanceof qr||e instanceof Mr))throw e;return void this.refuse(e)}if(!i)return this.started=!1,void((e.instance??this)===this&&mi(!1));let a=this.recorder.getMetadata();this.identity=new mo(i);let l=this.identity.build();this.recorder.awaitingRRWeb()&&this.transport.hold(),this.transport.start(i,a,"identity"in l?l.identity:null);let u=s;s=null;for(let e of u)this.transport.enqueue(e);!1!==this.config.networkCapture&&this.network.start((e,t,n)=>{this.recorder.emitEvent("network",e,void 0,!0,t,n)},()=>this.recorder.acceptsNetwork(),()=>this.transport.place())}stop(){return this.network.reportDue(),this.recorder.stopDom(),this.network.stop(),this.started=!1,this.network.settle(1e3).then(()=>{let t=null===e.instance;return Xi(t,()=>null!==e.instance||e.restartPending),t&&!e.restartPending&&mi(!1),this.recorder.stop(),this.transport.stop()})}decline(e){wo||console.info(e.message),wo=!0,this.endCapture();try{this.config.onError?.(e)}catch{}}refuse(e){console.error(e.message),this.endCapture();try{this.config.onError?.(e)}catch{}}endCapture(){let t=this.stop().catch(()=>{}).finally(()=>e.ending.delete(t));e.ending.add(t),e.instance===this&&(e.instance=null)}static cancelNextSession=()=>{};static nextSessionPaused=!1;static ending=new Set;static restartPending=!1;endSession(){let t=e.instance===this,n=this.recorder.isUserPaused();if(this.endCapture(),!t||typeof document>"u")return;e.cancelNextSession(),e.nextSessionPaused=n;let r={...this.config,sampleRate:1},i=()=>{let t=e.nextSessionPaused;e.cancelNextSession(),e.nextSessionPaused=!1,null===e.instance&&e.begin(r,t,!0).catch(e=>{console.warn("[keploy] the capture's next session could not start:",e)})},s={capture:!0,passive:!0};document.addEventListener("pointerdown",i,s),document.addEventListener("keydown",i,s);let o=po(()=>{});e.restartPending=!0,e.cancelNextSession=()=>{o(),document.removeEventListener("pointerdown",i,s),document.removeEventListener("keydown",i,s),e.restartPending=!1,e.cancelNextSession=()=>{}}}pause(){this.recorder.pause(),this.network.cutBodies()}resume(){this.recorder.resume()}};//# sourceMappingURL=index.js.map
|