@tracelog/lib 2.9.0-rc.107.4 → 2.9.0-rc.108.13

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.
@@ -1,6 +1,6 @@
1
- const fr = 9e5;
2
- const mr = 120, gr = 49152, pr = 100, Er = 500, Sr = 200;
3
- const Tr = 1e3, Ir = 500, _r = 1e3;
1
+ const gr = 9e5;
2
+ const pr = 120, Er = 49152, Sr = 100, Tr = 500, vr = 200;
3
+ const Ir = 1e3, _r = 500, yr = 1e3;
4
4
  const b = "data-tlog", bt = [
5
5
  "button",
6
6
  "a",
@@ -79,7 +79,7 @@ const S = {
79
79
  /<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
80
80
  /<embed\b[^>]*>/gi,
81
81
  /<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi
82
- ], I = "tlog", G = `${I}:qa_mode`, Ie = `${I}:uid`, rt = "tlog_mode", Ue = "qa", Fe = "qa_off", Ct = (r) => r ? `${I}:${r}:queue` : `${I}:queue`, Rt = (r) => r ? `${I}:${r}:rate_limit` : `${I}:rate_limit`, Nt = (r) => r ? `${I}:${r}:session` : `${I}:session`, Ot = (r) => r ? `${I}:${r}:broadcast` : `${I}:broadcast`, He = (r, e) => `${I}:${r}:session_counts:${e}`, xe = 10080 * 60 * 1e3, $e = `${I}:session_counts_last_cleanup`, Be = 3600 * 1e3, me = (r) => r ? `${I}:${r}:identity` : `${I}:identity`, F = `${I}:pending_identity`;
82
+ ], I = "tlog", G = `${I}:qa_mode`, ve = `${I}:uid`, rt = "tlog_mode", Ue = "qa", He = "qa_off", Ct = (r) => r ? `${I}:${r}:queue` : `${I}:queue`, Rt = (r) => r ? `${I}:${r}:rate_limit` : `${I}:rate_limit`, Nt = (r) => r ? `${I}:${r}:session` : `${I}:session`, Ot = (r) => r ? `${I}:${r}:broadcast` : `${I}:broadcast`, Fe = (r, e) => `${I}:${r}:session_counts:${e}`, xe = 10080 * 60 * 1e3, $e = `${I}:session_counts_last_cleanup`, Be = 3600 * 1e3, me = (r) => r ? `${I}:${r}:identity` : `${I}:identity`, H = `${I}:pending_identity`;
83
83
  var $ = /* @__PURE__ */ ((r) => (r.Localhost = "localhost:8080", r.Fail = "localhost:9999", r))($ || {}), A = /* @__PURE__ */ ((r) => (r.Mobile = "mobile", r.Tablet = "tablet", r.Desktop = "desktop", r.Unknown = "unknown", r))(A || {}), se = /* @__PURE__ */ ((r) => (r.EVENT = "event", r.QUEUE = "queue", r))(se || {});
