@nagoorkani/session-capture-expo 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +112 -0
- package/dist/device.d.ts +23 -0
- package/dist/index.d.ts +105 -0
- package/dist/index.js +1824 -0
- package/dist/index.mjs +1801 -0
- package/dist/lifecycle.d.ts +20 -0
- package/dist/store-expo.d.ts +35 -0
- package/package.json +60 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1824 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
DEFAULT_CONFIG: () => DEFAULT_CONFIG,
|
|
24
|
+
MemoryStore: () => MemoryStore,
|
|
25
|
+
SCHEMA_VERSION: () => SCHEMA_VERSION,
|
|
26
|
+
SDK_VERSION: () => SDK_VERSION,
|
|
27
|
+
breadcrumb: () => breadcrumb,
|
|
28
|
+
captureException: () => captureException,
|
|
29
|
+
createPersistentStore: () => createPersistentStore,
|
|
30
|
+
currentConfig: () => currentConfig,
|
|
31
|
+
endMeasure: () => endMeasure,
|
|
32
|
+
flush: () => flush,
|
|
33
|
+
identify: () => identify,
|
|
34
|
+
init: () => init,
|
|
35
|
+
isEnabled: () => isEnabled,
|
|
36
|
+
isSampled: () => isSampled,
|
|
37
|
+
isSelfDisabled: () => isSelfDisabled,
|
|
38
|
+
keepSessionAlive: () => keepSessionAlive,
|
|
39
|
+
markAppReady: () => markAppReady,
|
|
40
|
+
onError: () => onError,
|
|
41
|
+
onSession: () => onSession,
|
|
42
|
+
pendingBatches: () => pendingBatches,
|
|
43
|
+
safe: () => safe,
|
|
44
|
+
safeAsync: () => safeAsync,
|
|
45
|
+
screen: () => screen,
|
|
46
|
+
setEnabled: () => setEnabled,
|
|
47
|
+
shutdown: () => shutdown,
|
|
48
|
+
startMeasure: () => startMeasure,
|
|
49
|
+
track: () => track
|
|
50
|
+
});
|
|
51
|
+
module.exports = __toCommonJS(index_exports);
|
|
52
|
+
|
|
53
|
+
// ../core/src/batcher.ts
|
|
54
|
+
var DEFAULT_MAX_BUFFERED = 1e3;
|
|
55
|
+
var Batcher = class {
|
|
56
|
+
constructor(options) {
|
|
57
|
+
this.buffer = [];
|
|
58
|
+
this.timer = null;
|
|
59
|
+
this.droppedCount = 0;
|
|
60
|
+
this.options = options;
|
|
61
|
+
this.maxBuffered = options.maxBuffered ?? DEFAULT_MAX_BUFFERED;
|
|
62
|
+
}
|
|
63
|
+
/** Events discarded due to the buffer ceiling. */
|
|
64
|
+
get dropped() {
|
|
65
|
+
return this.droppedCount;
|
|
66
|
+
}
|
|
67
|
+
get size() {
|
|
68
|
+
return this.buffer.length;
|
|
69
|
+
}
|
|
70
|
+
add(event) {
|
|
71
|
+
if (this.buffer.length >= this.maxBuffered) {
|
|
72
|
+
this.buffer.shift();
|
|
73
|
+
this.droppedCount += 1;
|
|
74
|
+
}
|
|
75
|
+
this.buffer.push(event);
|
|
76
|
+
if (this.buffer.length >= this.options.maxSize) {
|
|
77
|
+
void this.flush();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
this.scheduleFlush();
|
|
81
|
+
}
|
|
82
|
+
/** Send whatever is buffered. No-op when empty. */
|
|
83
|
+
async flush() {
|
|
84
|
+
this.clearTimer();
|
|
85
|
+
if (this.buffer.length === 0) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const events = this.buffer;
|
|
89
|
+
this.buffer = [];
|
|
90
|
+
await this.options.onFlush(events);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Adopt new batching parameters, e.g. from remote config.
|
|
94
|
+
*
|
|
95
|
+
* A pending timer is left alone deliberately: restarting it on every config
|
|
96
|
+
* fetch would let a short interval keep resetting itself and delay the flush
|
|
97
|
+
* indefinitely. The new interval applies from the next scheduled flush.
|
|
98
|
+
*/
|
|
99
|
+
reconfigure(options) {
|
|
100
|
+
if (options.maxSize !== void 0) {
|
|
101
|
+
this.options.maxSize = options.maxSize;
|
|
102
|
+
}
|
|
103
|
+
if (options.flushIntervalMs !== void 0) {
|
|
104
|
+
this.options.flushIntervalMs = options.flushIntervalMs;
|
|
105
|
+
}
|
|
106
|
+
if (this.buffer.length >= this.options.maxSize) {
|
|
107
|
+
void this.flush();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Stop the timer. Call during teardown; does not flush. */
|
|
111
|
+
stop() {
|
|
112
|
+
this.clearTimer();
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Discard everything buffered and stop the timer.
|
|
116
|
+
*
|
|
117
|
+
* For consent withdrawal and the remote kill switch, where the buffer must
|
|
118
|
+
* not merely go unsent — it must go. Returns how many events were dropped.
|
|
119
|
+
*/
|
|
120
|
+
drop() {
|
|
121
|
+
this.clearTimer();
|
|
122
|
+
const dropped = this.buffer.length;
|
|
123
|
+
this.buffer = [];
|
|
124
|
+
return dropped;
|
|
125
|
+
}
|
|
126
|
+
scheduleFlush() {
|
|
127
|
+
if (this.timer !== null) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
this.timer = setTimeout(() => {
|
|
131
|
+
this.timer = null;
|
|
132
|
+
void this.flush();
|
|
133
|
+
}, this.options.flushIntervalMs);
|
|
134
|
+
this.timer?.unref?.();
|
|
135
|
+
}
|
|
136
|
+
clearTimer() {
|
|
137
|
+
if (this.timer !== null) {
|
|
138
|
+
clearTimeout(this.timer);
|
|
139
|
+
this.timer = null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// ../core/src/redact.ts
|
|
145
|
+
var DENIED_KEYS = /* @__PURE__ */ new Set([
|
|
146
|
+
"authorization",
|
|
147
|
+
"cookie",
|
|
148
|
+
"set-cookie",
|
|
149
|
+
"proxy-authorization"
|
|
150
|
+
]);
|
|
151
|
+
var DENIED_PATTERN = /token|key|secret|password|passwd|auth|session|credential/i;
|
|
152
|
+
var REDACTED = "[redacted]";
|
|
153
|
+
var MAX_DEPTH = 8;
|
|
154
|
+
function isDenied(key, extraKeys) {
|
|
155
|
+
const lower = key.toLowerCase();
|
|
156
|
+
return DENIED_KEYS.has(lower) || extraKeys.has(lower) || DENIED_PATTERN.test(key);
|
|
157
|
+
}
|
|
158
|
+
function redact(value, maskedKeys = []) {
|
|
159
|
+
const extra = new Set(maskedKeys.map((k) => k.toLowerCase()));
|
|
160
|
+
return walk(value, extra, 0, /* @__PURE__ */ new WeakSet());
|
|
161
|
+
}
|
|
162
|
+
function walk(value, extra, depth, seen) {
|
|
163
|
+
if (value === null || typeof value !== "object") {
|
|
164
|
+
return value;
|
|
165
|
+
}
|
|
166
|
+
if (depth >= MAX_DEPTH) {
|
|
167
|
+
return REDACTED;
|
|
168
|
+
}
|
|
169
|
+
if (seen.has(value)) {
|
|
170
|
+
return REDACTED;
|
|
171
|
+
}
|
|
172
|
+
seen.add(value);
|
|
173
|
+
if (Array.isArray(value)) {
|
|
174
|
+
return value.map((item) => walk(item, extra, depth + 1, seen));
|
|
175
|
+
}
|
|
176
|
+
const out = {};
|
|
177
|
+
for (const [key, item] of Object.entries(value)) {
|
|
178
|
+
out[key] = isDenied(key, extra) ? REDACTED : walk(item, extra, depth + 1, seen);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ../core/src/breadcrumbs.ts
|
|
184
|
+
var MAX_BREADCRUMBS = 20;
|
|
185
|
+
var MAX_MESSAGE_CHARS = 200;
|
|
186
|
+
var buffer = [];
|
|
187
|
+
function addBreadcrumb(type, message, data, maskedKeys = [], now = Date.now()) {
|
|
188
|
+
if (buffer.length >= MAX_BREADCRUMBS) {
|
|
189
|
+
buffer.shift();
|
|
190
|
+
}
|
|
191
|
+
const crumb = { timestamp: now, type };
|
|
192
|
+
if (message !== void 0) {
|
|
193
|
+
crumb.message = message.slice(0, MAX_MESSAGE_CHARS);
|
|
194
|
+
}
|
|
195
|
+
if (data !== void 0) {
|
|
196
|
+
crumb.data = redact(data, maskedKeys);
|
|
197
|
+
}
|
|
198
|
+
buffer.push(crumb);
|
|
199
|
+
}
|
|
200
|
+
function snapshotBreadcrumbs(now = Date.now()) {
|
|
201
|
+
return buffer.map(({ timestamp, ...rest }) => ({
|
|
202
|
+
t: now - timestamp,
|
|
203
|
+
...rest
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
function clearBreadcrumbs() {
|
|
207
|
+
buffer.length = 0;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ../core/src/types.ts
|
|
211
|
+
var SCHEMA_VERSION = 1;
|
|
212
|
+
var DEFAULT_CONFIG = {
|
|
213
|
+
enabled: true,
|
|
214
|
+
sampleRate: 1,
|
|
215
|
+
batchSize: 50,
|
|
216
|
+
flushIntervalMs: 1e4,
|
|
217
|
+
maskedKeys: [],
|
|
218
|
+
urlDenyList: [],
|
|
219
|
+
captureBodies: false,
|
|
220
|
+
replayEnabled: false,
|
|
221
|
+
replaySampleRate: 0,
|
|
222
|
+
configVersion: 0
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// ../core/src/config.ts
|
|
226
|
+
var FETCH_TIMEOUT_MS = 1e4;
|
|
227
|
+
var LIMITS = {
|
|
228
|
+
batchSize: { min: 1, max: 1e3 },
|
|
229
|
+
flushIntervalMs: { min: 1e3, max: 5 * 60 * 1e3 },
|
|
230
|
+
listEntries: 100
|
|
231
|
+
};
|
|
232
|
+
var CACHE_FILE = "remote-config.json";
|
|
233
|
+
function clamp(value, min, max) {
|
|
234
|
+
return Math.min(max, Math.max(min, value));
|
|
235
|
+
}
|
|
236
|
+
function asNumber(value, fallback, min, max) {
|
|
237
|
+
return typeof value === "number" && Number.isFinite(value) ? clamp(value, min, max) : fallback;
|
|
238
|
+
}
|
|
239
|
+
function asBoolean(value, fallback) {
|
|
240
|
+
return typeof value === "boolean" ? value : fallback;
|
|
241
|
+
}
|
|
242
|
+
function asStringList(value, fallback) {
|
|
243
|
+
if (!Array.isArray(value)) return [...fallback];
|
|
244
|
+
return value.filter((entry) => typeof entry === "string" && entry.length > 0).slice(0, LIMITS.listEntries);
|
|
245
|
+
}
|
|
246
|
+
function sanitizeConfig(raw, base = DEFAULT_CONFIG) {
|
|
247
|
+
if (typeof raw !== "object" || raw === null) {
|
|
248
|
+
return { ...base };
|
|
249
|
+
}
|
|
250
|
+
const input = raw;
|
|
251
|
+
return {
|
|
252
|
+
enabled: asBoolean(input.enabled, base.enabled),
|
|
253
|
+
sampleRate: asNumber(input.sampleRate, base.sampleRate, 0, 1),
|
|
254
|
+
batchSize: Math.round(
|
|
255
|
+
asNumber(input.batchSize, base.batchSize, LIMITS.batchSize.min, LIMITS.batchSize.max)
|
|
256
|
+
),
|
|
257
|
+
flushIntervalMs: Math.round(
|
|
258
|
+
asNumber(
|
|
259
|
+
input.flushIntervalMs,
|
|
260
|
+
base.flushIntervalMs,
|
|
261
|
+
LIMITS.flushIntervalMs.min,
|
|
262
|
+
LIMITS.flushIntervalMs.max
|
|
263
|
+
)
|
|
264
|
+
),
|
|
265
|
+
maskedKeys: asStringList(input.maskedKeys, base.maskedKeys),
|
|
266
|
+
urlDenyList: asStringList(input.urlDenyList, base.urlDenyList),
|
|
267
|
+
captureBodies: asBoolean(input.captureBodies, base.captureBodies),
|
|
268
|
+
replayEnabled: asBoolean(input.replayEnabled, base.replayEnabled),
|
|
269
|
+
replaySampleRate: asNumber(input.replaySampleRate, base.replaySampleRate, 0, 1),
|
|
270
|
+
configVersion: Math.round(
|
|
271
|
+
asNumber(input.configVersion, base.configVersion, 0, Number.MAX_SAFE_INTEGER)
|
|
272
|
+
)
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
async function fetchRemoteConfig(options) {
|
|
276
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
277
|
+
const base = options.endpoint.replace(/\/$/, "");
|
|
278
|
+
const url = `${base}/v1/config?projectId=${encodeURIComponent(options.projectId)}`;
|
|
279
|
+
const controller = new AbortController();
|
|
280
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS);
|
|
281
|
+
try {
|
|
282
|
+
const response = await doFetch(url, {
|
|
283
|
+
method: "GET",
|
|
284
|
+
headers: {
|
|
285
|
+
accept: "application/json",
|
|
286
|
+
authorization: `Bearer ${options.apiKey}`
|
|
287
|
+
},
|
|
288
|
+
signal: controller.signal
|
|
289
|
+
});
|
|
290
|
+
if (!response.ok) {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
return sanitizeConfig(await response.json());
|
|
294
|
+
} catch {
|
|
295
|
+
return null;
|
|
296
|
+
} finally {
|
|
297
|
+
clearTimeout(timer);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
async function loadCachedConfig(store) {
|
|
301
|
+
try {
|
|
302
|
+
const raw = await store.read(CACHE_FILE);
|
|
303
|
+
if (raw === null) return null;
|
|
304
|
+
return sanitizeConfig(JSON.parse(raw));
|
|
305
|
+
} catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
async function saveConfig(store, config) {
|
|
310
|
+
try {
|
|
311
|
+
await store.write(CACHE_FILE, JSON.stringify(config));
|
|
312
|
+
} catch {
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ../core/src/errors.ts
|
|
317
|
+
var MAX_STACK_CHARS = 8 * 1024;
|
|
318
|
+
var MAX_MESSAGE_CHARS2 = 1024;
|
|
319
|
+
function describeError(value, handled) {
|
|
320
|
+
if (value instanceof Error) {
|
|
321
|
+
return {
|
|
322
|
+
type: value.name || "Error",
|
|
323
|
+
message: (value.message || "").slice(0, MAX_MESSAGE_CHARS2),
|
|
324
|
+
stack: value.stack?.slice(0, MAX_STACK_CHARS),
|
|
325
|
+
handled
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
if (typeof value === "string") {
|
|
329
|
+
return {
|
|
330
|
+
type: "Error",
|
|
331
|
+
message: value.slice(0, MAX_MESSAGE_CHARS2),
|
|
332
|
+
handled
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
let message;
|
|
336
|
+
try {
|
|
337
|
+
message = typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
|
|
338
|
+
} catch {
|
|
339
|
+
message = "[unserializable]";
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
type: "UnknownError",
|
|
343
|
+
message: (message ?? "undefined").slice(0, MAX_MESSAGE_CHARS2),
|
|
344
|
+
handled
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
var installed = false;
|
|
348
|
+
function installErrorHandlers(onError2) {
|
|
349
|
+
if (installed) {
|
|
350
|
+
return () => {
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
installed = true;
|
|
354
|
+
const uninstalls = [];
|
|
355
|
+
uninstalls.push(installGlobalErrorHandler(onError2));
|
|
356
|
+
uninstalls.push(installRejectionHandler(onError2));
|
|
357
|
+
return () => {
|
|
358
|
+
installed = false;
|
|
359
|
+
for (const fn of uninstalls) {
|
|
360
|
+
try {
|
|
361
|
+
fn();
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function installGlobalErrorHandler(onError2) {
|
|
368
|
+
const errorUtils = globalThis.ErrorUtils;
|
|
369
|
+
if (!errorUtils?.setGlobalHandler || !errorUtils.getGlobalHandler) {
|
|
370
|
+
return installErrorEventHandler(onError2);
|
|
371
|
+
}
|
|
372
|
+
const previous = errorUtils.getGlobalHandler();
|
|
373
|
+
errorUtils.setGlobalHandler((error, isFatal) => {
|
|
374
|
+
try {
|
|
375
|
+
const captured = describeError(error, false);
|
|
376
|
+
captured.fatal = isFatal ?? false;
|
|
377
|
+
onError2(captured);
|
|
378
|
+
} catch {
|
|
379
|
+
}
|
|
380
|
+
previous?.(error, isFatal);
|
|
381
|
+
});
|
|
382
|
+
return () => {
|
|
383
|
+
if (previous) errorUtils.setGlobalHandler?.(previous);
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
function installErrorEventHandler(onError2) {
|
|
387
|
+
const target = globalThis;
|
|
388
|
+
if (typeof target.addEventListener !== "function") {
|
|
389
|
+
return () => {
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
const handler = (event) => {
|
|
393
|
+
try {
|
|
394
|
+
const thrown = event?.error;
|
|
395
|
+
const value = thrown ?? event?.message ?? event;
|
|
396
|
+
onError2(describeError(value, false));
|
|
397
|
+
} catch {
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
try {
|
|
401
|
+
target.addEventListener("error", handler);
|
|
402
|
+
} catch {
|
|
403
|
+
return () => {
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
return () => {
|
|
407
|
+
try {
|
|
408
|
+
target.removeEventListener?.("error", handler);
|
|
409
|
+
} catch {
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
function installRejectionHandler(onError2) {
|
|
414
|
+
const target = globalThis;
|
|
415
|
+
if (typeof target.addEventListener !== "function") {
|
|
416
|
+
return () => {
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
const handler = (event) => {
|
|
420
|
+
try {
|
|
421
|
+
const reason = event?.reason ?? event;
|
|
422
|
+
const captured = describeError(reason, false);
|
|
423
|
+
captured.type = captured.type === "Error" ? "UnhandledRejection" : captured.type;
|
|
424
|
+
onError2(captured);
|
|
425
|
+
} catch {
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
try {
|
|
429
|
+
target.addEventListener("unhandledrejection", handler);
|
|
430
|
+
} catch {
|
|
431
|
+
return () => {
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
return () => {
|
|
435
|
+
try {
|
|
436
|
+
target.removeEventListener?.("unhandledrejection", handler);
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// ../core/src/ids.ts
|
|
443
|
+
function createId(prefix) {
|
|
444
|
+
const time = Date.now().toString(36);
|
|
445
|
+
const random = Math.random().toString(36).slice(2, 10);
|
|
446
|
+
return `${prefix}_${time}${random}`;
|
|
447
|
+
}
|
|
448
|
+
function hashString(input) {
|
|
449
|
+
let hash = 2166136261;
|
|
450
|
+
for (let i = 0; i < input.length; i += 1) {
|
|
451
|
+
hash ^= input.charCodeAt(i);
|
|
452
|
+
hash = Math.imul(hash, 16777619);
|
|
453
|
+
}
|
|
454
|
+
hash ^= hash >>> 16;
|
|
455
|
+
hash = Math.imul(hash, 2246822507);
|
|
456
|
+
hash ^= hash >>> 13;
|
|
457
|
+
hash = Math.imul(hash, 3266489909);
|
|
458
|
+
hash ^= hash >>> 16;
|
|
459
|
+
return hash >>> 0;
|
|
460
|
+
}
|
|
461
|
+
function isSampled(sessionId, sampleRate) {
|
|
462
|
+
if (sampleRate >= 1) return true;
|
|
463
|
+
if (sampleRate <= 0) return false;
|
|
464
|
+
return hashString(sessionId) / 4294967296 < sampleRate;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ../core/src/performance.ts
|
|
468
|
+
var moduleLoadedAt = Date.now();
|
|
469
|
+
var marks = /* @__PURE__ */ new Map();
|
|
470
|
+
var MAX_OPEN_MARKS = 100;
|
|
471
|
+
function mark(name, now = Date.now()) {
|
|
472
|
+
if (marks.size >= MAX_OPEN_MARKS && !marks.has(name)) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
marks.set(name, now);
|
|
476
|
+
}
|
|
477
|
+
function measure(name, now = Date.now()) {
|
|
478
|
+
const started = marks.get(name);
|
|
479
|
+
if (started === void 0) {
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
marks.delete(name);
|
|
483
|
+
return { name, durationMs: now - started };
|
|
484
|
+
}
|
|
485
|
+
function timeToReady(now = Date.now()) {
|
|
486
|
+
return { name: "app_ready", durationMs: now - moduleLoadedAt };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ../core/src/session.ts
|
|
490
|
+
var SessionManager = class {
|
|
491
|
+
// Explicit fields rather than parameter properties: Node's strip-only
|
|
492
|
+
// TypeScript mode rejects the shorthand, and keeping these files runnable
|
|
493
|
+
// without a build step is worth more than the brevity.
|
|
494
|
+
constructor(options) {
|
|
495
|
+
this.state = null;
|
|
496
|
+
/** True only while `onEnd` runs. See `touch()`. */
|
|
497
|
+
this.rotating = false;
|
|
498
|
+
this.options = options;
|
|
499
|
+
this.now = options.now ?? Date.now;
|
|
500
|
+
this.state = options.initial ?? null;
|
|
501
|
+
}
|
|
502
|
+
current() {
|
|
503
|
+
return this.state;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Register activity, starting or rotating the session as needed.
|
|
507
|
+
*
|
|
508
|
+
* Returns the session the caller should attribute its event to.
|
|
509
|
+
*/
|
|
510
|
+
touch() {
|
|
511
|
+
const now = this.now();
|
|
512
|
+
if (this.state && (this.rotating || !this.expired(now))) {
|
|
513
|
+
this.state.lastActivityAt = now;
|
|
514
|
+
return this.state;
|
|
515
|
+
}
|
|
516
|
+
const ending = this.state;
|
|
517
|
+
if (ending) {
|
|
518
|
+
this.rotating = true;
|
|
519
|
+
try {
|
|
520
|
+
this.options.onEnd?.(ending);
|
|
521
|
+
} catch {
|
|
522
|
+
} finally {
|
|
523
|
+
this.rotating = false;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return this.start(now);
|
|
527
|
+
}
|
|
528
|
+
/** Whether the current session is over after a period with no activity. */
|
|
529
|
+
expired(now) {
|
|
530
|
+
if (!this.state) return true;
|
|
531
|
+
return now - this.state.lastActivityAt > this.options.timeoutMs;
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Take the next sequence number for a session already in hand.
|
|
535
|
+
*
|
|
536
|
+
* The caller has already decided which session this event belongs to —
|
|
537
|
+
* `touch()` for anything that keeps a session alive, `current()` for a
|
|
538
|
+
* goodbye. Taking the sequence must not make that decision a second time.
|
|
539
|
+
*/
|
|
540
|
+
takeSequence(session) {
|
|
541
|
+
const sequence = session.sequence;
|
|
542
|
+
session.sequence += 1;
|
|
543
|
+
return sequence;
|
|
544
|
+
}
|
|
545
|
+
setScreen(name) {
|
|
546
|
+
this.touch().screen = name;
|
|
547
|
+
}
|
|
548
|
+
/** Explicit end, e.g. on an intentional logout. */
|
|
549
|
+
end() {
|
|
550
|
+
this.state = null;
|
|
551
|
+
}
|
|
552
|
+
/** Apply a new sample rate. Takes effect from the next session onward. */
|
|
553
|
+
setSampleRate(sampleRate) {
|
|
554
|
+
this.options = { ...this.options, sampleRate };
|
|
555
|
+
}
|
|
556
|
+
start(now) {
|
|
557
|
+
const sessionId = createId("sess");
|
|
558
|
+
this.state = {
|
|
559
|
+
sessionId,
|
|
560
|
+
startedAt: now,
|
|
561
|
+
lastActivityAt: now,
|
|
562
|
+
// Sequence restarts per session. Ordering is only ever meaningful
|
|
563
|
+
// within one session (section 14).
|
|
564
|
+
sequence: 0,
|
|
565
|
+
sampled: isSampled(sessionId, this.options.sampleRate),
|
|
566
|
+
screen: null
|
|
567
|
+
};
|
|
568
|
+
try {
|
|
569
|
+
this.options.onStart?.(this.state);
|
|
570
|
+
} catch {
|
|
571
|
+
}
|
|
572
|
+
return this.state;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
// ../core/src/core.ts
|
|
577
|
+
var SDK_VERSION = "0.1.0";
|
|
578
|
+
var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
579
|
+
var ALWAYS_CAPTURED = /* @__PURE__ */ new Set([
|
|
580
|
+
"error"
|
|
581
|
+
]);
|
|
582
|
+
var SdkCore = class {
|
|
583
|
+
constructor(deps = {}) {
|
|
584
|
+
this.options = null;
|
|
585
|
+
this.config = DEFAULT_CONFIG;
|
|
586
|
+
this.sessions = null;
|
|
587
|
+
this.batcher = null;
|
|
588
|
+
this.enabled = false;
|
|
589
|
+
this.started = false;
|
|
590
|
+
/**
|
|
591
|
+
* Notified after an error is captured.
|
|
592
|
+
*
|
|
593
|
+
* The seam the optional replay package hangs off (section 23). Core does not
|
|
594
|
+
* know what replay is and must not: this is a list of callbacks, and if the
|
|
595
|
+
* package is not installed the list is empty.
|
|
596
|
+
*/
|
|
597
|
+
this.errorListeners = /* @__PURE__ */ new Set();
|
|
598
|
+
/**
|
|
599
|
+
* Notified as each session begins.
|
|
600
|
+
*
|
|
601
|
+
* The same seam as `errorListeners`, for the thing replay cannot get from
|
|
602
|
+
* `onError`: continuous recording needs the session id at every flush, and
|
|
603
|
+
* needs the start boundary to decide whether this session is sampled.
|
|
604
|
+
*/
|
|
605
|
+
this.sessionListeners = /* @__PURE__ */ new Set();
|
|
606
|
+
/** Events discarded because remote config disabled capture. Diagnostics. */
|
|
607
|
+
this.dropOnKill = 0;
|
|
608
|
+
this.now = deps.now ?? Date.now;
|
|
609
|
+
this.onFlush = deps.onFlush ?? (() => {
|
|
610
|
+
});
|
|
611
|
+
this.deviceContext = deps.deviceContext ?? (() => ({}));
|
|
612
|
+
this.restoreSession = deps.restoreSession ?? (() => null);
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* The live session, for a platform that has to persist it.
|
|
616
|
+
*
|
|
617
|
+
* Read-only by convention — it is the manager's own object, and mutating it
|
|
618
|
+
* from outside would desynchronize the sequence counter from the events
|
|
619
|
+
* already sent.
|
|
620
|
+
*/
|
|
621
|
+
session() {
|
|
622
|
+
return this.sessions?.current() ?? null;
|
|
623
|
+
}
|
|
624
|
+
init(options) {
|
|
625
|
+
if (this.started) {
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
this.options = options;
|
|
629
|
+
this.enabled = options.enabled ?? true;
|
|
630
|
+
this.started = true;
|
|
631
|
+
this.sessions = new SessionManager({
|
|
632
|
+
timeoutMs: SESSION_TIMEOUT_MS,
|
|
633
|
+
initial: this.restoreSession(),
|
|
634
|
+
sampleRate: this.config.sampleRate,
|
|
635
|
+
now: this.now,
|
|
636
|
+
onStart: (session) => this.announce(session.sessionId),
|
|
637
|
+
// Close the outgoing side of an inactivity rotation immediately. The
|
|
638
|
+
// backend finalizer remains the fallback for force-quits and OS kills.
|
|
639
|
+
onEnd: () => this.capture("session_end")
|
|
640
|
+
});
|
|
641
|
+
this.batcher = new Batcher({
|
|
642
|
+
maxSize: this.config.batchSize,
|
|
643
|
+
flushIntervalMs: this.config.flushIntervalMs,
|
|
644
|
+
onFlush: (events) => this.deliver(events)
|
|
645
|
+
});
|
|
646
|
+
this.startSessionIfNeeded();
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Whether capture is currently active.
|
|
650
|
+
*
|
|
651
|
+
* Three independent gates: initialized, locally enabled (consent), and
|
|
652
|
+
* remotely enabled (the kill switch). Any one of them off means nothing is
|
|
653
|
+
* captured and nothing is buffered.
|
|
654
|
+
*/
|
|
655
|
+
isEnabled() {
|
|
656
|
+
return this.started && this.enabled && this.config.enabled;
|
|
657
|
+
}
|
|
658
|
+
setEnabled(enabled) {
|
|
659
|
+
this.enabled = enabled;
|
|
660
|
+
if (enabled) {
|
|
661
|
+
this.startSessionIfNeeded();
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (!enabled) {
|
|
665
|
+
this.batcher?.drop();
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Apply remote configuration (section 39).
|
|
670
|
+
*
|
|
671
|
+
* Takes effect on a running SDK, not just at startup — that is the whole
|
|
672
|
+
* point of the kill switch. `isEnabled()` re-reads `config.enabled` on every
|
|
673
|
+
* capture, so `enabled: false` stops collection mid-session.
|
|
674
|
+
*
|
|
675
|
+
* Sampling is the one thing that cannot be retrofitted: it is decided once
|
|
676
|
+
* at session start and must stay that way, or a timeline ends up half
|
|
677
|
+
* captured while looking complete. A new rate therefore applies from the
|
|
678
|
+
* next session.
|
|
679
|
+
*/
|
|
680
|
+
applyConfig(config) {
|
|
681
|
+
const wasEnabled = this.config.enabled;
|
|
682
|
+
this.config = config;
|
|
683
|
+
this.sessions?.setSampleRate(config.sampleRate);
|
|
684
|
+
if (wasEnabled && !config.enabled) {
|
|
685
|
+
const dropped = this.batcher?.drop() ?? 0;
|
|
686
|
+
if (dropped > 0) {
|
|
687
|
+
this.dropOnKill = dropped;
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
this.batcher?.reconfigure({
|
|
692
|
+
maxSize: config.batchSize,
|
|
693
|
+
flushIntervalMs: config.flushIntervalMs
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
get droppedOnKill() {
|
|
697
|
+
return this.dropOnKill;
|
|
698
|
+
}
|
|
699
|
+
/** The config currently in force. */
|
|
700
|
+
get remoteConfig() {
|
|
701
|
+
return this.config;
|
|
702
|
+
}
|
|
703
|
+
capture(type, data) {
|
|
704
|
+
if (!this.isEnabled() || !this.sessions || !this.batcher) {
|
|
705
|
+
return null;
|
|
706
|
+
}
|
|
707
|
+
const session = type === "session_end" ? this.sessions.current() : this.sessions.touch();
|
|
708
|
+
if (!session) return null;
|
|
709
|
+
if (!session.sampled && !ALWAYS_CAPTURED.has(type)) {
|
|
710
|
+
return null;
|
|
711
|
+
}
|
|
712
|
+
const event = {
|
|
713
|
+
id: createId("evt"),
|
|
714
|
+
type,
|
|
715
|
+
sessionId: session.sessionId,
|
|
716
|
+
sequence: this.sessions.takeSequence(session),
|
|
717
|
+
timestamp: this.now(),
|
|
718
|
+
// Redact before the event reaches the buffer, never on the way out.
|
|
719
|
+
...data ? { data: redact(data, this.config.maskedKeys) } : {}
|
|
720
|
+
};
|
|
721
|
+
this.batcher.add(event);
|
|
722
|
+
if (type !== "error") {
|
|
723
|
+
addBreadcrumb(type, void 0, data, this.config.maskedKeys, event.timestamp);
|
|
724
|
+
}
|
|
725
|
+
return event;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Capture an error with its breadcrumb trail.
|
|
729
|
+
*
|
|
730
|
+
* Bypasses sampling: errors are rare and are the reason people install this.
|
|
731
|
+
*/
|
|
732
|
+
captureError(value, handled, extra) {
|
|
733
|
+
this.report(describeError(value, handled), extra);
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Capture an error the global handler has already described.
|
|
737
|
+
*
|
|
738
|
+
* Separate from `captureError` because `describeError` cannot usefully
|
|
739
|
+
* re-describe its own output: a `CapturedError` is a plain object, so it
|
|
740
|
+
* took the object branch and came out as `UnknownError` with the real type,
|
|
741
|
+
* message and stack JSON-stringified inside the message. Every *uncaught*
|
|
742
|
+
* error — the ones that matter most — arrived that way, and the `fatal`
|
|
743
|
+
* flag was lost with them.
|
|
744
|
+
*/
|
|
745
|
+
captureCrash(described) {
|
|
746
|
+
this.report(described);
|
|
747
|
+
}
|
|
748
|
+
report(described, extra) {
|
|
749
|
+
if (!this.isEnabled()) return;
|
|
750
|
+
this.capture("error", {
|
|
751
|
+
...described,
|
|
752
|
+
...extra,
|
|
753
|
+
breadcrumbs: snapshotBreadcrumbs(this.now())
|
|
754
|
+
});
|
|
755
|
+
const sessionId = this.sessions?.current()?.sessionId ?? "";
|
|
756
|
+
for (const listener of this.errorListeners) {
|
|
757
|
+
try {
|
|
758
|
+
listener(sessionId);
|
|
759
|
+
} catch {
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (described.fatal) {
|
|
763
|
+
this.capture("session_end", { reason: "crash" });
|
|
764
|
+
this.sessions?.end();
|
|
765
|
+
}
|
|
766
|
+
void this.batcher?.flush();
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Subscribe to errors. Returns an unsubscribe.
|
|
770
|
+
*
|
|
771
|
+
* The session id is passed rather than left for the subscriber to look up:
|
|
772
|
+
* by the time a listener runs the session could have rolled over, and a
|
|
773
|
+
* recording filed against the wrong session is worse than none.
|
|
774
|
+
*/
|
|
775
|
+
/**
|
|
776
|
+
* Count ongoing work as activity, without emitting an event for it.
|
|
777
|
+
*
|
|
778
|
+
* Recording is activity even when no analytics event happens, so replay
|
|
779
|
+
* calls this as it cuts segments. That keeps an actively recorded session
|
|
780
|
+
* alive; after thirty minutes without either kind of work, the next touch
|
|
781
|
+
* rotates through the ordinary inactivity boundary.
|
|
782
|
+
*/
|
|
783
|
+
keepAlive() {
|
|
784
|
+
if (!this.isEnabled()) return;
|
|
785
|
+
this.sessions?.touch();
|
|
786
|
+
}
|
|
787
|
+
/** The config in force right now, including anything remote config changed. */
|
|
788
|
+
currentConfig() {
|
|
789
|
+
return this.config;
|
|
790
|
+
}
|
|
791
|
+
onSession(listener) {
|
|
792
|
+
this.sessionListeners.add(listener);
|
|
793
|
+
const open = this.sessions?.current();
|
|
794
|
+
if (open) {
|
|
795
|
+
try {
|
|
796
|
+
listener(open.sessionId);
|
|
797
|
+
} catch {
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return () => {
|
|
801
|
+
this.sessionListeners.delete(listener);
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
onError(listener) {
|
|
805
|
+
this.errorListeners.add(listener);
|
|
806
|
+
return () => {
|
|
807
|
+
this.errorListeners.delete(listener);
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
captureNetwork(event) {
|
|
811
|
+
this.capture("network_request", { ...event });
|
|
812
|
+
}
|
|
813
|
+
/** Close a named mark and record its duration. */
|
|
814
|
+
measure(name) {
|
|
815
|
+
const result = measure(name, this.now());
|
|
816
|
+
if (result) {
|
|
817
|
+
this.capture("performance", { ...result });
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
mark(name) {
|
|
821
|
+
mark(name, this.now());
|
|
822
|
+
}
|
|
823
|
+
/** Record time from SDK load to app-ready. */
|
|
824
|
+
markReady() {
|
|
825
|
+
this.capture("performance", { ...timeToReady(this.now()) });
|
|
826
|
+
}
|
|
827
|
+
screen(name) {
|
|
828
|
+
if (!this.isEnabled() || !this.sessions) return;
|
|
829
|
+
this.sessions.setScreen(name);
|
|
830
|
+
this.capture("screen_view", { screen: name });
|
|
831
|
+
}
|
|
832
|
+
/** Called by the platform lifecycle glue. */
|
|
833
|
+
onAppStateChange(state) {
|
|
834
|
+
if (!this.isEnabled()) return;
|
|
835
|
+
if (state === "background") {
|
|
836
|
+
this.capture("lifecycle", { state: "background" });
|
|
837
|
+
void this.batcher?.flush();
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
this.sessions?.touch();
|
|
841
|
+
this.capture("lifecycle", { state: "active" });
|
|
842
|
+
}
|
|
843
|
+
async flush() {
|
|
844
|
+
await this.batcher?.flush();
|
|
845
|
+
}
|
|
846
|
+
shutdown() {
|
|
847
|
+
clearBreadcrumbs();
|
|
848
|
+
if (this.isEnabled() && this.sessions?.current()) {
|
|
849
|
+
this.capture("session_end");
|
|
850
|
+
void this.batcher?.flush();
|
|
851
|
+
}
|
|
852
|
+
this.batcher?.stop();
|
|
853
|
+
this.sessions?.end();
|
|
854
|
+
this.started = false;
|
|
855
|
+
}
|
|
856
|
+
startSessionIfNeeded() {
|
|
857
|
+
if (!this.isEnabled() || !this.sessions) return;
|
|
858
|
+
if (this.sessions.current()) return;
|
|
859
|
+
this.sessions.touch();
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Announce a session that has just begun.
|
|
863
|
+
*
|
|
864
|
+
* Called from inside `SessionManager.start()`, which is reachable from
|
|
865
|
+
* inside `capture()` — so this re-enters `capture()`. That is safe and is
|
|
866
|
+
* what gives the right ordering: `this.state` is already set, so the nested
|
|
867
|
+
* `touch()` finds a live session rather than rotating again, and
|
|
868
|
+
* `session_start` takes sequence 0 while the event that triggered the
|
|
869
|
+
* rotation takes 1.
|
|
870
|
+
*/
|
|
871
|
+
announce(sessionId) {
|
|
872
|
+
this.capture("session_start", { ...this.deviceContext() });
|
|
873
|
+
for (const listener of this.sessionListeners) {
|
|
874
|
+
try {
|
|
875
|
+
listener(sessionId);
|
|
876
|
+
} catch {
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
/** Test accessors. */
|
|
881
|
+
get currentSession() {
|
|
882
|
+
return this.sessions?.current() ?? null;
|
|
883
|
+
}
|
|
884
|
+
get buffered() {
|
|
885
|
+
return this.batcher?.size ?? 0;
|
|
886
|
+
}
|
|
887
|
+
deliver(events) {
|
|
888
|
+
if (!this.options) return;
|
|
889
|
+
const batch = {
|
|
890
|
+
schemaVersion: SCHEMA_VERSION,
|
|
891
|
+
projectId: this.options.projectId,
|
|
892
|
+
sdkVersion: SDK_VERSION,
|
|
893
|
+
sentAt: this.now(),
|
|
894
|
+
events
|
|
895
|
+
};
|
|
896
|
+
return this.onFlush(batch);
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
|
|
900
|
+
// ../core/src/transport.ts
|
|
901
|
+
function classifyStatus(status) {
|
|
902
|
+
if (status >= 200 && status < 300) {
|
|
903
|
+
return { kind: "sent" };
|
|
904
|
+
}
|
|
905
|
+
if (status === 408 || status === 425 || status === 429 || status >= 500) {
|
|
906
|
+
return { kind: "retry", reason: `http ${status}` };
|
|
907
|
+
}
|
|
908
|
+
return { kind: "permanent", reason: `http ${status}` };
|
|
909
|
+
}
|
|
910
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
911
|
+
if (!value) return void 0;
|
|
912
|
+
const seconds = Number(value);
|
|
913
|
+
if (Number.isFinite(seconds)) {
|
|
914
|
+
return Math.max(0, seconds * 1e3);
|
|
915
|
+
}
|
|
916
|
+
const when = Date.parse(value);
|
|
917
|
+
return Number.isNaN(when) ? void 0 : Math.max(0, when - now);
|
|
918
|
+
}
|
|
919
|
+
var BASE_DELAY_MS = 1e3;
|
|
920
|
+
var MAX_DELAY_MS = 5 * 60 * 1e3;
|
|
921
|
+
function backoffDelay(attempts, random = Math.random) {
|
|
922
|
+
const exponential = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.max(0, attempts));
|
|
923
|
+
return Math.floor(random() * exponential);
|
|
924
|
+
}
|
|
925
|
+
async function sendBatch(options, batch) {
|
|
926
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
927
|
+
const url = `${options.endpoint.replace(/\/$/, "")}/v1/mobile/events`;
|
|
928
|
+
let response;
|
|
929
|
+
try {
|
|
930
|
+
response = await doFetch(url, {
|
|
931
|
+
method: "POST",
|
|
932
|
+
headers: {
|
|
933
|
+
"content-type": "application/json",
|
|
934
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
935
|
+
"x-sdk-version": options.sdkVersion
|
|
936
|
+
},
|
|
937
|
+
body: JSON.stringify(batch),
|
|
938
|
+
// Ignored by runtimes that do not know it, which is what makes it safe
|
|
939
|
+
// to send unconditionally from a shared transport.
|
|
940
|
+
keepalive: options.keepalive === true
|
|
941
|
+
});
|
|
942
|
+
} catch (err) {
|
|
943
|
+
return {
|
|
944
|
+
kind: "retry",
|
|
945
|
+
reason: err instanceof Error ? err.message : "network error"
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
const outcome = classifyStatus(response.status);
|
|
949
|
+
if (outcome.kind === "retry") {
|
|
950
|
+
const retryAfterMs = parseRetryAfter(
|
|
951
|
+
typeof response.headers?.get === "function" ? response.headers.get("retry-after") : null
|
|
952
|
+
);
|
|
953
|
+
return retryAfterMs === void 0 ? outcome : { ...outcome, retryAfterMs };
|
|
954
|
+
}
|
|
955
|
+
return outcome;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// ../core/src/dispatcher.ts
|
|
959
|
+
var Dispatcher = class {
|
|
960
|
+
constructor(options) {
|
|
961
|
+
this.draining = false;
|
|
962
|
+
/** Wall-clock time before which no send should be attempted. */
|
|
963
|
+
this.pausedUntil = 0;
|
|
964
|
+
this.queue = options.queue;
|
|
965
|
+
this.transport = options.transport;
|
|
966
|
+
this.batchesPerDrain = options.batchesPerDrain ?? 5;
|
|
967
|
+
this.now = options.now ?? Date.now;
|
|
968
|
+
this.onOutcome = options.onOutcome;
|
|
969
|
+
}
|
|
970
|
+
/** True while backpressure is in effect. */
|
|
971
|
+
get paused() {
|
|
972
|
+
return this.now() < this.pausedUntil;
|
|
973
|
+
}
|
|
974
|
+
get pausedForMs() {
|
|
975
|
+
return Math.max(0, this.pausedUntil - this.now());
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Send what is queued.
|
|
979
|
+
*
|
|
980
|
+
* Returns the number of batches delivered. Stops early on the first batch
|
|
981
|
+
* that needs retrying: the queue is ordered, and a failure almost always
|
|
982
|
+
* means the network or the server is unavailable for the next one too.
|
|
983
|
+
* Continuing would just burn attempts on every queued batch at once.
|
|
984
|
+
*/
|
|
985
|
+
async drain() {
|
|
986
|
+
if (this.draining || this.paused) return 0;
|
|
987
|
+
this.draining = true;
|
|
988
|
+
let sent = 0;
|
|
989
|
+
try {
|
|
990
|
+
const entries = await this.queue.peek(this.batchesPerDrain);
|
|
991
|
+
for (const entry of entries) {
|
|
992
|
+
const outcome = await sendBatch(this.transport, entry.batch);
|
|
993
|
+
this.onOutcome?.(outcome, entry);
|
|
994
|
+
if (outcome.kind === "sent") {
|
|
995
|
+
await this.queue.remove(entry.name);
|
|
996
|
+
sent += 1;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (outcome.kind === "permanent") {
|
|
1000
|
+
await this.queue.remove(entry.name);
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
const delay = outcome.retryAfterMs ?? backoffDelay(entry.attempts);
|
|
1004
|
+
this.pausedUntil = this.now() + delay;
|
|
1005
|
+
await this.queue.recordFailure(entry);
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
} finally {
|
|
1009
|
+
this.draining = false;
|
|
1010
|
+
}
|
|
1011
|
+
return sent;
|
|
1012
|
+
}
|
|
1013
|
+
/** Clear backpressure, e.g. when the app returns to the foreground. */
|
|
1014
|
+
resume() {
|
|
1015
|
+
this.pausedUntil = 0;
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
// ../core/src/network.ts
|
|
1020
|
+
var PATCH_MARKER = "__sessionCapturePatched";
|
|
1021
|
+
function sanitizeUrl(url) {
|
|
1022
|
+
const queryStart = url.indexOf("?");
|
|
1023
|
+
return queryStart === -1 ? url : `${url.slice(0, queryStart)}?<redacted>`;
|
|
1024
|
+
}
|
|
1025
|
+
function shouldCapture(url, ingestEndpoint, denyList) {
|
|
1026
|
+
if (ingestEndpoint && url.startsWith(ingestEndpoint)) {
|
|
1027
|
+
return false;
|
|
1028
|
+
}
|
|
1029
|
+
return !denyList.some((pattern) => pattern && url.includes(pattern));
|
|
1030
|
+
}
|
|
1031
|
+
function headersToObject(init2) {
|
|
1032
|
+
if (!init2) return void 0;
|
|
1033
|
+
const out = {};
|
|
1034
|
+
try {
|
|
1035
|
+
if (Array.isArray(init2)) {
|
|
1036
|
+
for (const [k, v] of init2) out[k] = v;
|
|
1037
|
+
} else if (typeof init2.forEach === "function") {
|
|
1038
|
+
init2.forEach((v, k) => {
|
|
1039
|
+
out[k] = v;
|
|
1040
|
+
});
|
|
1041
|
+
} else {
|
|
1042
|
+
Object.assign(out, init2);
|
|
1043
|
+
}
|
|
1044
|
+
} catch {
|
|
1045
|
+
return void 0;
|
|
1046
|
+
}
|
|
1047
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
1048
|
+
}
|
|
1049
|
+
function installNetworkCapture(options) {
|
|
1050
|
+
const xhr = globalThis.XMLHttpRequest;
|
|
1051
|
+
const undo = [];
|
|
1052
|
+
if (typeof xhr === "function" && xhr.prototype) {
|
|
1053
|
+
undo.push(installXhrCapture(xhr, options));
|
|
1054
|
+
}
|
|
1055
|
+
undo.push(installFetchCapture(options));
|
|
1056
|
+
return () => {
|
|
1057
|
+
for (const teardown2 of undo) teardown2();
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
var insideFetch = false;
|
|
1061
|
+
var servedByXhr = false;
|
|
1062
|
+
function installXhrCapture(xhr, options) {
|
|
1063
|
+
const now = options.now ?? Date.now;
|
|
1064
|
+
const proto = xhr.prototype;
|
|
1065
|
+
if (proto[PATCH_MARKER]) {
|
|
1066
|
+
return () => {
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
const originalOpen = proto.open;
|
|
1070
|
+
const originalSend = proto.send;
|
|
1071
|
+
const originalSetHeader = proto.setRequestHeader;
|
|
1072
|
+
const pending = /* @__PURE__ */ new WeakMap();
|
|
1073
|
+
function patchedOpen(method, url, ...rest) {
|
|
1074
|
+
try {
|
|
1075
|
+
pending.set(this, {
|
|
1076
|
+
method: String(method ?? "GET").toUpperCase(),
|
|
1077
|
+
url: String(url ?? ""),
|
|
1078
|
+
headers: {},
|
|
1079
|
+
started: 0
|
|
1080
|
+
});
|
|
1081
|
+
} catch {
|
|
1082
|
+
}
|
|
1083
|
+
return originalOpen.call(this, method, url, ...rest);
|
|
1084
|
+
}
|
|
1085
|
+
function patchedSetHeader(name, value) {
|
|
1086
|
+
try {
|
|
1087
|
+
const state = pending.get(this);
|
|
1088
|
+
if (state) state.headers[name] = value;
|
|
1089
|
+
} catch {
|
|
1090
|
+
}
|
|
1091
|
+
return originalSetHeader.call(this, name, value);
|
|
1092
|
+
}
|
|
1093
|
+
function patchedSend(body) {
|
|
1094
|
+
try {
|
|
1095
|
+
const state = pending.get(this);
|
|
1096
|
+
if (state && shouldCapture(state.url, options.ingestEndpoint, options.urlDenyList)) {
|
|
1097
|
+
if (insideFetch) servedByXhr = true;
|
|
1098
|
+
state.started = now();
|
|
1099
|
+
if (options.captureBodies) {
|
|
1100
|
+
state.body = captureBody(
|
|
1101
|
+
body,
|
|
1102
|
+
headerValue(state.headers, "content-type"),
|
|
1103
|
+
options.maskedKeys
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
for (const reason of ["error", "timeout", "abort"]) {
|
|
1107
|
+
this.addEventListener(reason, () => {
|
|
1108
|
+
const current = pending.get(this);
|
|
1109
|
+
if (current) current.reason = reason;
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
this.addEventListener("loadend", () => finish(this));
|
|
1113
|
+
}
|
|
1114
|
+
} catch {
|
|
1115
|
+
}
|
|
1116
|
+
return originalSend.call(this, body);
|
|
1117
|
+
}
|
|
1118
|
+
function finish(request) {
|
|
1119
|
+
const state = pending.get(request);
|
|
1120
|
+
if (!state) return;
|
|
1121
|
+
pending.delete(request);
|
|
1122
|
+
try {
|
|
1123
|
+
const status = request.status;
|
|
1124
|
+
const event = {
|
|
1125
|
+
url: sanitizeUrl(state.url),
|
|
1126
|
+
method: state.method,
|
|
1127
|
+
durationMs: now() - state.started,
|
|
1128
|
+
requestHeaders: redactHeaders(state.headers, options.maskedKeys)
|
|
1129
|
+
};
|
|
1130
|
+
if (state.body !== void 0) {
|
|
1131
|
+
event.requestBody = state.body;
|
|
1132
|
+
}
|
|
1133
|
+
if (status > 0) {
|
|
1134
|
+
event.status = status;
|
|
1135
|
+
const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());
|
|
1136
|
+
event.responseHeaders = redactHeaders(responseHeaders, options.maskedKeys);
|
|
1137
|
+
if (options.captureBodies) {
|
|
1138
|
+
event.responseBody = readResponseBody(
|
|
1139
|
+
request,
|
|
1140
|
+
headerValue(responseHeaders ?? {}, "content-type"),
|
|
1141
|
+
options.maskedKeys
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
} else {
|
|
1145
|
+
event.error = FAILURE_TEXT[state.reason ?? "error"];
|
|
1146
|
+
}
|
|
1147
|
+
report(options, event);
|
|
1148
|
+
} catch {
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
proto.open = patchedOpen;
|
|
1152
|
+
proto.setRequestHeader = patchedSetHeader;
|
|
1153
|
+
proto.send = patchedSend;
|
|
1154
|
+
proto[PATCH_MARKER] = true;
|
|
1155
|
+
return () => {
|
|
1156
|
+
if (proto.open === patchedOpen) proto.open = originalOpen;
|
|
1157
|
+
if (proto.setRequestHeader === patchedSetHeader) proto.setRequestHeader = originalSetHeader;
|
|
1158
|
+
if (proto.send === patchedSend) proto.send = originalSend;
|
|
1159
|
+
delete proto[PATCH_MARKER];
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
var FAILURE_TEXT = {
|
|
1163
|
+
error: "network error",
|
|
1164
|
+
timeout: "timeout",
|
|
1165
|
+
abort: "aborted"
|
|
1166
|
+
};
|
|
1167
|
+
var MAX_BODY_CHARS = 4096;
|
|
1168
|
+
function truncate(text) {
|
|
1169
|
+
return text.length <= MAX_BODY_CHARS ? text : `${text.slice(0, MAX_BODY_CHARS)}\u2026[truncated]`;
|
|
1170
|
+
}
|
|
1171
|
+
function headerValue(headers, name) {
|
|
1172
|
+
const wanted = name.toLowerCase();
|
|
1173
|
+
for (const key of Object.keys(headers)) {
|
|
1174
|
+
if (key.toLowerCase() === wanted) return String(headers[key] ?? "");
|
|
1175
|
+
}
|
|
1176
|
+
return "";
|
|
1177
|
+
}
|
|
1178
|
+
function mediaType(contentType) {
|
|
1179
|
+
return (contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
1180
|
+
}
|
|
1181
|
+
function captureBody(raw, contentType, maskedKeys) {
|
|
1182
|
+
if (raw === void 0 || raw === null || raw === "") return void 0;
|
|
1183
|
+
if (typeof raw !== "string") {
|
|
1184
|
+
return `[not captured: ${describeBody(raw)}]`;
|
|
1185
|
+
}
|
|
1186
|
+
const type = mediaType(contentType);
|
|
1187
|
+
if (type === "application/json" || type.endsWith("+json")) {
|
|
1188
|
+
try {
|
|
1189
|
+
return truncate(JSON.stringify(redact(JSON.parse(raw), maskedKeys)));
|
|
1190
|
+
} catch {
|
|
1191
|
+
return "[not captured: malformed json]";
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (type === "application/x-www-form-urlencoded") {
|
|
1195
|
+
try {
|
|
1196
|
+
const fields = {};
|
|
1197
|
+
new URLSearchParams(raw).forEach((value, key) => {
|
|
1198
|
+
fields[key] = value;
|
|
1199
|
+
});
|
|
1200
|
+
const out = new URLSearchParams();
|
|
1201
|
+
for (const [key, value] of Object.entries(
|
|
1202
|
+
redact(fields, maskedKeys)
|
|
1203
|
+
)) {
|
|
1204
|
+
out.append(key, value);
|
|
1205
|
+
}
|
|
1206
|
+
return truncate(out.toString());
|
|
1207
|
+
} catch {
|
|
1208
|
+
return "[not captured: malformed form data]";
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
return `[not captured: ${type || "unknown content type"}]`;
|
|
1212
|
+
}
|
|
1213
|
+
function readHeaders(response) {
|
|
1214
|
+
const headers = response.headers;
|
|
1215
|
+
if (!headers || typeof headers.forEach !== "function") return void 0;
|
|
1216
|
+
const out = {};
|
|
1217
|
+
try {
|
|
1218
|
+
headers.forEach((value, key) => {
|
|
1219
|
+
out[key] = value;
|
|
1220
|
+
});
|
|
1221
|
+
} catch {
|
|
1222
|
+
return void 0;
|
|
1223
|
+
}
|
|
1224
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
1225
|
+
}
|
|
1226
|
+
var MAX_CLONE_BYTES = 256 * 1024;
|
|
1227
|
+
function cloneForReading(response) {
|
|
1228
|
+
if (typeof response.clone !== "function") return null;
|
|
1229
|
+
const headers = readHeaders(response) ?? {};
|
|
1230
|
+
const type = mediaType(headerValue(headers, "content-type"));
|
|
1231
|
+
const redactable = type === "application/json" || type.endsWith("+json") || type === "application/x-www-form-urlencoded";
|
|
1232
|
+
if (!redactable) return null;
|
|
1233
|
+
const declared = Number(headerValue(headers, "content-length"));
|
|
1234
|
+
if (Number.isFinite(declared) && declared > MAX_CLONE_BYTES) return null;
|
|
1235
|
+
try {
|
|
1236
|
+
return response.clone().text();
|
|
1237
|
+
} catch {
|
|
1238
|
+
return null;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
function describeBody(body) {
|
|
1242
|
+
const name = body?.constructor?.name;
|
|
1243
|
+
return name ? name.toLowerCase() : typeof body;
|
|
1244
|
+
}
|
|
1245
|
+
function readResponseBody(request, contentType, maskedKeys) {
|
|
1246
|
+
const type = request.responseType ?? "";
|
|
1247
|
+
if (type !== "" && type !== "text") {
|
|
1248
|
+
return `[not captured: ${type} response]`;
|
|
1249
|
+
}
|
|
1250
|
+
try {
|
|
1251
|
+
return captureBody(request.responseText, contentType, maskedKeys);
|
|
1252
|
+
} catch {
|
|
1253
|
+
return void 0;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
function parseResponseHeaders(raw) {
|
|
1257
|
+
if (!raw) return void 0;
|
|
1258
|
+
const out = {};
|
|
1259
|
+
for (const line of raw.split("\r\n")) {
|
|
1260
|
+
const colon = line.indexOf(":");
|
|
1261
|
+
if (colon === -1) continue;
|
|
1262
|
+
out[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
|
|
1263
|
+
}
|
|
1264
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
1265
|
+
}
|
|
1266
|
+
function installFetchCapture(options) {
|
|
1267
|
+
const now = options.now ?? Date.now;
|
|
1268
|
+
const target = globalThis;
|
|
1269
|
+
const original = target.fetch;
|
|
1270
|
+
if (typeof original !== "function" || original[PATCH_MARKER]) {
|
|
1271
|
+
return () => {
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
const patched = async function patchedFetch(input, init2) {
|
|
1275
|
+
const url = typeof input === "string" ? input : String(input);
|
|
1276
|
+
const method = (init2?.method ?? "GET").toUpperCase();
|
|
1277
|
+
if (!shouldCapture(url, options.ingestEndpoint, options.urlDenyList)) {
|
|
1278
|
+
return original(input, init2);
|
|
1279
|
+
}
|
|
1280
|
+
const started = now();
|
|
1281
|
+
let pending;
|
|
1282
|
+
insideFetch = true;
|
|
1283
|
+
servedByXhr = false;
|
|
1284
|
+
try {
|
|
1285
|
+
pending = original(input, init2);
|
|
1286
|
+
} finally {
|
|
1287
|
+
insideFetch = false;
|
|
1288
|
+
}
|
|
1289
|
+
const claimed = servedByXhr;
|
|
1290
|
+
const requestBody = options.captureBodies ? captureBody(init2?.body, headerValue(headersToObject(init2?.headers) ?? {}, "content-type"), options.maskedKeys) : void 0;
|
|
1291
|
+
try {
|
|
1292
|
+
const response = await pending;
|
|
1293
|
+
if (claimed) return response;
|
|
1294
|
+
const event = {
|
|
1295
|
+
url: sanitizeUrl(url),
|
|
1296
|
+
method,
|
|
1297
|
+
status: response.status,
|
|
1298
|
+
durationMs: now() - started,
|
|
1299
|
+
requestHeaders: redactHeaders(init2?.headers, options.maskedKeys),
|
|
1300
|
+
responseHeaders: redactHeaders(readHeaders(response), options.maskedKeys)
|
|
1301
|
+
};
|
|
1302
|
+
if (requestBody !== void 0) event.requestBody = requestBody;
|
|
1303
|
+
const copy = options.captureBodies ? cloneForReading(response) : null;
|
|
1304
|
+
if (copy) {
|
|
1305
|
+
copy.then(
|
|
1306
|
+
(text) => {
|
|
1307
|
+
event.responseBody = captureBody(
|
|
1308
|
+
text,
|
|
1309
|
+
headerValue(readHeaders(response) ?? {}, "content-type"),
|
|
1310
|
+
options.maskedKeys
|
|
1311
|
+
);
|
|
1312
|
+
report(options, event);
|
|
1313
|
+
},
|
|
1314
|
+
() => report(options, event)
|
|
1315
|
+
);
|
|
1316
|
+
} else {
|
|
1317
|
+
report(options, event);
|
|
1318
|
+
}
|
|
1319
|
+
return response;
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
if (!claimed) {
|
|
1322
|
+
const event = {
|
|
1323
|
+
url: sanitizeUrl(url),
|
|
1324
|
+
method,
|
|
1325
|
+
durationMs: now() - started,
|
|
1326
|
+
error: error instanceof Error ? error.message : "network error",
|
|
1327
|
+
requestHeaders: redactHeaders(init2?.headers, options.maskedKeys)
|
|
1328
|
+
};
|
|
1329
|
+
if (requestBody !== void 0) event.requestBody = requestBody;
|
|
1330
|
+
report(options, event);
|
|
1331
|
+
}
|
|
1332
|
+
throw error;
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
patched[PATCH_MARKER] = true;
|
|
1336
|
+
target.fetch = patched;
|
|
1337
|
+
return () => {
|
|
1338
|
+
if (target.fetch === patched) {
|
|
1339
|
+
target.fetch = original;
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
}
|
|
1343
|
+
function redactHeaders(headers, maskedKeys) {
|
|
1344
|
+
const raw = headersToObject(headers);
|
|
1345
|
+
if (!raw) return void 0;
|
|
1346
|
+
return redact(raw, maskedKeys);
|
|
1347
|
+
}
|
|
1348
|
+
function report(options, event) {
|
|
1349
|
+
try {
|
|
1350
|
+
options.onEvent(event);
|
|
1351
|
+
} catch {
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// ../core/src/queue.ts
|
|
1356
|
+
var DEFAULT_MAX_BATCHES = 50;
|
|
1357
|
+
var DEFAULT_MAX_ATTEMPTS = 8;
|
|
1358
|
+
var SendQueue = class {
|
|
1359
|
+
constructor(options) {
|
|
1360
|
+
this.counter = 0;
|
|
1361
|
+
this.droppedCount = 0;
|
|
1362
|
+
this.abandonedCount = 0;
|
|
1363
|
+
this.store = options.store;
|
|
1364
|
+
this.maxBatches = options.maxBatches ?? DEFAULT_MAX_BATCHES;
|
|
1365
|
+
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
1366
|
+
}
|
|
1367
|
+
/** Batches dropped because the queue was full. */
|
|
1368
|
+
get dropped() {
|
|
1369
|
+
return this.droppedCount;
|
|
1370
|
+
}
|
|
1371
|
+
/** Batches abandoned after exhausting their attempts. */
|
|
1372
|
+
get abandoned() {
|
|
1373
|
+
return this.abandonedCount;
|
|
1374
|
+
}
|
|
1375
|
+
async size() {
|
|
1376
|
+
return (await this.store.list()).length;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Persist a batch for sending.
|
|
1380
|
+
*
|
|
1381
|
+
* Called before any network attempt, so a crash between capture and delivery
|
|
1382
|
+
* loses nothing.
|
|
1383
|
+
*/
|
|
1384
|
+
async enqueue(batch, now = Date.now()) {
|
|
1385
|
+
await this.prune();
|
|
1386
|
+
this.counter = (this.counter + 1) % 1e6;
|
|
1387
|
+
const name = `${String(now).padStart(15, "0")}-${String(this.counter).padStart(6, "0")}.json`;
|
|
1388
|
+
const envelope = { batch, attempts: 0 };
|
|
1389
|
+
await this.store.write(name, JSON.stringify(envelope));
|
|
1390
|
+
return name;
|
|
1391
|
+
}
|
|
1392
|
+
/** Oldest queued batches, oldest first. */
|
|
1393
|
+
async peek(limit = 5) {
|
|
1394
|
+
const names = (await this.store.list()).sort().slice(0, limit);
|
|
1395
|
+
const out = [];
|
|
1396
|
+
for (const name of names) {
|
|
1397
|
+
const raw = await this.store.read(name);
|
|
1398
|
+
if (raw === null) continue;
|
|
1399
|
+
try {
|
|
1400
|
+
const envelope = JSON.parse(raw);
|
|
1401
|
+
if (!envelope?.batch?.events) throw new Error("missing events");
|
|
1402
|
+
out.push({ name, batch: envelope.batch, attempts: envelope.attempts ?? 0 });
|
|
1403
|
+
} catch {
|
|
1404
|
+
await this.store.remove(name);
|
|
1405
|
+
this.abandonedCount += 1;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return out;
|
|
1409
|
+
}
|
|
1410
|
+
async remove(name) {
|
|
1411
|
+
await this.store.remove(name);
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Record a failed attempt.
|
|
1415
|
+
*
|
|
1416
|
+
* Returns false when the batch has been abandoned, so the caller knows it is
|
|
1417
|
+
* gone rather than merely deferred.
|
|
1418
|
+
*/
|
|
1419
|
+
async recordFailure(entry) {
|
|
1420
|
+
const attempts = entry.attempts + 1;
|
|
1421
|
+
if (attempts >= this.maxAttempts) {
|
|
1422
|
+
await this.store.remove(entry.name);
|
|
1423
|
+
this.abandonedCount += 1;
|
|
1424
|
+
return false;
|
|
1425
|
+
}
|
|
1426
|
+
const envelope = { batch: entry.batch, attempts };
|
|
1427
|
+
await this.store.write(entry.name, JSON.stringify(envelope));
|
|
1428
|
+
return true;
|
|
1429
|
+
}
|
|
1430
|
+
/** Drop oldest batches until the queue is under its ceiling. */
|
|
1431
|
+
async prune() {
|
|
1432
|
+
const names = (await this.store.list()).sort();
|
|
1433
|
+
const excess = names.length - (this.maxBatches - 1);
|
|
1434
|
+
for (let i = 0; i < excess; i += 1) {
|
|
1435
|
+
const name = names[i];
|
|
1436
|
+
if (!name) break;
|
|
1437
|
+
await this.store.remove(name);
|
|
1438
|
+
this.droppedCount += 1;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
|
|
1443
|
+
// ../core/src/safe.ts
|
|
1444
|
+
var FAILURE_THRESHOLD = 5;
|
|
1445
|
+
var consecutiveFailures = 0;
|
|
1446
|
+
var disabled = false;
|
|
1447
|
+
function isSelfDisabled() {
|
|
1448
|
+
return disabled;
|
|
1449
|
+
}
|
|
1450
|
+
function safe(fn, fallback, label = "sdk") {
|
|
1451
|
+
return (...args) => {
|
|
1452
|
+
if (disabled) return fallback;
|
|
1453
|
+
try {
|
|
1454
|
+
const result = fn(...args);
|
|
1455
|
+
consecutiveFailures = 0;
|
|
1456
|
+
return result;
|
|
1457
|
+
} catch (err) {
|
|
1458
|
+
recordFailure(label, err);
|
|
1459
|
+
return fallback;
|
|
1460
|
+
}
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
function safeAsync(fn, fallback, label = "sdk") {
|
|
1464
|
+
return async (...args) => {
|
|
1465
|
+
if (disabled) return fallback;
|
|
1466
|
+
try {
|
|
1467
|
+
const result = await fn(...args);
|
|
1468
|
+
consecutiveFailures = 0;
|
|
1469
|
+
return result;
|
|
1470
|
+
} catch (err) {
|
|
1471
|
+
recordFailure(label, err);
|
|
1472
|
+
return fallback;
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
function recordFailure(label, err) {
|
|
1477
|
+
consecutiveFailures += 1;
|
|
1478
|
+
if (consecutiveFailures >= FAILURE_THRESHOLD) {
|
|
1479
|
+
disabled = true;
|
|
1480
|
+
console.warn(
|
|
1481
|
+
`[session-capture] disabled after ${FAILURE_THRESHOLD} consecutive internal errors (${label})`,
|
|
1482
|
+
err
|
|
1483
|
+
);
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
if (isDev()) {
|
|
1487
|
+
console.warn(`[session-capture] internal error in ${label}`, err);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
function isDev() {
|
|
1491
|
+
return typeof __DEV__ !== "undefined" && __DEV__ === true;
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// ../core/src/store.ts
|
|
1495
|
+
var QUEUE_DIR = "session-capture-queue";
|
|
1496
|
+
var CONFIG_DIR = "session-capture-config";
|
|
1497
|
+
var MemoryStore = class {
|
|
1498
|
+
constructor() {
|
|
1499
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1500
|
+
}
|
|
1501
|
+
async list() {
|
|
1502
|
+
return [...this.entries.keys()].sort();
|
|
1503
|
+
}
|
|
1504
|
+
async read(name) {
|
|
1505
|
+
return this.entries.get(name) ?? null;
|
|
1506
|
+
}
|
|
1507
|
+
async write(name, contents) {
|
|
1508
|
+
this.entries.set(name, contents);
|
|
1509
|
+
}
|
|
1510
|
+
async remove(name) {
|
|
1511
|
+
this.entries.delete(name);
|
|
1512
|
+
}
|
|
1513
|
+
/** Test helper. */
|
|
1514
|
+
get size() {
|
|
1515
|
+
return this.entries.size;
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
|
|
1519
|
+
// src/device.ts
|
|
1520
|
+
var import_react_native = require("react-native");
|
|
1521
|
+
function readDeviceContext(appVersion) {
|
|
1522
|
+
const context = {};
|
|
1523
|
+
if (appVersion) {
|
|
1524
|
+
context.appVersion = appVersion;
|
|
1525
|
+
}
|
|
1526
|
+
if (import_react_native.Platform.OS === "ios" || import_react_native.Platform.OS === "android") {
|
|
1527
|
+
context.platform = import_react_native.Platform.OS;
|
|
1528
|
+
}
|
|
1529
|
+
if (import_react_native.Platform.Version !== void 0 && import_react_native.Platform.Version !== null) {
|
|
1530
|
+
context.osVersion = String(import_react_native.Platform.Version);
|
|
1531
|
+
}
|
|
1532
|
+
return context;
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
// src/store-expo.ts
|
|
1536
|
+
var import_expo_file_system = require("expo-file-system");
|
|
1537
|
+
var ExpoFileStore = class {
|
|
1538
|
+
/**
|
|
1539
|
+
* `directory` is a parameter because the queue and the remote-config cache
|
|
1540
|
+
* must not share one. `SendQueue.peek()` treats every file it can see as a
|
|
1541
|
+
* queued batch and *deletes* whatever fails to parse as one, so a config
|
|
1542
|
+
* file stored alongside the queue would vanish on the first drain.
|
|
1543
|
+
*/
|
|
1544
|
+
constructor(directory = QUEUE_DIR) {
|
|
1545
|
+
this.dir = new import_expo_file_system.Directory(import_expo_file_system.Paths.document, directory);
|
|
1546
|
+
if (!this.dir.exists) {
|
|
1547
|
+
this.dir.create({ intermediates: true });
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
async list() {
|
|
1551
|
+
return this.dir.list().filter((entry) => entry instanceof import_expo_file_system.File).map((file) => file.name);
|
|
1552
|
+
}
|
|
1553
|
+
async read(name) {
|
|
1554
|
+
const file = new import_expo_file_system.File(this.dir, name);
|
|
1555
|
+
return file.exists ? file.text() : null;
|
|
1556
|
+
}
|
|
1557
|
+
async write(name, contents) {
|
|
1558
|
+
const file = new import_expo_file_system.File(this.dir, name);
|
|
1559
|
+
if (!file.exists) {
|
|
1560
|
+
file.create();
|
|
1561
|
+
}
|
|
1562
|
+
file.write(contents);
|
|
1563
|
+
}
|
|
1564
|
+
async remove(name) {
|
|
1565
|
+
const file = new import_expo_file_system.File(this.dir, name);
|
|
1566
|
+
if (file.exists) {
|
|
1567
|
+
file.delete();
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
function createPersistentStore(directory = QUEUE_DIR) {
|
|
1572
|
+
try {
|
|
1573
|
+
return new ExpoFileStore(directory);
|
|
1574
|
+
} catch {
|
|
1575
|
+
return null;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// src/lifecycle.ts
|
|
1580
|
+
var import_react_native2 = require("react-native");
|
|
1581
|
+
function installLifecycleListener(onChange) {
|
|
1582
|
+
try {
|
|
1583
|
+
const subscription = import_react_native2.AppState.addEventListener(
|
|
1584
|
+
"change",
|
|
1585
|
+
(next) => {
|
|
1586
|
+
if (next === "active") onChange("active");
|
|
1587
|
+
else if (next === "background") onChange("background");
|
|
1588
|
+
}
|
|
1589
|
+
);
|
|
1590
|
+
return () => {
|
|
1591
|
+
try {
|
|
1592
|
+
subscription?.remove?.();
|
|
1593
|
+
} catch {
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
} catch {
|
|
1597
|
+
return () => {
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
// src/index.ts
|
|
1603
|
+
var DRAIN_INTERVAL_MS = 3e4;
|
|
1604
|
+
var CONFIG_REFRESH_MS = 6 * 60 * 60 * 1e3;
|
|
1605
|
+
var CONFIG_MIN_INTERVAL_MS = 15 * 60 * 1e3;
|
|
1606
|
+
var core = null;
|
|
1607
|
+
var dispatcher = null;
|
|
1608
|
+
var queue = null;
|
|
1609
|
+
var configStore = null;
|
|
1610
|
+
var drainTimer = null;
|
|
1611
|
+
var configTimer = null;
|
|
1612
|
+
var lastConfigFetch = 0;
|
|
1613
|
+
var teardown = [];
|
|
1614
|
+
var networkOptions = {
|
|
1615
|
+
maskedKeys: [],
|
|
1616
|
+
urlDenyList: [],
|
|
1617
|
+
// Off until a project says otherwise, and off again the moment it stops
|
|
1618
|
+
// saying so — including when a config fetch is what turned it on.
|
|
1619
|
+
captureBodies: false
|
|
1620
|
+
};
|
|
1621
|
+
function applyConfig(config) {
|
|
1622
|
+
core?.applyConfig(config);
|
|
1623
|
+
networkOptions.maskedKeys = config.maskedKeys;
|
|
1624
|
+
networkOptions.urlDenyList = config.urlDenyList;
|
|
1625
|
+
networkOptions.captureBodies = config.captureBodies;
|
|
1626
|
+
}
|
|
1627
|
+
async function refreshConfig(options, force = false) {
|
|
1628
|
+
const now = Date.now();
|
|
1629
|
+
if (!force && now - lastConfigFetch < CONFIG_MIN_INTERVAL_MS) {
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
lastConfigFetch = now;
|
|
1633
|
+
const config = await fetchRemoteConfig({
|
|
1634
|
+
endpoint: options.endpoint,
|
|
1635
|
+
apiKey: options.apiKey,
|
|
1636
|
+
projectId: options.projectId
|
|
1637
|
+
});
|
|
1638
|
+
if (!config || !core) {
|
|
1639
|
+
return;
|
|
1640
|
+
}
|
|
1641
|
+
applyConfig(config);
|
|
1642
|
+
if (configStore) {
|
|
1643
|
+
await saveConfig(configStore, config);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
async function bootstrapConfig(options) {
|
|
1647
|
+
if (configStore) {
|
|
1648
|
+
const cached = await loadCachedConfig(configStore);
|
|
1649
|
+
if (cached && core) {
|
|
1650
|
+
applyConfig(cached);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
await refreshConfig(options, true);
|
|
1654
|
+
}
|
|
1655
|
+
var init = safe((options) => {
|
|
1656
|
+
if (core) {
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
const store = createPersistentStore() ?? new MemoryStore();
|
|
1660
|
+
queue = new SendQueue({ store });
|
|
1661
|
+
configStore = createPersistentStore(CONFIG_DIR) ?? new MemoryStore();
|
|
1662
|
+
dispatcher = new Dispatcher({
|
|
1663
|
+
queue,
|
|
1664
|
+
transport: {
|
|
1665
|
+
endpoint: options.endpoint,
|
|
1666
|
+
apiKey: options.apiKey,
|
|
1667
|
+
sdkVersion: SDK_VERSION
|
|
1668
|
+
}
|
|
1669
|
+
});
|
|
1670
|
+
core = new SdkCore({
|
|
1671
|
+
onFlush: async (batch) => {
|
|
1672
|
+
await queue?.enqueue(batch);
|
|
1673
|
+
void dispatcher?.drain();
|
|
1674
|
+
},
|
|
1675
|
+
deviceContext: () => ({ ...readDeviceContext(options.appVersion) })
|
|
1676
|
+
});
|
|
1677
|
+
core.init(options);
|
|
1678
|
+
void bootstrapConfig(options).catch(() => {
|
|
1679
|
+
});
|
|
1680
|
+
teardown.push(
|
|
1681
|
+
installLifecycleListener((state) => {
|
|
1682
|
+
core?.onAppStateChange(state);
|
|
1683
|
+
if (state === "active") {
|
|
1684
|
+
void refreshConfig(options).catch(() => {
|
|
1685
|
+
});
|
|
1686
|
+
dispatcher?.resume();
|
|
1687
|
+
void dispatcher?.drain();
|
|
1688
|
+
}
|
|
1689
|
+
})
|
|
1690
|
+
);
|
|
1691
|
+
drainTimer = setInterval(() => {
|
|
1692
|
+
void dispatcher?.drain();
|
|
1693
|
+
}, DRAIN_INTERVAL_MS);
|
|
1694
|
+
drainTimer?.unref?.();
|
|
1695
|
+
configTimer = setInterval(() => {
|
|
1696
|
+
void refreshConfig(options).catch(() => {
|
|
1697
|
+
});
|
|
1698
|
+
}, CONFIG_REFRESH_MS);
|
|
1699
|
+
configTimer?.unref?.();
|
|
1700
|
+
teardown.push(
|
|
1701
|
+
installErrorHandlers((error) => core?.captureCrash(error))
|
|
1702
|
+
);
|
|
1703
|
+
if (options.captureNetwork !== false) {
|
|
1704
|
+
teardown.push(
|
|
1705
|
+
installNetworkCapture({
|
|
1706
|
+
ingestEndpoint: options.endpoint,
|
|
1707
|
+
get urlDenyList() {
|
|
1708
|
+
return networkOptions.urlDenyList;
|
|
1709
|
+
},
|
|
1710
|
+
get maskedKeys() {
|
|
1711
|
+
return networkOptions.maskedKeys;
|
|
1712
|
+
},
|
|
1713
|
+
get captureBodies() {
|
|
1714
|
+
return networkOptions.captureBodies;
|
|
1715
|
+
},
|
|
1716
|
+
onEvent: (event) => core?.captureNetwork(event)
|
|
1717
|
+
})
|
|
1718
|
+
);
|
|
1719
|
+
}
|
|
1720
|
+
}, void 0, "init");
|
|
1721
|
+
var setEnabled = safe((enabled) => {
|
|
1722
|
+
core?.setEnabled(enabled);
|
|
1723
|
+
}, void 0, "setEnabled");
|
|
1724
|
+
var isEnabled = safe(
|
|
1725
|
+
() => core?.isEnabled() ?? false,
|
|
1726
|
+
false,
|
|
1727
|
+
"isEnabled"
|
|
1728
|
+
);
|
|
1729
|
+
var track = safe(
|
|
1730
|
+
(name, properties) => {
|
|
1731
|
+
core?.capture("custom", { name, ...properties });
|
|
1732
|
+
},
|
|
1733
|
+
void 0,
|
|
1734
|
+
"track"
|
|
1735
|
+
);
|
|
1736
|
+
var screen = safe((name) => {
|
|
1737
|
+
core?.screen(name);
|
|
1738
|
+
}, void 0, "screen");
|
|
1739
|
+
var identify = safe(
|
|
1740
|
+
(userId, traits) => {
|
|
1741
|
+
core?.capture("user_action", { action: "identify", userId, ...traits });
|
|
1742
|
+
},
|
|
1743
|
+
void 0,
|
|
1744
|
+
"identify"
|
|
1745
|
+
);
|
|
1746
|
+
var flush = safeAsync(
|
|
1747
|
+
async () => {
|
|
1748
|
+
await core?.flush();
|
|
1749
|
+
await dispatcher?.drain();
|
|
1750
|
+
},
|
|
1751
|
+
void 0,
|
|
1752
|
+
"flush"
|
|
1753
|
+
);
|
|
1754
|
+
var pendingBatches = safeAsync(
|
|
1755
|
+
async () => await queue?.size() ?? 0,
|
|
1756
|
+
0,
|
|
1757
|
+
"pendingBatches"
|
|
1758
|
+
);
|
|
1759
|
+
var currentConfig = safe(
|
|
1760
|
+
() => core?.currentConfig() ?? DEFAULT_CONFIG,
|
|
1761
|
+
DEFAULT_CONFIG,
|
|
1762
|
+
"currentConfig"
|
|
1763
|
+
);
|
|
1764
|
+
var keepSessionAlive = safe(() => {
|
|
1765
|
+
core?.keepAlive();
|
|
1766
|
+
}, void 0, "keepSessionAlive");
|
|
1767
|
+
var onSession = safe(
|
|
1768
|
+
(listener) => core?.onSession(listener) ?? (() => {
|
|
1769
|
+
}),
|
|
1770
|
+
() => {
|
|
1771
|
+
},
|
|
1772
|
+
"onSession"
|
|
1773
|
+
);
|
|
1774
|
+
var onError = safe(
|
|
1775
|
+
(listener) => core?.onError(listener) ?? (() => {
|
|
1776
|
+
}),
|
|
1777
|
+
() => {
|
|
1778
|
+
},
|
|
1779
|
+
"onError"
|
|
1780
|
+
);
|
|
1781
|
+
var captureException = safe(
|
|
1782
|
+
(error, extra) => {
|
|
1783
|
+
core?.captureError(error, true, extra);
|
|
1784
|
+
},
|
|
1785
|
+
void 0,
|
|
1786
|
+
"captureException"
|
|
1787
|
+
);
|
|
1788
|
+
var breadcrumb = safe(
|
|
1789
|
+
(message, data) => {
|
|
1790
|
+
addBreadcrumb("manual", message, data);
|
|
1791
|
+
},
|
|
1792
|
+
void 0,
|
|
1793
|
+
"breadcrumb"
|
|
1794
|
+
);
|
|
1795
|
+
var startMeasure = safe((name) => {
|
|
1796
|
+
core?.mark(name);
|
|
1797
|
+
}, void 0, "startMeasure");
|
|
1798
|
+
var endMeasure = safe((name) => {
|
|
1799
|
+
core?.measure(name);
|
|
1800
|
+
}, void 0, "endMeasure");
|
|
1801
|
+
var markAppReady = safe(() => {
|
|
1802
|
+
core?.markReady();
|
|
1803
|
+
}, void 0, "markAppReady");
|
|
1804
|
+
var shutdown = safe(() => {
|
|
1805
|
+
if (drainTimer) {
|
|
1806
|
+
clearInterval(drainTimer);
|
|
1807
|
+
drainTimer = null;
|
|
1808
|
+
}
|
|
1809
|
+
if (configTimer) {
|
|
1810
|
+
clearInterval(configTimer);
|
|
1811
|
+
configTimer = null;
|
|
1812
|
+
}
|
|
1813
|
+
while (teardown.length) {
|
|
1814
|
+
teardown.pop()?.();
|
|
1815
|
+
}
|
|
1816
|
+
core?.shutdown();
|
|
1817
|
+
core = null;
|
|
1818
|
+
dispatcher = null;
|
|
1819
|
+
queue = null;
|
|
1820
|
+
configStore = null;
|
|
1821
|
+
lastConfigFetch = 0;
|
|
1822
|
+
networkOptions.maskedKeys = [];
|
|
1823
|
+
networkOptions.urlDenyList = [];
|
|
1824
|
+
}, void 0, "shutdown");
|