bugstack-sdk 2.2.2 → 2.4.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +117 -2
  3. package/dist/adapters/express/index.d.mts +2 -2
  4. package/dist/adapters/express/index.d.ts +2 -2
  5. package/dist/adapters/express/index.js +408 -42
  6. package/dist/adapters/express/index.js.map +1 -1
  7. package/dist/adapters/express/index.mjs +408 -42
  8. package/dist/adapters/express/index.mjs.map +1 -1
  9. package/dist/adapters/generic/index.d.mts +2 -2
  10. package/dist/adapters/generic/index.d.ts +2 -2
  11. package/dist/adapters/generic/index.js +456 -42
  12. package/dist/adapters/generic/index.js.map +1 -1
  13. package/dist/adapters/generic/index.mjs +453 -43
  14. package/dist/adapters/generic/index.mjs.map +1 -1
  15. package/dist/adapters/nextjs/index.d.mts +2 -2
  16. package/dist/adapters/nextjs/index.d.ts +2 -2
  17. package/dist/adapters/nextjs/index.js +408 -42
  18. package/dist/adapters/nextjs/index.js.map +1 -1
  19. package/dist/adapters/nextjs/index.mjs +408 -42
  20. package/dist/adapters/nextjs/index.mjs.map +1 -1
  21. package/dist/browser/index.d.mts +131 -0
  22. package/dist/browser/index.d.ts +131 -0
  23. package/dist/browser/index.js +992 -0
  24. package/dist/browser/index.js.map +1 -0
  25. package/dist/browser/index.mjs +984 -0
  26. package/dist/browser/index.mjs.map +1 -0
  27. package/dist/{client-DK_ItP55.d.mts → client-B9WaTEYj.d.mts} +148 -1
  28. package/dist/{client-DK_ItP55.d.ts → client-B9WaTEYj.d.ts} +148 -1
  29. package/dist/index.d.mts +2 -2
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.js +468 -54
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +465 -55
  34. package/dist/index.mjs.map +1 -1
  35. package/package.json +17 -7