84
84
  class O extends Error {
85
85
  constructor(e, t, s) {
@@ -99,7 +99,7 @@ class ne extends Error {
99
99
  }
100
100
  }
101
101
  var u = /* @__PURE__ */ ((r) => (r.PAGE_VIEW = "page_view", r.CLICK = "click", r.SCROLL = "scroll", r.SESSION_START = "session_start", r.CUSTOM = "custom", r.WEB_VITALS = "web_vitals", r.ERROR = "error", r.VIEWPORT_VISIBLE = "viewport_visible", r))(u || {}), Z = /* @__PURE__ */ ((r) => (r.UP = "up", r.DOWN = "down", r))(Z || {}), B = /* @__PURE__ */ ((r) => (r.JS_ERROR = "js_error", r.PROMISE_REJECTION = "promise_rejection", r))(B || {}), ie = /* @__PURE__ */ ((r) => (r.QA = "qa", r))(ie || {});
102
- const vr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !0, yr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !1;
102
+ const wr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !0, br = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !1;
103
103
  class j extends Error {
104
104
  constructor(e, t, s) {
105
105
  super(e), this.errorCode = t, this.layer = s, this.name = this.constructor.name, Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
@@ -127,7 +127,7 @@ class N extends j {
127
127
  super(e, "INTEGRATION_INVALID", t);
128
128
  }
129
129
  }
130
- class wr extends j {
130
+ class Lr extends j {
131
131
  constructor(e, t, s = "runtime") {
132
132
  super(e, "INITIALIZATION_TIMEOUT", s), this.timeoutMs = t;
133
133
  }
@@ -164,12 +164,12 @@ const nt = "background: #ff9800; color: white; font-weight: bold; padding: 2px 8
164
164
  const { error: s, data: n, showToClient: i = !1, style: o, visibility: l } = t ?? {}, d = s ? kt(e, s) : `[TraceLog] ${e}`, c = r === "error" ? "error" : r === "warn" ? "warn" : "log";
165
165
  if (!Ut(l, i))
166
166
  return;
167
- const g = Ft(l, o), m = n !== void 0 ? _e(n) : void 0;
168
- Ht(c, d, g, m);
169
- }, Ut = (r, e) => r === "critical" ? !0 : r === "qa" || e ? Vt() : !1, Ft = (r, e) => e !== void 0 && e !== "" ? e : r === "critical" ? Dt : "", Ht = (r, e, t, s) => {
167
+ const m = Ht(l, o), g = n !== void 0 ? Ie(n) : void 0;
168
+ Ft(c, d, m, g);
169
+ }, Ut = (r, e) => r === "critical" ? !0 : r === "qa" || e ? Vt() : !1, Ht = (r, e) => e !== void 0 && e !== "" ? e : r === "critical" ? Dt : "", Ft = (r, e, t, s) => {
170
170
  const n = t !== void 0 && t !== "", i = n ? `%c${e}` : e;
171
171
  s !== void 0 ? n ? console[r](i, t, s) : console[r](i, s) : n ? console[r](i, t) : console[r](i);
172
- }, _e = (r) => {
172
+ }, Ie = (r) => {
173
173
  const e = {}, t = ["token", "password", "secret", "key", "apikey", "api_key", "sessionid", "session_id"];
174
174
  for (const [s, n] of Object.entries(r)) {
175
175
  const i = s.toLowerCase();
@@ -177,15 +177,15 @@ const nt = "background: #ff9800; color: white; font-weight: bold; padding: 2px 8
177
177
  e[s] = "[REDACTED]";
178
178
  continue;
179
179
  }
180
- n !== null && typeof n == "object" && !Array.isArray(n) ? e[s] = _e(n) : Array.isArray(n) ? e[s] = n.map(
181
- (o) => o !== null && typeof o == "object" && !Array.isArray(o) ? _e(o) : o
180
+ n !== null && typeof n == "object" && !Array.isArray(n) ? e[s] = Ie(n) : Array.isArray(n) ? e[s] = n.map(
181
+ (o) => o !== null && typeof o == "object" && !Array.isArray(o) ? Ie(o) : o
182
182
  ) : e[s] = n;
183
183
  }
184
184
  return e;
185
185
  };
186
- let ve, ot;
186
+ let _e, ot;
187
187
  const xt = () => {
188
- typeof window < "u" && !ve && (ve = window.matchMedia("(pointer: coarse)"), ot = window.matchMedia("(hover: none)"));
188
+ typeof window < "u" && !_e && (_e = window.matchMedia("(pointer: coarse)"), ot = window.matchMedia("(hover: none)"));
189
189
  }, oe = "Unknown", $t = (r) => {
190
190
  const e = r.userAgentData?.platform;
191
191
  if (e != null && e !== "") {
@@ -217,7 +217,7 @@ const xt = () => {
217
217
  return d != null && d !== "" && /ipad|tablet/i.test(d) ? A.Tablet : r.userAgentData.mobile ? A.Mobile : A.Desktop;
218
218
  }
219
219
  xt();
220
- const e = window.innerWidth, t = ve?.matches ?? !1, s = ot?.matches ?? !1, n = "ontouchstart" in window || navigator.maxTouchPoints > 0, i = navigator.userAgent.toLowerCase(), o = /mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(i), l = /tablet|ipad|android(?!.*mobile)/.test(i);
220
+ const e = window.innerWidth, t = _e?.matches ?? !1, s = ot?.matches ?? !1, n = "ontouchstart" in window || navigator.maxTouchPoints > 0, i = navigator.userAgent.toLowerCase(), o = /mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(i), l = /tablet|ipad|android(?!.*mobile)/.test(i);
221
221
  return e <= 767 || o && n ? A.Mobile : e >= 768 && e <= 1024 || l || t && s && n ? A.Tablet : A.Desktop;
222
222
  } catch (r) {
223
223
  return a("debug", "Device detection failed, defaulting to desktop", { error: r }), A.Desktop;
@@ -254,7 +254,7 @@ const xt = () => {
254
254
  /:\/\/[^:/]+:([^@]+)@/gi,
255
255
  // Sensitive URL query parameters (token=, password=, auth=, secret=, api_key=, etc.)
256
256
  /[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi
257
- ], Ge = 500, Xe = 2e3, je = 5e3, ee = 50, Xt = ee * 2, lt = 1, jt = 1e3, Kt = 10, Ke = 5e3, zt = 6e4, Qt = 64, br = {
257
+ ], Ge = 500, Xe = 2e3, je = 5e3, ee = 50, Xt = ee * 2, lt = 1, jt = 1e3, Kt = 10, Ke = 5e3, Qt = 6e4, zt = 64, Ar = {
258
258
  LCP: 2500,
259
259
  // Good: ≤ 2.5s
260
260
  FCP: 1800,
@@ -266,7 +266,7 @@ const xt = () => {
266
266
  TTFB: 800,
267
267
  // Good: ≤ 800ms
268
268
  LONG_TASK: 50
269
- }, ze = {
269
+ }, Qe = {
270
270
  LCP: 2500,
271
271
  // Needs improvement: > 2.5s (same as good boundary)
272
272
  FCP: 1800,
@@ -290,17 +290,17 @@ const xt = () => {
290
290
  TTFB: 1800,
291
291
  // Poor: > 1800ms
292
292
  LONG_TASK: 50
293
- }, ye = "needs-improvement", Qe = (r = ye) => {
293
+ }, ye = "needs-improvement", ze = (r = ye) => {
294
294
  switch (r) {
295
295
  case "all":
296
296
  return { LCP: 0, FCP: 0, CLS: 0, INP: 0, TTFB: 0, LONG_TASK: 0 };
297
297
  // Track everything
298
298
  case "needs-improvement":
299
- return ze;
299
+ return Qe;
300
300
  case "poor":
301
301
  return Yt;
302
302
  default:
303
- return ze;
303
+ return Qe;
304
304
  }
305
305
  }, qt = 1e3, Jt = 50, Zt = "2.9.0", es = Zt, ct = () => typeof window < "u" && typeof sessionStorage < "u", ts = () => {
306
306
  try {
@@ -319,10 +319,10 @@ const xt = () => {
319
319
  return e === Ue ? (s = !0, sessionStorage.setItem(G, "true"), a("info", "QA Mode ACTIVE", {
320
320
  visibility: "qa",
321
321
  style: nt
322
- })) : e === Fe && (s = !1, sessionStorage.setItem(G, "false"), a("info", "QA Mode DISABLED", {
322
+ })) : e === He && (s = !1, sessionStorage.setItem(G, "false"), a("info", "QA Mode DISABLED", {
323
323
  visibility: "qa",
324
324
  style: it
325
- })), (e === Ue || e === Fe) && ts(), s ?? t === "true";
325
+ })), (e === Ue || e === He) && ts(), s ?? t === "true";
326
326
  } catch {
327
327
  return !1;
328
328
  }
@@ -537,6 +537,16 @@ const os = () => {
537
537
  throw new p(S.INVALID_MAX_SAME_EVENT_PER_MINUTE, "config");
538
538
  if (r.sendIntervalMs !== void 0 && (!Number.isFinite(r.sendIntervalMs) || r.sendIntervalMs < 1e3 || r.sendIntervalMs > 6e4))
539
539
  throw new p(S.INVALID_SEND_INTERVAL, "config");
540
+ if (r.flushOnSpaNavigation !== void 0 && typeof r.flushOnSpaNavigation != "boolean")
541
+ throw new p(
542
+ `Invalid flushOnSpaNavigation type: ${typeof r.flushOnSpaNavigation}. Must be a boolean`,
543
+ "config"
544
+ );
545
+ if (r.flushOnPageHidden !== void 0 && typeof r.flushOnPageHidden != "boolean")
546
+ throw new p(
547
+ `Invalid flushOnPageHidden type: ${typeof r.flushOnPageHidden}. Must be a boolean`,
548
+ "config"
549
+ );
540
550
  if (r.viewport !== void 0 && us(r.viewport), r.webVitalsMode !== void 0) {
541
551
  if (typeof r.webVitalsMode != "string")
542
552
  throw new p(
@@ -633,7 +643,9 @@ const os = () => {
633
643
  pageViewThrottleMs: r?.pageViewThrottleMs ?? 1e3,
634
644
  clickThrottleMs: r?.clickThrottleMs ?? 300,
635
645
  maxSameEventPerMinute: r?.maxSameEventPerMinute ?? 60,
636
- sendIntervalMs: r?.sendIntervalMs ?? 1e4
646
+ sendIntervalMs: r?.sendIntervalMs ?? 1e4,
647
+ flushOnSpaNavigation: r?.flushOnSpaNavigation ?? !0,
648
+ flushOnPageHidden: r?.flushOnPageHidden ?? !0
637
649
  };
638
650
  return e.integrations?.custom && (e.integrations.custom = {
639
651
  ...e.integrations.custom,
@@ -909,7 +921,7 @@ function gt(r, e, t) {
909
921
  }
910
922
  }
911
923
  const Ee = { config: {} };
912
- class v {
924
+ class _ {
913
925
  /**
914
926
  * Retrieves a value from global state.
915
927
  *
@@ -967,7 +979,7 @@ class v {
967
979
  return { ...Ee };
968
980
  }
969
981
  }
970
- class Ze extends v {
982
+ class Ze extends _ {
971
983
  storeManager;
972
984
  integrationId;
973
985
  apiUrl;
@@ -1524,7 +1536,7 @@ class Ze extends v {
1524
1536
  }
1525
1537
  ), this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, !0) : !1;
1526
1538
  } catch (f) {
1527
- const g = c === 3;
1539
+ const m = c === 3;
1528
1540
  if (f instanceof O)
1529
1541
  throw this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, f;
1530
1542
  if (f instanceof re) {
@@ -1534,8 +1546,8 @@ class Ze extends v {
1534
1546
  break;
1535
1547
  }
1536
1548
  if (f instanceof ne || (l = !1), f instanceof TypeError || (d = !0), a(
1537
- g ? "error" : "warn",
1538
- `Send attempt ${c} failed${this.integrationId ? ` [${this.integrationId}]` : ""}${g ? " (all retries exhausted)" : ", will retry"}`,
1549
+ m ? "error" : "warn",
1550
+ `Send attempt ${c} failed${this.integrationId ? ` [${this.integrationId}]` : ""}${m ? " (all retries exhausted)" : ", will retry"}`,
1539
1551
  {
1540
1552
  error: f,
1541
1553
  data: {
@@ -1545,7 +1557,7 @@ class Ze extends v {
1545
1557
  maxAttempts: 3
1546
1558
  }
1547
1559
  }
1548
- ), !g) {
1560
+ ), !m) {
1549
1561
  await this.backoffDelay(c);
1550
1562
  continue;
1551
1563
  }
@@ -1633,7 +1645,7 @@ class Ze extends v {
1633
1645
  async readTraceLogErrorCode(e) {
1634
1646
  try {
1635
1647
  const t = await e.clone().json();
1636
- if (typeof t.code == "string" && t.code.length > 0 && t.code.length <= Qt)
1648
+ if (typeof t.code == "string" && t.code.length > 0 && t.code.length <= zt)
1637
1649
  return t.code;
1638
1650
  } catch {
1639
1651
  }
@@ -1894,12 +1906,12 @@ class Ze extends v {
1894
1906
  }
1895
1907
  logPermanentError(e, t) {
1896
1908
  const s = Date.now(), n = `${t.statusCode ?? "unknown"}:${t.responseCode ?? ""}`;
1897
- (!this.lastPermanentErrorLog || this.lastPermanentErrorLog.key !== n || s - this.lastPermanentErrorLog.timestamp >= zt) && (a("error", `${e}${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1909
+ (!this.lastPermanentErrorLog || this.lastPermanentErrorLog.key !== n || s - this.lastPermanentErrorLog.timestamp >= Qt) && (a("error", `${e}${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1898
1910
  data: { status: t.statusCode, code: t.responseCode, message: t.message }
1899
1911
  }), this.lastPermanentErrorLog = { key: n, timestamp: s });
1900
1912
  }
1901
1913
  }
1902
- class Ts extends v {
1914
+ class Ts extends _ {
1903
1915
  bootTime;
1904
1916
  bootTimestamp;
1905
1917
  hasPerformanceNow;
@@ -2048,8 +2060,8 @@ class Ts extends v {
2048
2060
  };
2049
2061
  }
2050
2062
  }
2051
- const Is = new Set(Object.values(u));
2052
- class _s extends v {
2063
+ const vs = new Set(Object.values(u));
2064
+ class Is extends _ {
2053
2065
  dataSenders;
2054
2066
  emitter;
2055
2067
  transformers;
@@ -2064,6 +2076,9 @@ class _s extends v {
2064
2076
  rateLimitCounter = 0;
2065
2077
  rateLimitWindowStart = 0;
2066
2078
  lastSessionId = null;
2079
+ // Set when a sync flush is requested mid-async-send; drained by the async
2080
+ // finally block. See `drainPendingSyncFlush` for the full rationale.
2081
+ pendingSyncFlush = !1;
2067
2082
  sessionEventCounts = {
2068
2083
  total: 0,
2069
2084
  [u.CLICK]: 0,
@@ -2219,14 +2234,14 @@ class _s extends v {
2219
2234
  a("error", "Event type is required - event will be ignored");
2220
2235
  return;
2221
2236
  }
2222
- if (!Is.has(e)) {
2237
+ if (!vs.has(e)) {
2223
2238
  a("error", "Invalid event type - event will be ignored", {
2224
2239
  data: { type: e }
2225
2240
  });
2226
2241
  return;
2227
2242
  }
2228
- const g = this.get("sessionId");
2229
- if (!g) {
2243
+ const m = this.get("sessionId");
2244
+ if (!m) {
2230
2245
  this.pendingEventsBuffer.length >= 100 && (this.pendingEventsBuffer.shift(), a("debug", "Pending events buffer full - dropping oldest event", {
2231
2246
  data: { maxBufferSize: 100 }
2232
2247
  })), this.pendingEventsBuffer.push({
@@ -2243,14 +2258,14 @@ class _s extends v {
2243
2258
  });
2244
2259
  return;
2245
2260
  }
2246
- this.lastSessionId !== g && (this.lastSessionId = g, this.sessionEventCounts = this.loadSessionCounts(g));
2247
- const m = e === u.SESSION_START;
2248
- if (m && a("debug", "Processing SESSION_START event", {
2249
- data: { sessionId: g }
2250
- }), !m && !this.checkRateLimit())
2261
+ this.lastSessionId !== m && (this.lastSessionId = m, this.sessionEventCounts = this.loadSessionCounts(m));
2262
+ const g = e === u.SESSION_START;
2263
+ if (g && a("debug", "Processing SESSION_START event", {
2264
+ data: { sessionId: m }
2265
+ }), !g && !this.checkRateLimit())
2251
2266
  return;
2252
2267
  const E = e;
2253
- if (!m) {
2268
+ if (!g) {
2254
2269
  if (this.sessionEventCounts.total >= 1e3) {
2255
2270
  a("warn", "Session event limit reached", {
2256
2271
  data: {
@@ -2261,15 +2276,15 @@ class _s extends v {
2261
2276
  });
2262
2277
  return;
2263
2278
  }
2264
- const T = this.getTypeLimitForEvent(E);
2265
- if (T) {
2279
+ const v = this.getTypeLimitForEvent(E);
2280
+ if (v) {
2266
2281
  const fe = this.sessionEventCounts[E];
2267
- if (fe !== void 0 && fe >= T) {
2282
+ if (fe !== void 0 && fe >= v) {
2268
2283
  a("warn", "Session event type limit reached", {
2269
2284
  data: {
2270
2285
  type: E,
2271
2286
  count: fe,
2272
- limit: T
2287
+ limit: v
2273
2288
  }
2274
2289
  });
2275
2290
  return;
@@ -2277,13 +2292,13 @@ class _s extends v {
2277
2292
  }
2278
2293
  }
2279
2294
  if (E === u.CUSTOM && o?.name) {
2280
- const T = this.get("config")?.maxSameEventPerMinute ?? 60;
2281
- if (!this.checkPerEventRateLimit(o.name, T))
2295
+ const v = this.get("config")?.maxSameEventPerMinute ?? 60;
2296
+ if (!this.checkPerEventRateLimit(o.name, v))
2282
2297
  return;
2283
2298
  }
2284
- const he = E === u.SESSION_START, Q = t || this.get("pageUrl"), U = this.buildEventPayload({
2299
+ const he = E === u.SESSION_START, z = t || this.get("pageUrl"), U = this.buildEventPayload({
2285
2300
  type: E,
2286
- page_url: Q,
2301
+ page_url: z,
2287
2302
  from_page_url: s,
2288
2303
  scroll_data: n,
2289
2304
  click_data: i,
@@ -2293,16 +2308,16 @@ class _s extends v {
2293
2308
  viewport_data: c,
2294
2309
  page_view: f
2295
2310
  });
2296
- if (U && !(!m && !this.shouldSample())) {
2311
+ if (U && !(!g && !this.shouldSample())) {
2297
2312
  if (he) {
2298
- const T = this.get("sessionId");
2299
- if (!T) {
2313
+ const v = this.get("sessionId");
2314
+ if (!v) {
2300
2315
  a("error", "Session start event requires sessionId - event will be ignored");
2301
2316
  return;
2302
2317
  }
2303
2318
  if (this.get("hasStartSession")) {
2304
2319
  a("debug", "Duplicate session_start detected", {
2305
- data: { sessionId: T }
2320
+ data: { sessionId: v }
2306
2321
  });
2307
2322
  return;
2308
2323
  }
@@ -2321,8 +2336,8 @@ class _s extends v {
2321
2336
  return;
2322
2337
  }
2323
2338
  if (E === u.VIEWPORT_VISIBLE && c) {
2324
- const T = c.name || c.id || c.selector;
2325
- a("info", `Viewport Visible: ${T}`, {
2339
+ const v = c.name || c.id || c.selector;
2340
+ a("info", `Viewport Visible: ${v}`, {
2326
2341
  visibility: "qa",
2327
2342
  data: {
2328
2343
  selector: c.selector,
@@ -2335,10 +2350,10 @@ class _s extends v {
2335
2350
  return;
2336
2351
  }
2337
2352
  }
2338
- if (this.addToQueue(U), !m) {
2353
+ if (this.addToQueue(U), !g) {
2339
2354
  this.sessionEventCounts.total++, this.sessionEventCounts[E] !== void 0 && this.sessionEventCounts[E]++;
2340
- const T = this.get("sessionId");
2341
- T && this.saveSessionCountsDebounced && this.saveSessionCountsDebounced(T);
2355
+ const v = this.get("sessionId");
2356
+ v && this.saveSessionCountsDebounced && this.saveSessionCountsDebounced(v);
2342
2357
  }
2343
2358
  }
2344
2359
  }
@@ -2378,7 +2393,7 @@ class _s extends v {
2378
2393
  * @see src/managers/README.md (lines 5-75) for cleanup details
2379
2394
  */
2380
2395
  stop() {
2381
- this.clearSendTimeout(), this.sendInProgress = !1, this.consecutiveSendFailures = 0;
2396
+ this.clearSendTimeout(), this.sendInProgress = !1, this.pendingSyncFlush = !1, this.consecutiveSendFailures = 0;
2382
2397
  const e = this.get("sessionId");
2383
2398
  e && this.saveSessionCounts(e), this.eventsQueue = [], this.pendingEventsBuffer = [], this.recentEventFingerprints.clear(), this.rateLimitCounter = 0, this.rateLimitWindowStart = 0, this.perEventRateLimits.clear(), this.sessionEventCounts = {
2384
2399
  total: 0,
@@ -2465,6 +2480,62 @@ class _s extends v {
2465
2480
  flushImmediatelySync() {
2466
2481
  return this.flushEvents(!0);
2467
2482
  }
2483
+ /**
2484
+ * Sends ONLY the most recently queued event via `navigator.sendBeacon()` in
2485
+ * a dedicated single-event batch.
2486
+ *
2487
+ * **Purpose**: Guarantee delivery of an event that *must* survive an
2488
+ * imminent page unload (purchase confirmation, signup completion, etc.),
2489
+ * independent of the main queue's size or in-flight async send state.
2490
+ *
2491
+ * **Why a dedicated batch**: `flushImmediatelySync()` serialises the entire
2492
+ * queue into one `sendBeacon` call. If the queue is heavy (>64KB) the
2493
+ * beacon fails and the batch is persisted to `localStorage`, which is only
2494
+ * recovered on the next `init()` — useless for one-shot conversion events
2495
+ * where the user never returns.
2496
+ *
2497
+ * **Behaviour**:
2498
+ * - Reads the last entry of `eventsQueue` (the just-tracked event).
2499
+ * - Wraps it in its own `EventsQueue` and dispatches synchronously through
2500
+ * every `SenderManager` via `sendEventsQueueSync()`.
2501
+ * - Leaves the main queue untouched; the same event will be re-delivered by
2502
+ * the next periodic / unload flush. Idempotency is the caller-side
2503
+ * contract: the backend MUST deduplicate by `event.id` (e.g. unique index
2504
+ * on the ingestion collection) — same guarantee the library already
2505
+ * relies on for the persisted-events recovery path.
2506
+ *
2507
+ * **Use it after** `track()` so the event is in the queue. Caller is
2508
+ * responsible for verifying that `track()` actually queued the event
2509
+ * (it can be dropped by rate limiting / sampling / `beforeSend`).
2510
+ *
2511
+ * **Standalone mode** (no senders configured): returns `false` without
2512
+ * emitting. The subsequent main-queue drain (`flushImmediatelySync()`) is
2513
+ * responsible for delivering the event to local listeners — emitting here
2514
+ * too would surface the same event twice to a `tracelog.on('queue', ...)`
2515
+ * subscriber.
2516
+ *
2517
+ * @returns `true` if at least one sender delivered the beacon successfully,
2518
+ * `false` otherwise (including standalone mode — the drain handles it).
2519
+ */
2520
+ flushLastEventSync() {
2521
+ if (this.dataSenders.length === 0)
2522
+ return !1;
2523
+ const e = this.eventsQueue[this.eventsQueue.length - 1];
2524
+ if (!e)
2525
+ return !1;
2526
+ const { _session_id: t, ...s } = e;
2527
+ if (!t)
2528
+ return a("debug", "flushLastEventSync: last queued event missing _session_id, skipping"), !1;
2529
+ const n = this.get("config")?.globalMetadata, i = this.get("identity"), o = {
2530
+ user_id: this.get("userId"),
2531
+ session_id: t,
2532
+ device: this.get("device"),
2533
+ events: [s],
2534
+ ...n && { global_metadata: n },
2535
+ ...i && { identify: i }
2536
+ };
2537
+ return this.dataSenders.map((d) => d.sendEventsQueueSync(o)).some(Boolean);
2538
+ }
2468
2539
  /**
2469
2540
  * Sets the custom headers provider callback for the custom integration.
2470
2541
  * Only affects requests to custom backend (not TraceLog SaaS).
@@ -2654,7 +2725,7 @@ class _s extends v {
2654
2725
  }
2655
2726
  if (e && this.sendInProgress) {
2656
2727
  const s = t.reduce((n, i) => n + i.eventIds.length, 0);
2657
- return a("debug", "Sync flush skipped: async send already in-flight, trusting fetch to deliver", {
2728
+ return this.pendingSyncFlush = !0, a("debug", "Sync flush deferred: async send in-flight, will retry on settle", {
2658
2729
  data: { eventCount: s }
2659
2730
  }), !0;
2660
2731
  }
@@ -2662,13 +2733,29 @@ class _s extends v {
2662
2733
  const s = t.map(({ batch: n, eventIds: i }) => this.sendBatchSync(n, i));
2663
2734
  return this.clearSendTimeout(), s.some(Boolean);
2664
2735
  }
2665
- return (async () => {
2666
- const s = await Promise.all(
2667
- t.map(async ({ batch: n, eventIds: i }) => this.sendBatchAsync(n, i))
2668
- );
2669
- return this.clearSendTimeout(), s.some(Boolean);
2736
+ return this.sendInProgress = !0, (async () => {
2737
+ try {
2738
+ const s = await Promise.all(
2739
+ t.map(async ({ batch: n, eventIds: i }) => this.sendBatchAsync(n, i))
2740
+ );
2741
+ return this.clearSendTimeout(), s.some(Boolean);
2742
+ } finally {
2743
+ this.sendInProgress = !1, this.drainPendingSyncFlush();
2744
+ }
2670
2745
  })();
2671
2746
  }
2747
+ /**
2748
+ * Re-runs a sync flush that was deferred while an async send was in flight.
2749
+ *
2750
+ * Called from the `finally` blocks of `flushEvents(false)` and
2751
+ * `sendEventsQueue()`. If `pendingSyncFlush` is set, clears the flag and
2752
+ * invokes `flushImmediatelySync()` synchronously so any events that arrived
2753
+ * after the deferred sync call are delivered before the next event loop
2754
+ * tick. Critical for high-stakes events tracked mid-async-send.
2755
+ */
2756
+ drainPendingSyncFlush() {
2757
+ this.pendingSyncFlush && (this.pendingSyncFlush = !1, this.flushImmediatelySync());
2758
+ }
2672
2759
  /**
2673
2760
  * Sends one batch synchronously across all integrations (sendBeacon path).
2674
2761
  * Optimistic removal: if any integration succeeds, we remove the batch's
@@ -2719,7 +2806,7 @@ class _s extends v {
2719
2806
  e.map(async ({ batch: n, eventIds: i }) => this.sendBatchAsync(n, i))
2720
2807
  )).some(Boolean) ? this.consecutiveSendFailures = 0 : this.consecutiveSendFailures = Math.min(this.consecutiveSendFailures + 1, 5), this.eventsQueue.length === 0 ? this.clearSendTimeout() : this.scheduleSendTimeout();
2721
2808
  } finally {
2722
- this.sendInProgress = !1;
2809
+ this.sendInProgress = !1, this.drainPendingSyncFlush();
2723
2810
  }
2724
2811
  }
2725
2812
  }
@@ -2744,11 +2831,11 @@ class _s extends v {
2744
2831
  */
2745
2832
  buildBatchFromGroup(e, t) {
2746
2833
  const s = /* @__PURE__ */ new Map(), n = [];
2747
- for (const m of t) {
2748
- const E = this.createEventSignature(m);
2749
- s.has(E) || n.push(E), s.set(E, m);
2834
+ for (const g of t) {
2835
+ const E = this.createEventSignature(g);
2836
+ s.has(E) || n.push(E), s.set(E, g);
2750
2837
  }
2751
- const i = n.map((m) => s.get(m)).filter((m) => !!m).sort((m, E) => m.type === u.SESSION_START && E.type !== u.SESSION_START ? -1 : E.type === u.SESSION_START && m.type !== u.SESSION_START ? 1 : m.timestamp - E.timestamp).map(({ _session_id: m, ...E }) => E), o = this.get("config")?.globalMetadata, l = this.get("identity");
2838
+ const i = n.map((g) => s.get(g)).filter((g) => !!g).sort((g, E) => g.type === u.SESSION_START && E.type !== u.SESSION_START ? -1 : E.type === u.SESSION_START && g.type !== u.SESSION_START ? 1 : g.timestamp - E.timestamp).map(({ _session_id: g, ...E }) => E), o = this.get("config")?.globalMetadata, l = this.get("identity");
2752
2839
  let d = {
2753
2840
  user_id: this.get("userId"),
2754
2841
  session_id: e,
@@ -2757,10 +2844,10 @@ class _s extends v {
2757
2844
  ...o && { global_metadata: o },
2758
2845
  ...l && { identify: l }
2759
2846
  };
2760
- const c = this.get("collectApiUrls"), f = !!(c?.custom || c?.saas), g = this.transformers.beforeBatch;
2761
- if (!f && g) {
2762
- const m = gt(d, g, "EventManager");
2763
- m !== null && (d = m);
2847
+ const c = this.get("collectApiUrls"), f = !!(c?.custom || c?.saas), m = this.transformers.beforeBatch;
2848
+ if (!f && m) {
2849
+ const g = gt(d, m, "EventManager");
2850
+ g !== null && (d = g);
2764
2851
  }
2765
2852
  return d;
2766
2853
  }
@@ -2792,12 +2879,12 @@ class _s extends v {
2792
2879
  ...e.page_view && { page_view: e.page_view },
2793
2880
  ...d && { utm: d }
2794
2881
  };
2795
- const f = this.get("collectApiUrls"), g = !!f?.custom, m = !!f?.saas, E = g || m, he = g && m, Q = this.transformers.beforeSend;
2796
- if (Q && (!E || g && !he)) {
2797
- const T = mt(c, Q, "EventManager");
2798
- if (T === null)
2882
+ const f = this.get("collectApiUrls"), m = !!f?.custom, g = !!f?.saas, E = m || g, he = m && g, z = this.transformers.beforeSend;
2883
+ if (z && (!E || m && !he)) {
2884
+ const v = mt(c, z, "EventManager");
2885
+ if (v === null)
2799
2886
  return null;
2800
- c = T;
2887
+ c = v;
2801
2888
  }
2802
2889
  return { ...c, _session_id: t };
2803
2890
  }
@@ -2974,7 +3061,7 @@ class _s extends v {
2974
3061
  loadSessionCounts(e) {
2975
3062
  if (typeof window > "u" || typeof localStorage > "u")
2976
3063
  return this.getInitialCounts();
2977
- const t = this.get("userId") || "anonymous", s = He(t, e);
3064
+ const t = this.get("userId") || "anonymous", s = Fe(t, e);
2978
3065
  try {
2979
3066
  const n = localStorage.getItem(s);
2980
3067
  if (!n)
@@ -3084,7 +3171,7 @@ class _s extends v {
3084
3171
  * @internal
3085
3172
  */
3086
3173
  saveSessionCounts(e) {
3087
- const t = this.get("userId") || "anonymous", s = He(t, e);
3174
+ const t = this.get("userId") || "anonymous", s = Fe(t, e);
3088
3175
  try {
3089
3176
  const n = {
3090
3177
  ...this.sessionEventCounts,
@@ -3100,7 +3187,7 @@ class _s extends v {
3100
3187
  }
3101
3188
  }
3102
3189
  }
3103
- class vs {
3190
+ class _s {
3104
3191
  /**
3105
3192
  * Gets or creates a unique user ID.
3106
3193
  *
@@ -3118,15 +3205,15 @@ class vs {
3118
3205
  * @returns Persistent unique user ID (UUID v4 format)
3119
3206
  */
3120
3207
  static getId(e) {
3121
- const t = e.getItem(Ie);
3208
+ const t = e.getItem(ve);
3122
3209
  if (t)
3123
3210
  return t;
3124
3211
  const s = dt();
3125
- return e.setItem(Ie, s), s;
3212
+ return e.setItem(ve, s), s;
3126
3213
  }
3127
3214
  }
3128
3215
  const ys = /^\d{13}-[a-z0-9]{9}$/;
3129
- class ws extends v {
3216
+ class ws extends _ {
3130
3217
  storageManager;
3131
3218
  eventManager;
3132
3219
  projectId;
@@ -3457,7 +3544,7 @@ class ws extends v {
3457
3544
  this.clearSessionTimeout(), this.cleanupActivityListeners(), this.cleanupCrossTabSync(), this.cleanupLifecycleListeners(), this.isTracking = !1, this.needsRenewal = !1, this.set("hasStartSession", !1);
3458
3545
  }
3459
3546
  }
3460
- class bs extends v {
3547
+ class bs extends _ {
3461
3548
  eventManager;
3462
3549
  storageManager;
3463
3550
  sessionManager = null;
@@ -3545,7 +3632,7 @@ class bs extends v {
3545
3632
  this.destroyed || (this.sessionManager && (this.sessionManager.destroy(), this.sessionManager = null), this.destroyed = !0);
3546
3633
  }
3547
3634
  }
3548
- class Ls extends v {
3635
+ class Ls extends _ {
3549
3636
  eventManager;
3550
3637
  onTrack;
3551
3638
  originalPushState;
@@ -3600,7 +3687,7 @@ class Ls extends v {
3600
3687
  page_url: this.get("pageUrl"),
3601
3688
  from_page_url: i,
3602
3689
  ...o && { page_view: o }
3603
- });
3690
+ }), this.get("config").flushOnSpaNavigation !== !1 && this.eventManager.flushImmediately();
3604
3691
  };
3605
3692
  trackInitialPageView() {
3606
3693
  const e = we(window.location.href, this.get("config").sensitiveQueryParams), t = this.extractPageViewData();
@@ -3621,7 +3708,7 @@ class Ls extends v {
3621
3708
  };
3622
3709
  }
3623
3710
  }
3624
- class As extends v {
3711
+ class As extends _ {
3625
3712
  eventManager;
3626
3713
  lastClickTimes = /* @__PURE__ */ new Map();
3627
3714
  clickHandler;
@@ -3658,12 +3745,12 @@ class As extends v {
3658
3745
  if (o) {
3659
3746
  const f = this.extractTrackingData(o);
3660
3747
  if (f) {
3661
- const g = this.createCustomEventData(f);
3748
+ const m = this.createCustomEventData(f);
3662
3749
  this.eventManager.track({
3663
3750
  type: u.CUSTOM,
3664
3751
  custom_event: {
3665
- name: g.name,
3666
- ...g.value && { metadata: { value: g.value } }
3752
+ name: m.name,
3753
+ ...m.value && { metadata: { value: m.value } }
3667
3754
  }
3668
3755
  });
3669
3756
  }
@@ -3885,7 +3972,7 @@ class As extends v {
3885
3972
  };
3886
3973
  }
3887
3974
  }
3888
- class Ms extends v {
3975
+ class Ms extends _ {
3889
3976
  eventManager;
3890
3977
  containers = [];
3891
3978
  limitWarningLogged = !1;
@@ -4069,12 +4156,12 @@ class Ms extends v {
4069
4156
  const { element: t, lastScrollPos: s, lastEventTime: n } = e, i = this.getScrollTop(t), o = Date.now(), l = Math.abs(i - s);
4070
4157
  if (l < 10 || t === window && !this.isWindowScrollable())
4071
4158
  return null;
4072
- const d = this.getViewportHeight(t), c = this.getScrollHeight(t), f = this.getScrollDirection(i, s), g = this.calculateScrollDepth(i, c, d);
4073
- let m;
4074
- n > 0 ? m = o - n : e.firstScrollEventTime !== null ? m = o - e.firstScrollEventTime : m = 250;
4075
- const E = Math.round(l / m * 1e3);
4076
- return g > e.maxDepthReached && (e.maxDepthReached = g), e.lastScrollPos = i, {
4077
- depth: g,
4159
+ const d = this.getViewportHeight(t), c = this.getScrollHeight(t), f = this.getScrollDirection(i, s), m = this.calculateScrollDepth(i, c, d);
4160
+ let g;
4161
+ n > 0 ? g = o - n : e.firstScrollEventTime !== null ? g = o - e.firstScrollEventTime : g = 250;
4162
+ const E = Math.round(l / g * 1e3);
4163
+ return m > e.maxDepthReached && (e.maxDepthReached = m), e.lastScrollPos = i, {
4164
+ depth: m,
4078
4165
  direction: f,
4079
4166
  velocity: E,
4080
4167
  max_depth_reached: e.maxDepthReached
@@ -4113,7 +4200,7 @@ class Ms extends v {
4113
4200
  e.isPrimary = t;
4114
4201
  }
4115
4202
  }
4116
- class Cs extends v {
4203
+ class Cs extends _ {
4117
4204
  eventManager;
4118
4205
  trackedElements = /* @__PURE__ */ new Map();
4119
4206
  observer = null;
@@ -4275,7 +4362,7 @@ class Cs extends v {
4275
4362
  }
4276
4363
  }
4277
4364
  const Rs = "tracelog_session_id", Ns = "tracelog_user_id";
4278
- class Os extends v {
4365
+ class Os extends _ {
4279
4366
  visibilityHandler = null;
4280
4367
  pageshowHandler = null;
4281
4368
  lastSyncedKey = null;
@@ -4617,7 +4704,7 @@ class Ps {
4617
4704
  this.fallbackSessionStorage.delete(e);
4618
4705
  }
4619
4706
  }
4620
- class Ds extends v {
4707
+ class Ds extends _ {
4621
4708
  eventManager;
4622
4709
  reportedByNav = /* @__PURE__ */ new Map();
4623
4710
  navigationHistory = [];
@@ -4628,7 +4715,7 @@ class Ds extends v {
4628
4715
  navigationCounter = 0;
4629
4716
  // Counter for handling simultaneous navigations edge case
4630
4717
  constructor(e) {
4631
- super(), this.eventManager = e, this.vitalThresholds = Qe(ye);
4718
+ super(), this.eventManager = e, this.vitalThresholds = ze(ye);
4632
4719
  }
4633
4720
  /**
4634
4721
  * Starts tracking Web Vitals and performance metrics.
@@ -4646,7 +4733,7 @@ class Ds extends v {
4646
4733
  */
4647
4734
  async startTracking() {
4648
4735
  const e = this.get("config"), t = e?.webVitalsMode ?? ye;
4649
- this.vitalThresholds = Qe(t), e?.webVitalsThresholds && (this.vitalThresholds = { ...this.vitalThresholds, ...e.webVitalsThresholds }), await this.initWebVitals(), this.observeLongTasks();
4736
+ this.vitalThresholds = ze(t), e?.webVitalsThresholds && (this.vitalThresholds = { ...this.vitalThresholds, ...e.webVitalsThresholds }), await this.initWebVitals(), this.observeLongTasks();
4650
4737
  }
4651
4738
  /**
4652
4739
  * Stops tracking Web Vitals and cleans up resources.
@@ -4716,7 +4803,7 @@ class Ds extends v {
4716
4803
  }
4717
4804
  async initWebVitals() {
4718
4805
  try {
4719
- const { onLCP: e, onCLS: t, onFCP: s, onTTFB: n, onINP: i } = await Promise.resolve().then(() => hr), o = (l) => (d) => {
4806
+ const { onLCP: e, onCLS: t, onFCP: s, onTTFB: n, onINP: i } = await Promise.resolve().then(() => mr), o = (l) => (d) => {
4720
4807
  const c = Number(d.value.toFixed(2));
4721
4808
  this.sendVital({ type: l, value: c });
4722
4809
  };
@@ -4850,7 +4937,7 @@ class Ds extends v {
4850
4937
  return !(typeof s == "number" && t <= s);
4851
4938
  }
4852
4939
  }
4853
- class ae extends v {
4940
+ class ae extends _ {
4854
4941
  eventManager;
4855
4942
  recentErrors = /* @__PURE__ */ new Map();
4856
4943
  errorBurstCounter = 0;
@@ -4902,12 +4989,13 @@ class ae extends v {
4902
4989
  const t = this.sanitize(e.message || "Unknown error");
4903
4990
  if (this.shouldSuppressError(B.JS_ERROR, t))
4904
4991
  return;
4905
- const s = typeof e.error?.stack == "string" ? this.truncateStack(e.error.stack) : void 0;
4992
+ const s = typeof e.error?.stack == "string" ? this.truncateStack(e.error.stack) : void 0, n = typeof e.error?.name == "string" && e.error.name !== "Error" ? e.error.name : void 0;
4906
4993
  this.eventManager.track({
4907
4994
  type: u.ERROR,
4908
4995
  error_data: {
4909
4996
  type: B.JS_ERROR,
4910
4997
  message: t,
4998
+ ...n !== void 0 && { name: n },
4911
4999
  ...e.filename !== "" && { filename: e.filename },
4912
5000
  ...e.lineno !== 0 && { line: e.lineno },
4913
5001
  ...e.colno !== 0 && { column: e.colno },
@@ -4921,12 +5009,13 @@ class ae extends v {
4921
5009
  const t = this.extractRejectionMessage(e.reason), s = this.sanitize(t);
4922
5010
  if (this.shouldSuppressError(B.PROMISE_REJECTION, s))
4923
5011
  return;
4924
- const n = e.reason instanceof Error && typeof e.reason.stack == "string" ? this.truncateStack(e.reason.stack) : void 0;
5012
+ const n = e.reason instanceof Error && typeof e.reason.stack == "string" ? this.truncateStack(e.reason.stack) : void 0, i = e.reason instanceof Error && e.reason.name !== "Error" ? e.reason.name : void 0;
4925
5013
  this.eventManager.track({
4926
5014
  type: u.ERROR,
4927
5015
  error_data: {
4928
5016
  type: B.PROMISE_REJECTION,
4929
5017
  message: s,
5018
+ ...i !== void 0 && { name: i },
4930
5019
  ...n !== void 0 && { stack: n }
4931
5020
  }
4932
5021
  });
@@ -4980,10 +5069,12 @@ class ae extends v {
4980
5069
  }
4981
5070
  }
4982
5071
  }
4983
- class ks extends v {
5072
+ class ks extends _ {
4984
5073
  isInitialized = !1;
4985
5074
  suppressNextScrollTimer = null;
4986
5075
  pageUnloadHandler = null;
5076
+ pageShowHandler = null;
5077
+ visibilityFlushHandler = null;
4987
5078
  emitter = new Es();
4988
5079
  transformers = {};
4989
5080
  customHeadersProvider;
@@ -5007,7 +5098,7 @@ class ks extends v {
5007
5098
  try {
5008
5099
  this.setupState(e);
5009
5100
  const t = e.integrations?.custom?.headers ?? {}, s = e.integrations?.custom?.fetchCredentials ?? "include";
5010
- return this.managers.event = new _s(
5101
+ return this.managers.event = new Is(
5011
5102
  this.managers.storage,
5012
5103
  this.emitter,
5013
5104
  this.transformers,
@@ -5024,33 +5115,74 @@ class ks extends v {
5024
5115
  }
5025
5116
  }
5026
5117
  /**
5027
- * Sends a custom event with optional metadata.
5118
+ * Asynchronously flushes all pending events in the queue.
5119
+ *
5120
+ * Internally calls `EventManager.flushImmediately()` which uses `fetch()` with retries.
5121
+ * Use when you need to force-send buffered events without waiting for the next send interval
5122
+ * (e.g., before a critical user action like sign-out, or before a SPA route teardown).
5123
+ *
5124
+ * @returns Promise<boolean> — `true` if all integrations sent successfully, `false` otherwise
5125
+ * @internal Called from api.flushImmediately()
5126
+ */
5127
+ async flushImmediately() {
5128
+ return await this.managers.event?.flushImmediately() ?? !1;
5129
+ }
5130
+ /**
5131
+ * Synchronously flushes all pending events using `navigator.sendBeacon()`.
5132
+ *
5133
+ * Use only for page-unload scenarios (or equivalent) where async fetch may be cancelled.
5134
+ * For general flush needs, prefer {@link flushImmediately}.
5135
+ *
5136
+ * @returns `true` if all integrations sent successfully, `false` otherwise
5137
+ * @internal Called from api.flushImmediatelySync()
5138
+ */
5139
+ flushImmediatelySync() {
5140
+ return this.managers.event?.flushImmediatelySync() ?? !1;
5141
+ }
5142
+ /**
5143
+ * Sends a custom event with optional metadata and options.
5028
5144
  *
5029
5145
  * @param name - Event name
5030
5146
  * @param metadata - Optional metadata
5147
+ * @param options - Optional event options. `{ critical: true }` triggers the
5148
+ * double-write delivery path: (1) the just-tracked event is sent in its
5149
+ * own dedicated single-event `sendBeacon` (immune to the 64KB queue cap),
5150
+ * and (2) the main queue is drained too — deferred to the in-flight
5151
+ * async send's `finally` block when one is running, so events tracked
5152
+ * immediately before the critical one are not stranded. Backend must
5153
+ * deduplicate by `event.id` since both paths may deliver the same event.
5154
+ * No-op for events dropped by rate limiting / sampling / `beforeSend`.
5031
5155
  * @internal Called from api.event()
5032
5156
  */
5033
- sendCustomEvent(e, t) {
5157
+ sendCustomEvent(e, t, s) {
5034
5158
  if (!this.managers.event) {
5035
5159
  a("warn", "Cannot send custom event: TraceLog not initialized", { data: { name: e } });
5036
5160
  return;
5037
5161
  }
5038
- let s = t;
5039
- t && typeof t == "object" && !Array.isArray(t) && Object.getPrototypeOf(t) !== Object.prototype && (s = Object.assign({}, t));
5040
- const { valid: n, error: i, sanitizedMetadata: o } = ps(e, s);
5041
- if (!n) {
5162
+ let n = t;
5163
+ t && typeof t == "object" && !Array.isArray(t) && Object.getPrototypeOf(t) !== Object.prototype && (n = Object.assign({}, t));
5164
+ const { valid: i, error: o, sanitizedMetadata: l } = ps(e, n);
5165
+ if (!i) {
5042
5166
  if (this.get("mode") === ie.QA)
5043
- throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${i}`);
5044
- a("warn", `Custom event "${e}" dropped: ${i}`);
5167
+ throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${o}`);
5168
+ a("warn", `Custom event "${e}" dropped: ${o}`);
5045
5169
  return;
5046
5170
  }
5047
- this.managers.event.track({
5171
+ const d = this.managers.event.getQueueLength();
5172
+ if (this.managers.event.track({
5048
5173
  type: u.CUSTOM,
5049
5174
  custom_event: {
5050
5175
  name: e,
5051
- ...o && { metadata: o }
5176
+ ...l && { metadata: l }
5052
5177
  }
5053
- });
5178
+ }), s?.critical === !0) {
5179
+ if (!(this.managers.event.getQueueLength() > d)) {
5180
+ a("debug", "Critical event was dropped before queueing — no flush triggered", { data: { name: e } });
5181
+ return;
5182
+ }
5183
+ const f = this.managers.event.flushLastEventSync(), m = this.managers.event.flushImmediatelySync();
5184
+ !f && !m && a("debug", "Critical event: dedicated beacon and queue drain both failed", { data: { name: e } });
5185
+ }
5054
5186
  }
5055
5187
  on(e, t) {
5056
5188
  this.emitter.on(e, t);
@@ -5103,11 +5235,11 @@ class ks extends v {
5103
5235
  } catch (s) {
5104
5236
  a("warn", "Failed to stop tracking", { error: s });
5105
5237
  }
5106
- }), this.suppressNextScrollTimer && (clearTimeout(this.suppressNextScrollTimer), this.suppressNextScrollTimer = null), this.pageUnloadHandler && (window.removeEventListener("pagehide", this.pageUnloadHandler), window.removeEventListener("beforeunload", this.pageUnloadHandler), this.pageUnloadHandler = null), this.managers.event?.flushImmediatelySync(), this.managers.event?.stop(), this.emitter.removeAllListeners(), this.transformers.beforeSend = void 0, this.transformers.beforeBatch = void 0, this.customHeadersProvider = void 0, this.set("suppressNextScroll", !1), this.set("sessionId", null), this.set("identity", void 0), this.clearPersistedIdentity(), this.integrationInstances.shopifyCartLinker?.deactivate(), this.integrationInstances = {}, this.isInitialized = !1, this.handlers = {}, this.managers = {});
5238
+ }), this.suppressNextScrollTimer && (clearTimeout(this.suppressNextScrollTimer), this.suppressNextScrollTimer = null), this.pageUnloadHandler && (window.removeEventListener("pagehide", this.pageUnloadHandler), window.removeEventListener("beforeunload", this.pageUnloadHandler), this.pageUnloadHandler = null), this.pageShowHandler && (window.removeEventListener("pageshow", this.pageShowHandler), this.pageShowHandler = null), this.visibilityFlushHandler && (document.removeEventListener("visibilitychange", this.visibilityFlushHandler), this.visibilityFlushHandler = null), this.managers.event?.flushImmediatelySync(), this.managers.event?.stop(), this.emitter.removeAllListeners(), this.transformers.beforeSend = void 0, this.transformers.beforeBatch = void 0, this.customHeadersProvider = void 0, this.set("suppressNextScroll", !1), this.set("sessionId", null), this.set("identity", void 0), this.clearPersistedIdentity(), this.integrationInstances.shopifyCartLinker?.deactivate(), this.integrationInstances = {}, this.isInitialized = !1, this.handlers = {}, this.managers = {});
5107
5239
  }
5108
5240
  setupState(e = {}) {
5109
5241
  this.set("config", e);
5110
- const t = vs.getId(this.managers.storage);
5242
+ const t = _s.getId(this.managers.storage);
5111
5243
  this.set("userId", t);
5112
5244
  const s = ls(e);
5113
5245
  this.set("collectApiUrls", s);
@@ -5252,7 +5384,7 @@ class ks extends v {
5252
5384
  async resetIdentity() {
5253
5385
  await this.managers.event?.flushImmediately(), this.set("identity", void 0), this.clearPersistedIdentity();
5254
5386
  const e = dt();
5255
- this.managers.storage.setItem(Ie, e), this.set("userId", e), this.set("hasStartSession", !1), this.set("sessionId", null), this.handlers.session?.stopTracking(), this.handlers.session?.startTracking(), a("debug", "Identity reset, new UUID generated");
5387
+ this.managers.storage.setItem(ve, e), this.set("userId", e), this.set("hasStartSession", !1), this.set("sessionId", null), this.handlers.session?.stopTracking(), this.handlers.session?.startTracking(), a("debug", "Identity reset, new UUID generated");
5256
5388
  }
5257
5389
  /**
5258
5390
  * Returns the project ID used for identity storage scoping.
@@ -5279,10 +5411,10 @@ class ks extends v {
5279
5411
  loadPersistedIdentity() {
5280
5412
  const e = this.managers.storage, t = this.getProjectId(), s = me(t);
5281
5413
  try {
5282
- const n = e.getItem(F);
5414
+ const n = e.getItem(H);
5283
5415
  if (n) {
5284
5416
  const i = JSON.parse(n);
5285
- if (e.removeItem(F), !this.isValidIdentityData(i)) {
5417
+ if (e.removeItem(H), !this.isValidIdentityData(i)) {
5286
5418
  a("debug", "Invalid pending identity in localStorage, discarded");
5287
5419
  return;
5288
5420
  }
@@ -5291,7 +5423,7 @@ class ks extends v {
5291
5423
  return;
5292
5424
  }
5293
5425
  } catch {
5294
- e.removeItem(F);
5426
+ e.removeItem(H);
5295
5427
  }
5296
5428
  try {
5297
5429
  const n = e.getItem(s);
@@ -5329,7 +5461,7 @@ class ks extends v {
5329
5461
  clearPersistedIdentity() {
5330
5462
  try {
5331
5463
  const e = this.managers.storage, t = this.getProjectId();
5332
- e.removeItem(me(t)), e.removeItem(F);
5464
+ e.removeItem(me(t)), e.removeItem(H);
5333
5465
  } catch {
5334
5466
  a("debug", "Failed to clear persisted identity");
5335
5467
  }
@@ -5337,7 +5469,13 @@ class ks extends v {
5337
5469
  setupPageLifecycleListeners() {
5338
5470
  this.pageUnloadHandler = () => {
5339
5471
  this.managers.event?.flushImmediatelySync();
5340
- }, window.addEventListener("pagehide", this.pageUnloadHandler), window.addEventListener("beforeunload", this.pageUnloadHandler);
5472
+ }, this.pageShowHandler = (e) => {
5473
+ e.persisted && this.managers.event?.recoverPersistedEvents().catch((t) => {
5474
+ a("warn", "Failed to recover persisted events on bfcache restore", { error: t });
5475
+ });
5476
+ }, this.visibilityFlushHandler = () => {
5477
+ typeof document > "u" || !document.hidden || this.get("config").flushOnPageHidden !== !1 && this.managers.event?.flushImmediatelySync();
5478
+ }, window.addEventListener("pagehide", this.pageUnloadHandler), window.addEventListener("beforeunload", this.pageUnloadHandler), window.addEventListener("pageshow", this.pageShowHandler), document.addEventListener("visibilitychange", this.visibilityFlushHandler);
5341
5479
  }
5342
5480
  initializeHandlers() {
5343
5481
  const e = this.get("config");
@@ -5361,8 +5499,8 @@ class ks extends v {
5361
5499
  }
5362
5500
  }
5363
5501
  const k = [], M = [];
5364
- let D = null, h = null, R = !1, _ = !1, P = null;
5365
- const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { sessionId: "" } : (_ = !1, window.__traceLogDisabled === !0 ? { sessionId: "" } : h ? { sessionId: h.getSessionId() ?? "" } : (R && P || (R = !0, P = (async () => {
5502
+ let D = null, h = null, R = !1, T = !1, P = null;
5503
+ const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { sessionId: "" } : (T = !1, window.__traceLogDisabled === !0 ? { sessionId: "" } : h ? { sessionId: h.getSessionId() ?? "" } : (R && P || (R = !0, P = (async () => {
5366
5504
  try {
5367
5505
  const e = fs(r ?? {}), t = new ks();
5368
5506
  try {
@@ -5390,15 +5528,15 @@ const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { session
5390
5528
  } finally {
5391
5529
  R = !1, P = null;
5392
5530
  }
5393
- })()), P)), Us = (r, e) => {
5531
+ })()), P)), Us = (r, e, t) => {
5394
5532
  if (!(typeof window > "u" || typeof document > "u")) {
5395
5533
  if (!h)
5396
5534
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5397
- if (_)
5535
+ if (T)
5398
5536
  throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");
5399
- h.sendCustomEvent(r, e);
5537
+ h.sendCustomEvent(r, e, t);
5400
5538
  }
5401
- }, Fs = (r, e) => {
5539
+ }, Hs = async () => typeof window > "u" || typeof document > "u" || !h || T ? !1 : h.flushImmediately(), Fs = () => typeof window > "u" || typeof document > "u" || !h || T ? !1 : h.flushImmediatelySync(), xs = (r, e) => {
5402
5540
  if (!(typeof window > "u" || typeof document > "u")) {
5403
5541
  if (!h || R) {
5404
5542
  k.push({ event: r, callback: e });
@@ -5406,7 +5544,7 @@ const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { session
5406
5544
  }
5407
5545
  h.on(r, e);
5408
5546
  }
5409
- }, Hs = (r, e) => {
5547
+ }, $s = (r, e) => {
5410
5548
  if (!(typeof window > "u" || typeof document > "u")) {
5411
5549
  if (!h) {
5412
5550
  const t = k.findIndex((s) => s.event === r && s.callback === e);
@@ -5416,7 +5554,7 @@ const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { session
5416
5554
  h.off(r, e);
5417
5555
  }
5418
5556
  };
5419
- function xs(r, e) {
5557
+ function Bs(r, e) {
5420
5558
  if (!(typeof window > "u" || typeof document > "u")) {
5421
5559
  if (typeof e != "function")
5422
5560
  throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof e}`);
@@ -5425,23 +5563,23 @@ function xs(r, e) {
5425
5563
  t !== -1 && M.splice(t, 1), M.push({ hook: r, fn: e });
5426
5564
  return;
5427
5565
  }
5428
- if (_)
5566
+ if (T)
5429
5567
  throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");
5430
5568
  r === "beforeSend" ? h.setTransformer("beforeSend", e) : h.setTransformer("beforeBatch", e);
5431
5569
  }
5432
5570
  }
5433
- const $s = (r) => {
5571
+ const Ws = (r) => {
5434
5572
  if (!(typeof window > "u" || typeof document > "u")) {
5435
5573
  if (!h) {
5436
5574
  const e = M.findIndex((t) => t.hook === r);
5437
5575
  e !== -1 && M.splice(e, 1);
5438
5576
  return;
5439
5577
  }
5440
- if (_)
5578
+ if (T)
5441
5579
  throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");
5442
5580
  h.removeTransformer(r);
5443
5581
  }
5444
- }, Bs = (r) => {
5582
+ }, Gs = (r) => {
5445
5583
  if (!(typeof window > "u" || typeof document > "u")) {
5446
5584
  if (typeof r != "function")
5447
5585
  throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof r}`);
@@ -5449,54 +5587,54 @@ const $s = (r) => {
5449
5587
  D = r;
5450
5588
  return;
5451
5589
  }
5452
- if (_)
5590
+ if (T)
5453
5591
  throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");
5454
5592
  h.setCustomHeaders(r);
5455
5593
  }
5456
- }, Ws = () => {
5594
+ }, Xs = () => {
5457
5595
  if (!(typeof window > "u" || typeof document > "u")) {
5458
5596
  if (!h) {
5459
5597
  D = null;
5460
5598
  return;
5461
5599
  }
5462
- if (_)
5600
+ if (T)
5463
5601
  throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");
5464
5602
  h.removeCustomHeaders();
5465
5603
  }
5466
- }, Gs = () => typeof window > "u" || typeof document > "u" ? !1 : h !== null, Xs = () => typeof window > "u" || typeof document > "u" || !h ? null : h.getSessionId(), js = () => {
5604
+ }, js = () => typeof window > "u" || typeof document > "u" ? !1 : h !== null, Ks = () => typeof window > "u" || typeof document > "u" || !h ? null : h.getSessionId(), Qs = () => {
5467
5605
  if (!(typeof window > "u" || typeof document > "u")) {
5468
- if (_)
5606
+ if (T)
5469
5607
  throw new Error("[TraceLog] Destroy operation already in progress");
5470
5608
  if (!h) {
5471
- _ = !1;
5609
+ T = !1;
5472
5610
  return;
5473
5611
  }
5474
- _ = !0;
5612
+ T = !0;
5475
5613
  try {
5476
- h.destroy(), h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, _ = !1;
5614
+ h.destroy(), h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, T = !1;
5477
5615
  } catch (r) {
5478
- h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, _ = !1, a("warn", "Error during destroy, forced cleanup completed", { error: r });
5616
+ h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, T = !1, a("warn", "Error during destroy, forced cleanup completed", { error: r });
5479
5617
  }
5480
5618
  }
5481
- }, Ks = (r) => {
5482
- typeof window > "u" || typeof document > "u" || rs(r);
5483
5619
  }, zs = (r) => {
5620
+ typeof window > "u" || typeof document > "u" || rs(r);
5621
+ }, Ys = (r) => {
5484
5622
  if (!(typeof window > "u" || typeof document > "u")) {
5485
5623
  if (!h)
5486
5624
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5487
- if (_)
5625
+ if (T)
5488
5626
  throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");
5489
5627
  h.updateGlobalMetadata(r);
5490
5628
  }
5491
- }, Qs = (r) => {
5629
+ }, qs = (r) => {
5492
5630
  if (!(typeof window > "u" || typeof document > "u")) {
5493
5631
  if (!h)
5494
5632
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5495
- if (_)
5633
+ if (T)
5496
5634
  throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");
5497
5635
  h.mergeGlobalMetadata(r);
5498
5636
  }
5499
- }, Ys = (r, e) => {
5637
+ }, Js = (r, e) => {
5500
5638
  if (!(typeof window > "u" || typeof document > "u")) {
5501
5639
  if (!r || typeof r != "string" || r.trim().length === 0) {
5502
5640
  a("warn", "identify() called with invalid userId");
@@ -5506,7 +5644,7 @@ const $s = (r) => {
5506
5644
  a("warn", "identify() userId exceeds 256 characters");
5507
5645
  return;
5508
5646
  }
5509
- if (_) {
5647
+ if (T) {
5510
5648
  a("warn", "Cannot identify while TraceLog is being destroyed");
5511
5649
  return;
5512
5650
  }
@@ -5519,41 +5657,43 @@ const $s = (r) => {
5519
5657
  userId: r.trim(),
5520
5658
  ...t ? { traits: t } : {}
5521
5659
  };
5522
- localStorage.setItem(F, JSON.stringify(s)), a("debug", "Identity persisted pre-init (will be applied on init)");
5660
+ localStorage.setItem(H, JSON.stringify(s)), a("debug", "Identity persisted pre-init (will be applied on init)");
5523
5661
  } catch {
5524
5662
  a("debug", "Failed to persist pre-init identity");
5525
5663
  }
5526
5664
  }
5527
- }, qs = async () => {
5665
+ }, Zs = async () => {
5528
5666
  if (!(typeof window > "u" || typeof document > "u")) {
5529
5667
  if (!h) {
5530
5668
  try {
5531
- localStorage.removeItem(F);
5669
+ localStorage.removeItem(H);
5532
5670
  } catch {
5533
5671
  }
5534
5672
  return;
5535
5673
  }
5536
- if (_)
5674
+ if (T)
5537
5675
  throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");
5538
5676
  await h.resetIdentity();
5539
5677
  }
5540
- }, Lr = {
5678
+ }, Mr = {
5541
5679
  init: Vs,
5542
5680
  event: Us,
5543
- on: Fs,
5544
- off: Hs,
5545
- setTransformer: xs,
5546
- removeTransformer: $s,
5547
- setCustomHeaders: Bs,
5548
- removeCustomHeaders: Ws,
5549
- isInitialized: Gs,
5550
- getSessionId: Xs,
5551
- destroy: js,
5552
- setQaMode: Ks,
5553
- updateGlobalMetadata: zs,
5554
- mergeGlobalMetadata: Qs,
5555
- identify: Ys,
5556
- resetIdentity: qs
5681
+ on: xs,
5682
+ off: $s,
5683
+ setTransformer: Bs,
5684
+ removeTransformer: Ws,
5685
+ setCustomHeaders: Gs,
5686
+ removeCustomHeaders: Xs,
5687
+ isInitialized: js,
5688
+ getSessionId: Ks,
5689
+ destroy: Qs,
5690
+ setQaMode: zs,
5691
+ updateGlobalMetadata: Ys,
5692
+ mergeGlobalMetadata: qs,
5693
+ identify: Js,
5694
+ resetIdentity: Zs,
5695
+ flushImmediately: Hs,
5696
+ flushImmediatelySync: Fs
5557
5697
  };
5558
5698
  var Ae, C, X, pt, le, Et = -1, V = function(r) {
5559
5699
  addEventListener("pageshow", (function(e) {
@@ -5602,28 +5742,28 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5602
5742
  return function() {
5603
5743
  e || (r(), e = !0);
5604
5744
  };
5605
- }, H = -1, et = function() {
5745
+ }, F = -1, et = function() {
5606
5746
  return document.visibilityState !== "hidden" || document.prerendering ? 1 / 0 : 0;
5607
5747
  }, ce = function(r) {
5608
- document.visibilityState === "hidden" && H > -1 && (H = r.type === "visibilitychange" ? r.timeStamp : 0, Js());
5748
+ document.visibilityState === "hidden" && F > -1 && (F = r.type === "visibilitychange" ? r.timeStamp : 0, er());
5609
5749
  }, tt = function() {
5610
5750
  addEventListener("visibilitychange", ce, !0), addEventListener("prerenderingchange", ce, !0);
5611
- }, Js = function() {
5751
+ }, er = function() {
5612
5752
  removeEventListener("visibilitychange", ce, !0), removeEventListener("prerenderingchange", ce, !0);
5613
5753
  }, Ve = function() {
5614
- return H < 0 && (H = et(), tt(), V((function() {
5754
+ return F < 0 && (F = et(), tt(), V((function() {
5615
5755
  setTimeout((function() {
5616
- H = et(), tt();
5756
+ F = et(), tt();
5617
5757
  }), 0);
5618
5758
  }))), { get firstHiddenTime() {
5619
- return H;
5759
+ return F;
5620
5760
  } };
5621
- }, z = function(r) {
5761
+ }, Q = function(r) {
5622
5762
  document.prerendering ? addEventListener("prerenderingchange", (function() {
5623
5763
  return r();
5624
5764
  }), !0) : r();
5625
5765
  }, Me = [1800, 3e3], St = function(r, e) {
5626
- e = e || {}, z((function() {
5766
+ e = e || {}, Q((function() {
5627
5767
  var t, s = Ve(), n = y("FCP"), i = x("paint", (function(o) {
5628
5768
  o.forEach((function(l) {
5629
5769
  l.name === "first-contentful-paint" && (i.disconnect(), l.startTime < s.firstHiddenTime && (n.value = Math.max(l.startTime - de(), 0), n.entries.push(l), t(!0)));
@@ -5635,13 +5775,13 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5635
5775
  }));
5636
5776
  })));
5637
5777
  }));
5638
- }, Ce = [0.1, 0.25], Zs = function(r, e) {
5778
+ }, Ce = [0.1, 0.25], tr = function(r, e) {
5639
5779
  e = e || {}, St(ue((function() {
5640
5780
  var t, s = y("CLS", 0), n = 0, i = [], o = function(d) {
5641
5781
  d.forEach((function(c) {
5642
5782
  if (!c.hadRecentInput) {
5643
- var f = i[0], g = i[i.length - 1];
5644
- n && c.startTime - g.startTime < 1e3 && c.startTime - f.startTime < 5e3 ? (n += c.value, i.push(c)) : (n = c.value, i = [c]);
5783
+ var f = i[0], m = i[i.length - 1];
5784
+ n && c.startTime - m.startTime < 1e3 && c.startTime - f.startTime < 5e3 ? (n += c.value, i.push(c)) : (n = c.value, i = [c]);
5645
5785
  }
5646
5786
  })), n > s.value && (s.value = n, s.entries = i, t());
5647
5787
  }, l = x("layout-shift", o);
@@ -5653,19 +5793,19 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5653
5793
  }));
5654
5794
  })), setTimeout(t, 0));
5655
5795
  })));
5656
- }, Tt = 0, Se = 1 / 0, J = 0, er = function(r) {
5796
+ }, Tt = 0, Se = 1 / 0, J = 0, sr = function(r) {
5657
5797
  r.forEach((function(e) {
5658
5798
  e.interactionId && (Se = Math.min(Se, e.interactionId), J = Math.max(J, e.interactionId), Tt = J ? (J - Se) / 7 + 1 : 0);
5659
5799
  }));
5660
- }, It = function() {
5800
+ }, vt = function() {
5661
5801
  return Ae ? Tt : performance.interactionCount || 0;
5662
- }, tr = function() {
5663
- "interactionCount" in performance || Ae || (Ae = x("event", er, { type: "event", buffered: !0, durationThreshold: 0 }));
5664
- }, L = [], te = /* @__PURE__ */ new Map(), _t = 0, sr = function() {
5665
- var r = Math.min(L.length - 1, Math.floor((It() - _t) / 50));
5802
+ }, rr = function() {
5803
+ "interactionCount" in performance || Ae || (Ae = x("event", sr, { type: "event", buffered: !0, durationThreshold: 0 }));
5804
+ }, L = [], te = /* @__PURE__ */ new Map(), It = 0, nr = function() {
5805
+ var r = Math.min(L.length - 1, Math.floor((vt() - It) / 50));
5666
5806
  return L[r];
5667
- }, rr = [], nr = function(r) {
5668
- if (rr.forEach((function(n) {
5807
+ }, ir = [], or = function(r) {
5808
+ if (ir.forEach((function(n) {
5669
5809
  return n(r);
5670
5810
  })), r.interactionId || r.entryType === "first-input") {
5671
5811
  var e = L[L.length - 1], t = te.get(r.interactionId);
@@ -5682,28 +5822,28 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5682
5822
  }));
5683
5823
  }
5684
5824
  }
5685
- }, vt = function(r) {
5825
+ }, _t = function(r) {
5686
5826
  var e = self.requestIdleCallback || self.setTimeout, t = -1;
5687
5827
  return r = ue(r), document.visibilityState === "hidden" ? r() : (t = e(r), K(r)), t;
5688
- }, Re = [200, 500], ir = function(r, e) {
5689
- "PerformanceEventTiming" in self && "interactionId" in PerformanceEventTiming.prototype && (e = e || {}, z((function() {
5828
+ }, Re = [200, 500], ar = function(r, e) {
5829
+ "PerformanceEventTiming" in self && "interactionId" in PerformanceEventTiming.prototype && (e = e || {}, Q((function() {
5690
5830
  var t;
5691
- tr();
5831
+ rr();
5692
5832
  var s, n = y("INP"), i = function(l) {
5693
- vt((function() {
5694
- l.forEach(nr);
5695
- var d = sr();
5833
+ _t((function() {
5834
+ l.forEach(or);
5835
+ var d = nr();
5696
5836
  d && d.latency !== n.value && (n.value = d.latency, n.entries = d.entries, s());
5697
5837
  }));
5698
5838
  }, o = x("event", i, { durationThreshold: (t = e.durationThreshold) !== null && t !== void 0 ? t : 40 });
5699
5839
  s = w(r, n, Re, e.reportAllChanges), o && (o.observe({ type: "first-input", buffered: !0 }), K((function() {
5700
5840
  i(o.takeRecords()), s(!0);
5701
5841
  })), V((function() {
5702
- _t = It(), L.length = 0, te.clear(), n = y("INP"), s = w(r, n, Re, e.reportAllChanges);
5842
+ It = vt(), L.length = 0, te.clear(), n = y("INP"), s = w(r, n, Re, e.reportAllChanges);
5703
5843
  })));
5704
5844
  })));
5705
- }, Ne = [2500, 4e3], Te = {}, or = function(r, e) {
5706
- e = e || {}, z((function() {
5845
+ }, Ne = [2500, 4e3], Te = {}, lr = function(r, e) {
5846
+ e = e || {}, Q((function() {
5707
5847
  var t, s = Ve(), n = y("LCP"), i = function(d) {
5708
5848
  e.reportAllChanges || (d = d.slice(-1)), d.forEach((function(c) {
5709
5849
  c.startTime < s.firstHiddenTime && (n.value = Math.max(c.startTime - de(), 0), n.entries = [c], t());
@@ -5716,7 +5856,7 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5716
5856
  }));
5717
5857
  ["keydown", "click"].forEach((function(d) {
5718
5858
  addEventListener(d, (function() {
5719
- return vt(l);
5859
+ return _t(l);
5720
5860
  }), { once: !0, capture: !0 });
5721
5861
  })), K(l), V((function(d) {
5722
5862
  n = y("LCP"), t = w(r, n, Ne, e.reportAllChanges), ke((function() {
@@ -5725,31 +5865,31 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5725
5865
  }));
5726
5866
  }
5727
5867
  }));
5728
- }, Oe = [800, 1800], ar = function r(e) {
5729
- document.prerendering ? z((function() {
5868
+ }, Oe = [800, 1800], cr = function r(e) {
5869
+ document.prerendering ? Q((function() {
5730
5870
  return r(e);
5731
5871
  })) : document.readyState !== "complete" ? addEventListener("load", (function() {
5732
5872
  return r(e);
5733
5873
  }), !0) : setTimeout(e, 0);
5734
- }, lr = function(r, e) {
5874
+ }, dr = function(r, e) {
5735
5875
  e = e || {};
5736
5876
  var t = y("TTFB"), s = w(r, t, Oe, e.reportAllChanges);
5737
- ar((function() {
5877
+ cr((function() {
5738
5878
  var n = De();
5739
5879
  n && (t.value = Math.max(n.responseStart - de(), 0), t.entries = [n], s(!0), V((function() {
5740
5880
  t = y("TTFB", 0), (s = w(r, t, Oe, e.reportAllChanges))(!0);
5741
5881
  })));
5742
5882
  }));
5743
- }, W = { passive: !0, capture: !0 }, cr = /* @__PURE__ */ new Date(), st = function(r, e) {
5883
+ }, W = { passive: !0, capture: !0 }, ur = /* @__PURE__ */ new Date(), st = function(r, e) {
5744
5884
  C || (C = e, X = r, pt = /* @__PURE__ */ new Date(), wt(removeEventListener), yt());
5745
5885
  }, yt = function() {
5746
- if (X >= 0 && X < pt - cr) {
5886
+ if (X >= 0 && X < pt - ur) {
5747
5887
  var r = { entryType: "first-input", name: C.type, target: C.target, cancelable: C.cancelable, startTime: C.timeStamp, processingStart: C.timeStamp + X };
5748
5888
  le.forEach((function(e) {
5749
5889
  e(r);
5750
5890
  })), le = [];
5751
5891
  }
5752
- }, dr = function(r) {
5892
+ }, hr = function(r) {
5753
5893
  if (r.cancelable) {
5754
5894
  var e = (r.timeStamp > 1e12 ? /* @__PURE__ */ new Date() : performance.now()) - r.timeStamp;
5755
5895
  r.type == "pointerdown" ? (function(t, s) {
@@ -5765,10 +5905,10 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5765
5905
  }
5766
5906
  }, wt = function(r) {
5767
5907
  ["mousedown", "keydown", "touchstart", "pointerdown"].forEach((function(e) {
5768
- return r(e, dr, W);
5908
+ return r(e, hr, W);
5769
5909
  }));
5770
- }, Pe = [100, 300], ur = function(r, e) {
5771
- e = e || {}, z((function() {
5910
+ }, Pe = [100, 300], fr = function(r, e) {
5911
+ e = e || {}, Q((function() {
5772
5912
  var t, s = Ve(), n = y("FID"), i = function(d) {
5773
5913
  d.startTime < s.firstHiddenTime && (n.value = d.processingStart - d.startTime, n.entries.push(d), t(!0));
5774
5914
  }, o = function(d) {
@@ -5782,7 +5922,7 @@ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5782
5922
  })));
5783
5923
  }));
5784
5924
  };
5785
- const hr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5925
+ const mr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5786
5926
  __proto__: null,
5787
5927
  CLSThresholds: Ce,
5788
5928
  FCPThresholds: Me,
@@ -5790,31 +5930,31 @@ const hr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5790
5930
  INPThresholds: Re,
5791
5931
  LCPThresholds: Ne,
5792
5932
  TTFBThresholds: Oe,
5793
- onCLS: Zs,
5933
+ onCLS: tr,
5794
5934
  onFCP: St,
5795
- onFID: ur,
5796
- onINP: ir,
5797
- onLCP: or,
5798
- onTTFB: lr
5935
+ onFID: fr,
5936
+ onINP: ar,
5937
+ onLCP: lr,
5938
+ onTTFB: dr
5799
5939
  }, Symbol.toStringTag, { value: "Module" }));
5800
5940
  export {
5801
5941
  p as AppConfigValidationError,
5802
- fr as DEFAULT_SESSION_TIMEOUT,
5942
+ gr as DEFAULT_SESSION_TIMEOUT,
5803
5943
  ye as DEFAULT_WEB_VITALS_MODE,
5804
5944
  A as DeviceType,
5805
5945
  se as EmitterEvent,
5806
5946
  B as ErrorType,
5807
5947
  u as EventType,
5808
- wr as InitializationTimeoutError,
5948
+ Lr as InitializationTimeoutError,
5809
5949
  N as IntegrationValidationError,
5810
- _r as MAX_ARRAY_LENGTH,
5811
- Er as MAX_CUSTOM_EVENT_ARRAY_SIZE,
5812
- pr as MAX_CUSTOM_EVENT_KEYS,
5813
- mr as MAX_CUSTOM_EVENT_NAME_LENGTH,
5814
- gr as MAX_CUSTOM_EVENT_STRING_SIZE,
5815
- Sr as MAX_NESTED_OBJECT_KEYS,
5816
- Tr as MAX_STRING_LENGTH,
5817
- Ir as MAX_STRING_LENGTH_IN_ARRAY,
5950
+ yr as MAX_ARRAY_LENGTH,
5951
+ Tr as MAX_CUSTOM_EVENT_ARRAY_SIZE,
5952
+ Sr as MAX_CUSTOM_EVENT_KEYS,
5953
+ pr as MAX_CUSTOM_EVENT_NAME_LENGTH,
5954
+ Er as MAX_CUSTOM_EVENT_STRING_SIZE,
5955
+ vr as MAX_NESTED_OBJECT_KEYS,
5956
+ Ir as MAX_STRING_LENGTH,
5957
+ _r as MAX_STRING_LENGTH_IN_ARRAY,
5818
5958
  ie as Mode,
5819
5959
  at as PII_PATTERNS,
5820
5960
  O as PermanentError,
@@ -5825,11 +5965,11 @@ export {
5825
5965
  $ as SpecialApiUrl,
5826
5966
  ne as TimeoutError,
5827
5967
  j as TraceLogValidationError,
5828
- br as WEB_VITALS_GOOD_THRESHOLDS,
5829
- ze as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,
5968
+ Ar as WEB_VITALS_GOOD_THRESHOLDS,
5969
+ Qe as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,
5830
5970
  Yt as WEB_VITALS_POOR_THRESHOLDS,
5831
- Qe as getWebVitalsThresholds,
5832
- vr as isPrimaryScrollEvent,
5833
- yr as isSecondaryScrollEvent,
5834
- Lr as tracelog
5971
+ ze as getWebVitalsThresholds,
5972
+ wr as isPrimaryScrollEvent,
5973
+ br as isSecondaryScrollEvent,
5974
+ Mr as tracelog
5835
5975
  };