@@ -0,0 +1,992 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/browser/redact.ts
8
+ function currentRoute(loc = location) {
9
+ return cap(loc.pathname || "/", 300);
10
+ }
11
+ function requestPath(raw, base = location) {
12
+ var _a;
13
+ try {
14
+ const u = new URL(raw, base.href);
15
+ return cap(u.origin === base.origin ? u.pathname : `${u.host}${u.pathname}`, 300);
16
+ } catch {
17
+ return cap((_a = String(raw).split(/[?#]/)[0]) != null ? _a : "", 300);
18
+ }
19
+ }
20
+ function isEndpoint(raw, endpoint, base = location) {
21
+ try {
22
+ const u = new URL(raw, base.href);
23
+ const e = new URL(endpoint, base.href);
24
+ return u.origin === e.origin && u.pathname === e.pathname;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+ function cap(s, max) {
30
+ return s.length > max ? s.slice(0, max) : s;
31
+ }
32
+ var ACTIONABLE = 'button, a[href], [role="button"], input[type="submit"], input[type="button"], input[type="reset"], input[type="image"]';
33
+ function clickTarget(target) {
34
+ var _a;
35
+ let el = null;
36
+ if (target && target.nodeType === 1) el = target;
37
+ else if (target && target.nodeType === 3) el = target.parentElement;
38
+ if (!el) return null;
39
+ return (_a = el.closest(ACTIONABLE)) != null ? _a : el;
40
+ }
41
+ function isActionable(el) {
42
+ var _a;
43
+ if (!el.matches(ACTIONABLE)) return false;
44
+ if (el.matches("a[href]")) {
45
+ const href = (_a = el.getAttribute("href")) != null ? _a : "";
46
+ if (el.getAttribute("target") === "_blank" || el.hasAttribute("download")) return false;
47
+ if (/^(mailto|tel|sms):/i.test(href)) return false;
48
+ }
49
+ return !isDisabled(el);
50
+ }
51
+ function isDisabled(el) {
52
+ return el.hasAttribute("disabled") || el.getAttribute("aria-disabled") === "true" || el.disabled === true;
53
+ }
54
+ function stableClass(c) {
55
+ if (!/^[A-Za-z_][\w-]*$/.test(c)) return false;
56
+ if (c.length > 40) return false;
57
+ return !(/\d/.test(c) && c.length > 8);
58
+ }
59
+ function escapeIdent(s) {
60
+ return s.replace(/[^\w-]/g, (ch) => `\\${ch}`);
61
+ }
62
+ function selectorFor(el) {
63
+ var _a, _b;
64
+ const parts = [];
65
+ let cur = el;
66
+ for (let depth = 0; cur && depth < 5; depth++) {
67
+ if (cur.nodeType !== 1 || cur === ((_a = cur.ownerDocument) == null ? void 0 : _a.documentElement)) break;
68
+ let part = cur.tagName.toLowerCase();
69
+ const id = cur.getAttribute("id");
70
+ if (id && id.length <= 60) part += `#${escapeIdent(id)}`;
71
+ const classes = depth === 0 ? Array.from((_b = cur.classList) != null ? _b : []).filter(stableClass).slice(0, 2) : [];
72
+ for (const c of classes) part += `.${c}`;
73
+ const testId = cur.getAttribute("data-testid");
74
+ if (testId) part += `[data-testid="${cap(testId, 40).replace(/"/g, "")}"]`;
75
+ parts.unshift(part);
76
+ if (id) break;
77
+ cur = cur.parentElement;
78
+ }
79
+ return cap(parts.join(" > "), 200);
80
+ }
81
+ var SECRET_INPUT = 'input, textarea, select, [contenteditable=""], [contenteditable="true"]';
82
+ function labelFor(el) {
83
+ var _a, _b, _c;
84
+ const aria = (_a = el.getAttribute("aria-label")) != null ? _a : el.getAttribute("title");
85
+ if (aria && aria.trim()) return cap(aria.trim().replace(/\s+/g, " "), 60);
86
+ if (el.matches(SECRET_INPUT) || el.querySelector(SECRET_INPUT)) return void 0;
87
+ if (el.isContentEditable || el.closest('[contenteditable=""], [contenteditable="true"]')) {
88
+ return void 0;
89
+ }
90
+ const raw = (_c = (_b = el.innerText) != null ? _b : el.textContent) != null ? _c : "";
91
+ const text = String(raw).trim().replace(/\s+/g, " ");
92
+ return text ? cap(text, 60) : void 0;
93
+ }
94
+ function describeElement(el) {
95
+ const label = labelFor(el);
96
+ return label ? { selector: selectorFor(el), label } : { selector: selectorFor(el) };
97
+ }
98
+ function describeField(el) {
99
+ var _a;
100
+ const selector = selectorFor(el);
101
+ let label = el.getAttribute("aria-label");
102
+ if (!label) {
103
+ const id = el.getAttribute("id");
104
+ const doc = el.ownerDocument;
105
+ const forLabel = id && doc ? doc.querySelector(`label[for="${id.replace(/["\\]/g, "")}"]`) : null;
106
+ const wrapping = el.closest("label");
107
+ const source = forLabel != null ? forLabel : wrapping;
108
+ if (source) {
109
+ const clone = source.cloneNode(true);
110
+ for (const f of Array.from(clone.querySelectorAll(SECRET_INPUT))) f.remove();
111
+ label = clone.textContent;
112
+ }
113
+ }
114
+ if (!label) label = (_a = el.getAttribute("placeholder")) != null ? _a : el.getAttribute("name");
115
+ const t = label ? label.trim().replace(/\s+/g, " ") : "";
116
+ return t ? { selector, label: cap(t, 60) } : { selector };
117
+ }
118
+ function describeForm(form) {
119
+ var _a, _b;
120
+ const selector = selectorFor(form);
121
+ const submit = form.querySelector('button[type="submit"], button:not([type]), input[type="submit"]');
122
+ let label = ((_a = form.getAttribute("aria-label")) == null ? void 0 : _a.trim()) || void 0;
123
+ if (!label && submit) {
124
+ label = submit.matches("input") ? (_b = submit.getAttribute("value")) != null ? _b : void 0 : labelFor(submit);
125
+ }
126
+ return label ? { selector, label: cap(label.trim().replace(/\s+/g, " "), 60) } : { selector };
127
+ }
128
+ function isNotFoundPage(doc = document) {
129
+ var _a;
130
+ try {
131
+ if (doc.querySelector('meta[name="next-error"][content="not-found"]')) return true;
132
+ return /^\s*404\b/.test((_a = doc.title) != null ? _a : "");
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ // src/browser/transport.ts
139
+ var MAX_EVENTS_PER_BATCH = 100;
140
+ var MAX_BATCH_BYTES = 64 * 1024;
141
+ var MAX_QUEUED_EVENTS = 500;
142
+ var MAX_ATTEMPTS = 3;
143
+ function byteLength(s) {
144
+ try {
145
+ return new TextEncoder().encode(s).length;
146
+ } catch {
147
+ return s.length * 3;
148
+ }
149
+ }
150
+ function takeBatch(queue, envelope) {
151
+ const events = [];
152
+ const overhead = byteLength(JSON.stringify({ ...envelope, events: [] }));
153
+ let bytes = overhead;
154
+ while (queue.length > 0 && events.length < MAX_EVENTS_PER_BATCH) {
155
+ const next = queue[0];
156
+ const size = byteLength(JSON.stringify(next)) + 1;
157
+ if (bytes + size > MAX_BATCH_BYTES) {
158
+ if (events.length === 0) {
159
+ queue.shift();
160
+ continue;
161
+ }
162
+ break;
163
+ }
164
+ events.push(next);
165
+ bytes += size;
166
+ queue.shift();
167
+ }
168
+ return events.length > 0 ? { ...envelope, events } : null;
169
+ }
170
+ var Transport = class {
171
+ constructor(deps, envelope) {
172
+ __publicField(this, "deps", deps);
173
+ __publicField(this, "envelope", envelope);
174
+ __publicField(this, "queue", []);
175
+ __publicField(this, "stopped", false);
176
+ __publicField(this, "backoffMs", 0);
177
+ __publicField(this, "notBefore", 0);
178
+ __publicField(this, "inFlight", false);
179
+ __publicField(this, "attempts", 0);
180
+ }
181
+ get isStopped() {
182
+ return this.stopped;
183
+ }
184
+ get size() {
185
+ return this.queue.length;
186
+ }
187
+ push(event) {
188
+ if (this.stopped) return;
189
+ this.queue.push(event);
190
+ if (this.queue.length > MAX_QUEUED_EVENTS) this.queue.splice(0, this.queue.length - MAX_QUEUED_EVENTS);
191
+ }
192
+ /** Send one batch by fetch, when allowed. Never rejects. */
193
+ async flush() {
194
+ if (this.stopped || this.inFlight || this.queue.length === 0) return;
195
+ if (this.deps.now() < this.notBefore) return;
196
+ const fetchImpl = this.deps.fetchImpl;
197
+ if (!fetchImpl) return;
198
+ const batch = takeBatch(this.queue, this.envelope());
199
+ if (!batch) return;
200
+ this.inFlight = true;
201
+ try {
202
+ const res = await fetchImpl(this.deps.endpoint, {
203
+ method: "POST",
204
+ headers: { "Content-Type": "application/json", "X-BugStack-Key": this.deps.key },
205
+ body: JSON.stringify(batch),
206
+ keepalive: true,
207
+ credentials: "omit"
208
+ });
209
+ this.settle(res.status, batch.events);
210
+ } catch {
211
+ this.retry(batch.events);
212
+ } finally {
213
+ this.inFlight = false;
214
+ }
215
+ }
216
+ /** On page hide: everything left, by beacon (falls back to keepalive fetch). */
217
+ flushOnHide() {
218
+ if (this.stopped) return;
219
+ while (this.queue.length > 0) {
220
+ const batch = takeBatch(this.queue, this.envelope());
221
+ if (!batch) return;
222
+ const body = JSON.stringify(batch);
223
+ const url = beaconUrl(this.deps.endpoint, this.deps.key);
224
+ let sent = false;
225
+ try {
226
+ sent = this.deps.beacon ? this.deps.beacon(url, body) : false;
227
+ } catch {
228
+ sent = false;
229
+ }
230
+ if (!sent && this.deps.fetchImpl) {
231
+ try {
232
+ void this.deps.fetchImpl(this.deps.endpoint, {
233
+ method: "POST",
234
+ headers: { "Content-Type": "application/json", "X-BugStack-Key": this.deps.key },
235
+ body,
236
+ keepalive: true,
237
+ credentials: "omit"
238
+ }).catch(() => {
239
+ });
240
+ } catch {
241
+ }
242
+ }
243
+ }
244
+ }
245
+ stop() {
246
+ this.stopped = true;
247
+ this.queue = [];
248
+ }
249
+ settle(status, events) {
250
+ if (status >= 200 && status < 300) {
251
+ this.backoffMs = 0;
252
+ this.attempts = 0;
253
+ return;
254
+ }
255
+ if (status === 401 || status === 403) {
256
+ this.stop();
257
+ return;
258
+ }
259
+ if (status === 429) {
260
+ this.backoffMs = this.backoffMs === 0 ? 1e4 : Math.min(this.backoffMs * 2, 3e5);
261
+ this.notBefore = this.deps.now() + this.backoffMs;
262
+ this.queue.unshift(...events);
263
+ return;
264
+ }
265
+ if (status === 400 || status === 413) return;
266
+ this.retry(events);
267
+ }
268
+ retry(events) {
269
+ this.attempts += 1;
270
+ if (this.attempts >= MAX_ATTEMPTS) {
271
+ this.attempts = 0;
272
+ return;
273
+ }
274
+ this.queue.unshift(...events);
275
+ if (this.queue.length > MAX_QUEUED_EVENTS) this.queue.length = MAX_QUEUED_EVENTS;
276
+ }
277
+ };
278
+ function beaconUrl(endpoint, key) {
279
+ return `${endpoint}${endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(key)}`;
280
+ }
281
+ function envelopeFor(input) {
282
+ const env = { v: 1, sessionId: input.sessionId };
283
+ if (input.user && (input.user.id || input.user.email)) env.user = input.user;
284
+ if (input.release) env.release = input.release;
285
+ if (input.environment) env.environment = input.environment;
286
+ return env;
287
+ }
288
+
289
+ // src/browser/recorder.ts
290
+ var DEFAULT_ENDPOINT = "https://dashboard.bugstack.ai/api/v1/sessions/ingest";
291
+ var CLICK_WINDOW_MS = 1e3;
292
+ var RAGE_CLICKS = 3;
293
+ var FLUSH_INTERVAL_MS = 5e3;
294
+ var MAX_SAME_EVENT = 5;
295
+ var MAX_ERRORS_PER_PAGE = 100;
296
+ var SESSION_KEY = "bugstack.session";
297
+ var SAMPLED_KEY = "bugstack.sampled";
298
+ var FRUSTRATION_SAMPLED_KEY = "bugstack.frustration";
299
+ var LAST_LINK_KEY = "bugstack.lastLink";
300
+ var THRASH_WINDOW_MS = 1e4;
301
+ var THRASH_SWITCHES = 4;
302
+ var DEFAULT_FRUSTRATION_PER_PAGE = 20;
303
+ var MAX_INVALID_FIELDS = 5;
304
+ var FIELD = "input, select, textarea";
305
+ function frustrationFor(config) {
306
+ var _a;
307
+ const f = config.frustration;
308
+ const off = { on: false, maxPerPage: 0 };
309
+ if (!f) return off;
310
+ const obj = typeof f === "object" ? f : {};
311
+ if (obj.enabled === false) return off;
312
+ const maxPerPage = typeof obj.maxPerPage === "number" && obj.maxPerPage >= 1 ? Math.min(100, Math.floor(obj.maxPerPage)) : DEFAULT_FRUSTRATION_PER_PAGE;
313
+ const rate = typeof obj.sampleRate === "number" && Number.isFinite(obj.sampleRate) ? Math.min(1, Math.max(0, obj.sampleRate)) : 1;
314
+ if (rate >= 1) return { on: true, maxPerPage };
315
+ let storage = null;
316
+ try {
317
+ storage = window.sessionStorage;
318
+ } catch {
319
+ storage = null;
320
+ }
321
+ let raw = (_a = storage == null ? void 0 : storage.getItem(FRUSTRATION_SAMPLED_KEY)) != null ? _a : null;
322
+ if (raw !== "1" && raw !== "0") {
323
+ raw = Math.random() < rate ? "1" : "0";
324
+ try {
325
+ storage == null ? void 0 : storage.setItem(FRUSTRATION_SAMPLED_KEY, raw);
326
+ } catch {
327
+ }
328
+ }
329
+ return { on: raw === "1", maxPerPage };
330
+ }
331
+ function safe(fn) {
332
+ try {
333
+ fn();
334
+ } catch {
335
+ }
336
+ }
337
+ function randomId() {
338
+ const bytes = new Uint8Array(12);
339
+ try {
340
+ crypto.getRandomValues(bytes);
341
+ } catch {
342
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
343
+ }
344
+ return `s_${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
345
+ }
346
+ var SESSION_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
347
+ function sessionFor(sampleRate) {
348
+ var _a, _b;
349
+ let storage = null;
350
+ try {
351
+ storage = window.sessionStorage;
352
+ } catch {
353
+ storage = null;
354
+ }
355
+ let sessionId = (_a = storage == null ? void 0 : storage.getItem(SESSION_KEY)) != null ? _a : null;
356
+ let sampledRaw = (_b = storage == null ? void 0 : storage.getItem(SAMPLED_KEY)) != null ? _b : null;
357
+ if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
358
+ sessionId = randomId();
359
+ sampledRaw = null;
360
+ try {
361
+ storage == null ? void 0 : storage.setItem(SESSION_KEY, sessionId);
362
+ } catch {
363
+ }
364
+ }
365
+ if (sampledRaw !== "1" && sampledRaw !== "0") {
366
+ const rate = Number.isFinite(sampleRate) ? Math.min(1, Math.max(0, sampleRate)) : 1;
367
+ sampledRaw = Math.random() < rate ? "1" : "0";
368
+ try {
369
+ storage == null ? void 0 : storage.setItem(SAMPLED_KEY, sampledRaw);
370
+ } catch {
371
+ }
372
+ }
373
+ return { sessionId, sampled: sampledRaw === "1" };
374
+ }
375
+ function nowIso() {
376
+ return (/* @__PURE__ */ new Date()).toISOString();
377
+ }
378
+ function errorShape(err) {
379
+ var _a, _b;
380
+ if (err instanceof Error || err && typeof err === "object" && "message" in err) {
381
+ const e = err;
382
+ const out = {
383
+ name: cap(String(e.name || "Error"), 200),
384
+ message: cap(String((_a = e.message) != null ? _a : ""), 1e3)
385
+ };
386
+ if (typeof e.stack === "string" && e.stack) out.stack = cap(e.stack, 8e3);
387
+ return out;
388
+ }
389
+ let message;
390
+ try {
391
+ message = typeof err === "string" ? err : (_b = JSON.stringify(err)) != null ? _b : String(err);
392
+ } catch {
393
+ message = String(err);
394
+ }
395
+ return { name: "UnhandledRejection", message: cap(message, 1e3) };
396
+ }
397
+ var OWN_FILE = /[/\\](?:@bugstack[/\\]browser|bugstack-sdk[/\\]dist[/\\]browser)[/\\]/i;
398
+ var SessionRecorder = class {
399
+ constructor(config, sessionId) {
400
+ __publicField(this, "sessionId", sessionId);
401
+ __publicField(this, "transport");
402
+ __publicField(this, "user", null);
403
+ __publicField(this, "patches", []);
404
+ __publicField(this, "listeners", []);
405
+ __publicField(this, "observer", null);
406
+ __publicField(this, "flushTimer", null);
407
+ __publicField(this, "activity", 0);
408
+ __publicField(this, "lastRoute", null);
409
+ __publicField(this, "seen", /* @__PURE__ */ new Map());
410
+ __publicField(this, "errorsThisPage", 0);
411
+ __publicField(this, "clickHistory", /* @__PURE__ */ new Map());
412
+ __publicField(this, "deadReportedAt", /* @__PURE__ */ new WeakMap());
413
+ // Frustration (OFF unless config.frustration).
414
+ __publicField(this, "frustration");
415
+ __publicField(this, "maxFrustrationPerPage");
416
+ __publicField(this, "frustrationThisPage", 0);
417
+ __publicField(this, "lastClick", null);
418
+ __publicField(this, "pendingLink", null);
419
+ __publicField(this, "forms", /* @__PURE__ */ new Map());
420
+ __publicField(this, "navTrail", []);
421
+ __publicField(this, "thrashReported", /* @__PURE__ */ new Set());
422
+ /** Elements whose click already became an error click: never also a dead click. */
423
+ __publicField(this, "errorClicked", /* @__PURE__ */ new WeakSet());
424
+ __publicField(this, "unloading", false);
425
+ __publicField(this, "closed", false);
426
+ __publicField(this, "endpoint");
427
+ this.endpoint = config.endpoint || DEFAULT_ENDPOINT;
428
+ const fr = frustrationFor(config);
429
+ this.frustration = fr.on;
430
+ this.maxFrustrationPerPage = fr.maxPerPage;
431
+ const fetchImpl = typeof window.fetch === "function" ? window.fetch.bind(window) : void 0;
432
+ const beacon = typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function" ? (url, body) => navigator.sendBeacon(url, body) : void 0;
433
+ this.transport = new Transport(
434
+ { endpoint: this.endpoint, key: config.key, fetchImpl, beacon, now: () => Date.now() },
435
+ () => envelopeFor({
436
+ sessionId: this.sessionId,
437
+ user: this.user,
438
+ release: config.release,
439
+ environment: config.environment
440
+ })
441
+ );
442
+ }
443
+ /** For tests and flush(): the transport. */
444
+ get queue() {
445
+ return this.transport;
446
+ }
447
+ install() {
448
+ this.listen(window, "error", (ev) => this.onError(ev));
449
+ this.listen(
450
+ window,
451
+ "unhandledrejection",
452
+ (ev) => this.recordError(ev.reason)
453
+ );
454
+ this.listen(document, "click", (ev) => this.onClick(ev), true);
455
+ this.listen(window, "popstate", () => this.onNavigation());
456
+ this.listen(window, "hashchange", () => this.onNavigation());
457
+ this.listen(window, "pagehide", () => {
458
+ this.unloading = true;
459
+ this.flushForms();
460
+ this.onHide();
461
+ });
462
+ if (this.frustration) {
463
+ this.listen(document, "invalid", (ev) => this.onInvalid(ev.target), true);
464
+ this.listen(document, "submit", (ev) => this.onSubmit(ev.target), true);
465
+ }
466
+ this.listen(window, "beforeunload", () => {
467
+ this.unloading = true;
468
+ });
469
+ this.listen(window, "pageshow", () => {
470
+ this.unloading = false;
471
+ });
472
+ this.listen(document, "visibilitychange", () => {
473
+ if (document.visibilityState === "hidden") this.onHide();
474
+ });
475
+ this.patchFetch();
476
+ this.patchXhr();
477
+ this.patchHistory();
478
+ safe(() => {
479
+ if (this.frustration && typeof MutationObserver === "function") {
480
+ this.observer = new MutationObserver(() => {
481
+ this.activity++;
482
+ });
483
+ this.observer.observe(document.documentElement, {
484
+ subtree: true,
485
+ childList: true,
486
+ attributes: true,
487
+ characterData: true
488
+ });
489
+ }
490
+ });
491
+ this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);
492
+ this.onNavigation(true);
493
+ }
494
+ setUser(user) {
495
+ if (!user) {
496
+ this.user = null;
497
+ return;
498
+ }
499
+ const next = {};
500
+ if (typeof user.id === "string" && user.id.trim()) next.id = cap(user.id.trim(), 200);
501
+ else if (typeof user.id === "number") next.id = String(user.id);
502
+ if (typeof user.email === "string" && user.email.trim()) next.email = cap(user.email.trim(), 320);
503
+ this.user = next.id || next.email ? next : null;
504
+ }
505
+ captureError(err) {
506
+ this.recordError(err);
507
+ }
508
+ flush() {
509
+ return this.transport.flush();
510
+ }
511
+ close() {
512
+ if (this.closed) return;
513
+ this.closed = true;
514
+ safe(() => this.transport.flushOnHide());
515
+ for (const off of this.listeners.splice(0)) safe(off);
516
+ for (const p of this.patches.splice(0)) safe(p.restore);
517
+ safe(() => {
518
+ var _a;
519
+ return (_a = this.observer) == null ? void 0 : _a.disconnect();
520
+ });
521
+ if (this.flushTimer) clearInterval(this.flushTimer);
522
+ for (const h of this.clickHistory.values()) if (h.timer) clearTimeout(h.timer);
523
+ this.clickHistory.clear();
524
+ }
525
+ // --- recording -----------------------------------------------------------
526
+ push(event, dedupeKey) {
527
+ var _a;
528
+ if (this.closed) return;
529
+ if (dedupeKey) {
530
+ const n = ((_a = this.seen.get(dedupeKey)) != null ? _a : 0) + 1;
531
+ this.seen.set(dedupeKey, n);
532
+ if (n > MAX_SAME_EVENT) return;
533
+ }
534
+ this.transport.push(event);
535
+ if (this.transport.size >= 100) void this.flush();
536
+ }
537
+ onError(ev) {
538
+ safe(() => {
539
+ var _a;
540
+ if (!ev || typeof ev.message !== "string") return;
541
+ if (ev.message === "Script error." && !ev.filename && !ev.error) return;
542
+ if (ev.filename && OWN_FILE.test(ev.filename)) return;
543
+ this.recordError((_a = ev.error) != null ? _a : { name: "Error", message: ev.message });
544
+ });
545
+ }
546
+ recordError(err) {
547
+ safe(() => {
548
+ const error = errorShape(err);
549
+ if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
550
+ this.errorsThisPage++;
551
+ const route = currentRoute();
552
+ this.push({ kind: "error", at: nowIso(), route, error }, `error:${error.name}:${error.message}:${route}`);
553
+ const c = this.lastClick;
554
+ if (this.frustration && c && !c.errored && Date.now() - c.at <= CLICK_WINDOW_MS) {
555
+ c.errored = true;
556
+ this.errorClicked.add(c.el);
557
+ const element = describeElement(c.el);
558
+ this.pushFrustration(
559
+ {
560
+ kind: "error_click",
561
+ at: new Date(c.at).toISOString(),
562
+ route: c.route,
563
+ element,
564
+ error: { name: error.name, message: cap(error.message, 200) }
565
+ },
566
+ `error_click:${c.route}:${element.selector}:${error.name}`
567
+ );
568
+ }
569
+ });
570
+ }
571
+ /** A frustration event: only when recording frustration, at most maxPerPage a page view. */
572
+ pushFrustration(event, dedupeKey) {
573
+ if (!this.frustration || this.frustrationThisPage >= this.maxFrustrationPerPage) return;
574
+ this.frustrationThisPage++;
575
+ this.push(event, dedupeKey);
576
+ }
577
+ // --- forms ---------------------------------------------------------------
578
+ formState(form) {
579
+ let st = this.forms.get(form);
580
+ if (!st) {
581
+ st = { route: currentRoute(), fields: /* @__PURE__ */ new Map(), attempts: 0, lastAttemptAt: 0, submittedAt: 0 };
582
+ this.forms.set(form, st);
583
+ }
584
+ return st;
585
+ }
586
+ addFields(st, fields) {
587
+ for (const f of fields) {
588
+ if (st.fields.size >= MAX_INVALID_FIELDS) return;
589
+ const d = describeField(f);
590
+ if (!st.fields.has(d.selector)) st.fields.set(d.selector, d);
591
+ }
592
+ }
593
+ /** A native validation failure: one `invalid` per bad field, one attempt per submit. */
594
+ onInvalid(target) {
595
+ safe(() => {
596
+ var _a;
597
+ const field = target && target.nodeType === 1 ? target : null;
598
+ if (!field || !field.matches(FIELD)) return;
599
+ const form = (_a = field.form) != null ? _a : field.closest("form");
600
+ if (!form) return;
601
+ const st = this.formState(form);
602
+ const now = Date.now();
603
+ if (now - st.lastAttemptAt > 250) st.attempts++;
604
+ st.lastAttemptAt = now;
605
+ this.addFields(st, [field]);
606
+ });
607
+ }
608
+ /**
609
+ * A submit that native validation let through: the app's own validation
610
+ * may still reject it. Within the click window, a field marked
611
+ * aria-invalid (or :invalid under novalidate) or a non-empty role="alert"
612
+ * in the form is a failed attempt; neither is a submit that passed.
613
+ */
614
+ onSubmit(target) {
615
+ safe(() => {
616
+ const form = target && target.nodeType === 1 ? target : null;
617
+ if (!form || !form.matches("form")) return;
618
+ const route = currentRoute();
619
+ const pending = this.forms.get(form);
620
+ if (pending) pending.submittedAt = Date.now();
621
+ setTimeout(() => {
622
+ safe(() => {
623
+ if (this.closed || this.unloading) return;
624
+ if (!form.isConnected || currentRoute() !== route) {
625
+ this.forms.delete(form);
626
+ return;
627
+ }
628
+ const bad = Array.from(form.querySelectorAll('[aria-invalid="true"], :invalid')).filter((el) => el.matches(FIELD));
629
+ const alert = Array.from(form.querySelectorAll('[role="alert"]')).some((el) => {
630
+ var _a;
631
+ return ((_a = el.textContent) != null ? _a : "").trim() !== "";
632
+ });
633
+ if (bad.length === 0 && !alert) {
634
+ this.forms.delete(form);
635
+ return;
636
+ }
637
+ const st = this.formState(form);
638
+ st.attempts++;
639
+ st.lastAttemptAt = Date.now();
640
+ this.addFields(st, bad);
641
+ });
642
+ }, CLICK_WINDOW_MS);
643
+ });
644
+ }
645
+ /** The page is being left: every form whose submit failed and never passed was abandoned. */
646
+ flushForms() {
647
+ safe(() => {
648
+ const now = Date.now();
649
+ for (const [form, st] of this.forms) {
650
+ if (st.attempts === 0) continue;
651
+ if (st.submittedAt > st.lastAttemptAt && now - st.submittedAt <= CLICK_WINDOW_MS) continue;
652
+ const element = describeForm(form);
653
+ this.pushFrustration(
654
+ { kind: "form_abandon", at: nowIso(), route: st.route, element, fields: [...st.fields.values()], attempts: Math.min(100, st.attempts) },
655
+ `form_abandon:${st.route}:${element.selector}`
656
+ );
657
+ }
658
+ this.forms.clear();
659
+ });
660
+ }
661
+ // --- thrashing and dead links --------------------------------------------
662
+ onRouteChange(route, initial) {
663
+ if (!this.frustration) return;
664
+ const now = Date.now();
665
+ this.navTrail = this.navTrail.filter((n) => now - n.at <= THRASH_WINDOW_MS).slice(-8);
666
+ this.navTrail.push({ route, at: now });
667
+ if (!initial) {
668
+ const r = this.navTrail.map((n) => n.route);
669
+ let switches = 1;
670
+ for (let i = r.length - 1; i >= 2 && r[i] === r[i - 2] && r[i] !== r[i - 1]; i--) switches++;
671
+ if (switches + 1 >= THRASH_SWITCHES) {
672
+ const pair = [r[r.length - 1], r[r.length - 2]];
673
+ const key = [...pair].sort().join("\0");
674
+ if (!this.thrashReported.has(key)) {
675
+ this.thrashReported.add(key);
676
+ this.pushFrustration({ kind: "thrash", at: nowIso(), route, routes: pair, switches: switches + 1 }, `thrash:${key}`);
677
+ }
678
+ }
679
+ }
680
+ if (initial) {
681
+ let stored = null;
682
+ try {
683
+ const raw = window.sessionStorage.getItem(LAST_LINK_KEY);
684
+ window.sessionStorage.removeItem(LAST_LINK_KEY);
685
+ stored = raw ? JSON.parse(raw) : null;
686
+ } catch {
687
+ stored = null;
688
+ }
689
+ const e = stored == null ? void 0 : stored.element;
690
+ if (stored && typeof stored.at === "number" && now - stored.at <= 5 * CLICK_WINDOW_MS && typeof stored.route === "string" && stored.route !== route && e && typeof e.selector === "string") {
691
+ const from = stored.route;
692
+ const at = stored.at;
693
+ const element = e.label ? { selector: cap(e.selector, 200), label: cap(String(e.label), 60) } : { selector: cap(e.selector, 200) };
694
+ setTimeout(() => {
695
+ safe(() => {
696
+ if (this.closed || this.unloading || currentRoute() !== route || !isNotFoundPage()) return;
697
+ this.pushFrustration(
698
+ { kind: "dead_click", at: new Date(at).toISOString(), route: from, element, reason: "not_found", to: route },
699
+ `dead:${from}:${element.selector}:not_found`
700
+ );
701
+ });
702
+ }, CLICK_WINDOW_MS);
703
+ }
704
+ return;
705
+ }
706
+ try {
707
+ window.sessionStorage.removeItem(LAST_LINK_KEY);
708
+ } catch {
709
+ }
710
+ const link = this.pendingLink;
711
+ this.pendingLink = null;
712
+ if (!initial && link && now - link.at <= 2 * CLICK_WINDOW_MS) {
713
+ setTimeout(() => {
714
+ safe(() => {
715
+ if (this.closed || this.unloading || currentRoute() !== route || !isNotFoundPage()) return;
716
+ const element = describeElement(link.el);
717
+ this.pushFrustration(
718
+ { kind: "dead_click", at: new Date(link.at).toISOString(), route: link.route, element, reason: "not_found", to: route },
719
+ `dead:${link.route}:${element.selector}:not_found`
720
+ );
721
+ });
722
+ }, CLICK_WINDOW_MS);
723
+ }
724
+ }
725
+ recordFailedRequest(method, url, status, started) {
726
+ safe(() => {
727
+ const path = requestPath(url);
728
+ const route = currentRoute();
729
+ this.push(
730
+ {
731
+ kind: "failed_request",
732
+ at: nowIso(),
733
+ route,
734
+ request: { method: cap(method.toUpperCase(), 10), path, status, durationMs: Math.max(0, Date.now() - started) }
735
+ },
736
+ `request:${method}:${path}:${status}`
737
+ );
738
+ });
739
+ }
740
+ onNavigation(initial = false) {
741
+ safe(() => {
742
+ this.activity++;
743
+ const route = currentRoute();
744
+ if (!initial && route === this.lastRoute) return;
745
+ if (!initial) this.flushForms();
746
+ this.lastRoute = route;
747
+ this.frustrationThisPage = 0;
748
+ this.push({ kind: "navigation", at: nowIso(), route });
749
+ this.onRouteChange(route, initial);
750
+ });
751
+ }
752
+ onHide() {
753
+ safe(() => {
754
+ this.activity++;
755
+ this.transport.flushOnHide();
756
+ });
757
+ }
758
+ // --- clicks --------------------------------------------------------------
759
+ onClick(ev) {
760
+ safe(() => {
761
+ var _a, _b;
762
+ const el = clickTarget(ev.target);
763
+ if (!el) return;
764
+ const now = Date.now();
765
+ const route = currentRoute();
766
+ if (!this.frustration) return;
767
+ this.lastClick = { el, at: now, route, errored: false };
768
+ if (el.matches("a[href]")) {
769
+ this.pendingLink = { el, at: now, route };
770
+ try {
771
+ window.sessionStorage.setItem(LAST_LINK_KEY, JSON.stringify({ at: now, route, element: describeElement(el) }));
772
+ } catch {
773
+ }
774
+ }
775
+ const h = (_a = this.clickHistory.get(el)) != null ? _a : { times: [], burst: 0, startedAt: now, timer: null };
776
+ h.times = h.times.filter((t) => now - t < CLICK_WINDOW_MS);
777
+ h.times.push(now);
778
+ this.clickHistory.set(el, h);
779
+ if (h.burst > 0 || h.times.length >= RAGE_CLICKS) {
780
+ if (h.burst === 0) {
781
+ h.burst = h.times.length;
782
+ h.startedAt = (_b = h.times[0]) != null ? _b : now;
783
+ } else {
784
+ h.burst += 1;
785
+ }
786
+ if (h.timer) clearTimeout(h.timer);
787
+ h.timer = setTimeout(() => {
788
+ safe(() => {
789
+ const clicks = h.burst;
790
+ const at = new Date(h.startedAt).toISOString();
791
+ h.burst = 0;
792
+ h.times = [];
793
+ h.timer = null;
794
+ const element = describeElement(el);
795
+ this.pushFrustration({ kind: "rage_click", at, route, element, clicks }, `rage:${route}:${element.selector}`);
796
+ });
797
+ }, CLICK_WINDOW_MS);
798
+ return;
799
+ }
800
+ if (!isActionable(el)) return;
801
+ const before = this.activity;
802
+ setTimeout(() => {
803
+ safe(() => {
804
+ var _a2, _b2, _c;
805
+ if (this.closed || this.unloading) return;
806
+ if (h.burst > 0) return;
807
+ if (this.activity !== before) return;
808
+ if (!el.isConnected) return;
809
+ if (el.matches('[aria-pressed="true"], [aria-selected="true"], [aria-checked="true"], [aria-current]:not([aria-current="false"])')) return;
810
+ if (this.errorClicked.has(el)) return;
811
+ const form = el.closest("form");
812
+ if (form && el.matches('button[type="submit"], button:not([type]), input[type="submit"]') && ((_b2 = (_a2 = this.forms.get(form)) == null ? void 0 : _a2.attempts) != null ? _b2 : 0) > 0) return;
813
+ const last = (_c = this.deadReportedAt.get(el)) != null ? _c : 0;
814
+ if (Date.now() - last < 5 * CLICK_WINDOW_MS) return;
815
+ this.deadReportedAt.set(el, Date.now());
816
+ const element = describeElement(el);
817
+ this.pushFrustration(
818
+ { kind: "dead_click", at: new Date(now).toISOString(), route, element },
819
+ `dead:${route}:${element.selector}`
820
+ );
821
+ });
822
+ }, CLICK_WINDOW_MS);
823
+ });
824
+ }
825
+ // --- patches -------------------------------------------------------------
826
+ listen(target, type, fn, capture = false) {
827
+ const handler = (ev) => safe(() => fn(ev));
828
+ target.addEventListener(type, handler, capture);
829
+ this.listeners.push(() => target.removeEventListener(type, handler, capture));
830
+ }
831
+ patchFetch() {
832
+ if (typeof window.fetch !== "function") return;
833
+ const original = window.fetch;
834
+ const self = this;
835
+ const wrapped = function(input, init2) {
836
+ var _a;
837
+ let method = "GET";
838
+ let url = "";
839
+ try {
840
+ method = String((_a = init2 == null ? void 0 : init2.method) != null ? _a : typeof Request !== "undefined" && input instanceof Request ? input.method : "GET");
841
+ url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
842
+ } catch {
843
+ }
844
+ const own = isEndpoint(url, self.endpoint);
845
+ if (!own) self.activity++;
846
+ const started = Date.now();
847
+ const result = original.apply(this != null ? this : window, arguments);
848
+ if (own) return result;
849
+ return result.then(
850
+ (res) => {
851
+ safe(() => {
852
+ if (res && res.status >= 500) self.recordFailedRequest(method, url, res.status, started);
853
+ });
854
+ return res;
855
+ },
856
+ (err) => {
857
+ safe(() => {
858
+ if (!(err && err.name === "AbortError")) {
859
+ self.recordFailedRequest(method, url, null, started);
860
+ }
861
+ });
862
+ throw err;
863
+ }
864
+ );
865
+ };
866
+ window.fetch = wrapped;
867
+ this.patches.push({
868
+ restore: () => {
869
+ if (window.fetch === wrapped) window.fetch = original;
870
+ }
871
+ });
872
+ }
873
+ patchXhr() {
874
+ if (typeof XMLHttpRequest === "undefined") return;
875
+ const proto = XMLHttpRequest.prototype;
876
+ const originalOpen = proto.open;
877
+ const originalSend = proto.send;
878
+ const info = /* @__PURE__ */ new WeakMap();
879
+ const self = this;
880
+ proto.open = function(method, url) {
881
+ safe(() => info.set(this, { method: String(method), url: String(url) }));
882
+ return originalOpen.apply(this, arguments);
883
+ };
884
+ proto.send = function() {
885
+ safe(() => {
886
+ const req = info.get(this);
887
+ if (!req || isEndpoint(req.url, self.endpoint)) return;
888
+ self.activity++;
889
+ const started = Date.now();
890
+ let aborted = false;
891
+ this.addEventListener("abort", () => {
892
+ aborted = true;
893
+ });
894
+ this.addEventListener("loadend", () => {
895
+ safe(() => {
896
+ if (aborted) return;
897
+ if (this.status === 0) self.recordFailedRequest(req.method, req.url, null, started);
898
+ else if (this.status >= 500) self.recordFailedRequest(req.method, req.url, this.status, started);
899
+ });
900
+ });
901
+ });
902
+ return originalSend.apply(this, arguments);
903
+ };
904
+ this.patches.push({
905
+ restore: () => {
906
+ proto.open = originalOpen;
907
+ proto.send = originalSend;
908
+ }
909
+ });
910
+ }
911
+ patchHistory() {
912
+ const h = window.history;
913
+ if (!h) return;
914
+ for (const name of ["pushState", "replaceState"]) {
915
+ const original = h[name];
916
+ if (typeof original !== "function") continue;
917
+ const self = this;
918
+ const wrapped = function(...args) {
919
+ const out = original.apply(this, args);
920
+ self.onNavigation();
921
+ return out;
922
+ };
923
+ h[name] = wrapped;
924
+ this.patches.push({
925
+ restore: () => {
926
+ if (h[name] === wrapped) h[name] = original;
927
+ }
928
+ });
929
+ }
930
+ }
931
+ };
932
+
933
+ // src/browser/index.ts
934
+ var recorder = null;
935
+ function inBrowser() {
936
+ return typeof window !== "undefined" && typeof document !== "undefined";
937
+ }
938
+ function init(config) {
939
+ var _a;
940
+ try {
941
+ if (!inBrowser() || recorder) return;
942
+ if (!config || typeof config.key !== "string" || config.key.trim() === "") return;
943
+ const { sessionId, sampled } = sessionFor((_a = config.sampleRate) != null ? _a : 1);
944
+ if (!sampled) return;
945
+ recorder = new SessionRecorder({ ...config, key: config.key.trim() }, sessionId);
946
+ recorder.install();
947
+ } catch {
948
+ recorder = null;
949
+ }
950
+ }
951
+ function setUser(user) {
952
+ try {
953
+ recorder == null ? void 0 : recorder.setUser(user);
954
+ } catch {
955
+ }
956
+ }
957
+ function captureError(err) {
958
+ try {
959
+ recorder == null ? void 0 : recorder.captureError(err);
960
+ } catch {
961
+ }
962
+ }
963
+ function flush() {
964
+ try {
965
+ return recorder ? recorder.flush().catch(() => {
966
+ }) : Promise.resolve();
967
+ } catch {
968
+ return Promise.resolve();
969
+ }
970
+ }
971
+ function close() {
972
+ try {
973
+ recorder == null ? void 0 : recorder.close();
974
+ } catch {
975
+ } finally {
976
+ recorder = null;
977
+ }
978
+ }
979
+ function getSessionId() {
980
+ var _a;
981
+ return (_a = recorder == null ? void 0 : recorder.sessionId) != null ? _a : null;
982
+ }
983
+
984
+ exports.DEFAULT_ENDPOINT = DEFAULT_ENDPOINT;
985
+ exports.captureError = captureError;
986
+ exports.close = close;
987
+ exports.flush = flush;
988
+ exports.getSessionId = getSessionId;
989
+ exports.init = init;
990
+ exports.setUser = setUser;
991
+ //# sourceMappingURL=index.js.map
992
+ //# sourceMappingURL=index.js.map