@extn/segi-js 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -16,7 +16,14 @@ interface InitOptions {
16
16
  type SegiInitOptions = SegiClientOptions & {
17
17
  replay?: ReplayConfig;
18
18
  };
19
+ type ErrorSignal = {
20
+ ts: string;
21
+ url?: string;
22
+ };
19
23
  type ReplayApi = {
24
+ _captureError(signal: ErrorSignal): void;
25
+ _sessionUid(): string | null;
26
+ _stop(): void;
20
27
  pause(): void;
21
28
  resume(): void;
22
29
  setUser(user: {
package/dist/index.d.ts CHANGED
@@ -16,7 +16,14 @@ interface InitOptions {
16
16
  type SegiInitOptions = SegiClientOptions & {
17
17
  replay?: ReplayConfig;
18
18
  };
19
+ type ErrorSignal = {
20
+ ts: string;
21
+ url?: string;
22
+ };
19
23
  type ReplayApi = {
24
+ _captureError(signal: ErrorSignal): void;
25
+ _sessionUid(): string | null;
26
+ _stop(): void;
20
27
  pause(): void;
21
28
  resume(): void;
22
29
  setUser(user: {
package/dist/index.js CHANGED
@@ -178,7 +178,18 @@ function detachListeners() {
178
178
  window.removeEventListener("error", captureWindowError, true);
179
179
  window.removeEventListener("unhandledrejection", captureWindowError, true);
180
180
  }
181
+ var pendingReplayErrors = [];
182
+ var replayEnabled = false;
183
+ var replayEpoch = 0;
181
184
  var noopReplay = {
185
+ _captureError(signal) {
186
+ if (pendingReplayErrors.length < 20) pendingReplayErrors.push(signal);
187
+ },
188
+ _sessionUid() {
189
+ return null;
190
+ },
191
+ _stop() {
192
+ },
182
193
  pause() {
183
194
  },
184
195
  resume() {
@@ -215,14 +226,28 @@ var Segi = {
215
226
  return;
216
227
  }
217
228
  if (state.initialized) detachListeners();
229
+ Segi.replay._stop();
230
+ Segi.replay = noopReplay;
231
+ pendingReplayErrors = [];
232
+ const epoch = ++replayEpoch;
218
233
  const { replay, ...core } = options;
234
+ replayEnabled = !!_optionalChain([replay, 'optionalAccess', _3 => _3.__segi_replay]) && replay.options.enabled !== false;
219
235
  state.options = { ...core };
220
236
  state.initialized = true;
221
237
  if (w) w.__segiInitialized = true;
222
238
  attachListeners();
223
- if (_optionalChain([replay, 'optionalAccess', _3 => _3.__segi_replay])) {
239
+ if (_optionalChain([replay, 'optionalAccess', _4 => _4.__segi_replay])) {
224
240
  void Promise.resolve().then(() => _interopRequireWildcard(require("./replay/index.js"))).then((mod) => {
241
+ if (epoch !== replayEpoch || !state.initialized) return;
225
242
  Segi.replay = mod.replayApi;
243
+ for (const error of pendingReplayErrors) mod.replayApi._captureError(error);
244
+ pendingReplayErrors = [];
245
+ if (state.user) {
246
+ mod.replayApi.setUser({
247
+ id: state.user.id,
248
+ email: state.user.email
249
+ });
250
+ }
226
251
  return mod.activateReplay({
227
252
  projectKey: core.projectKey,
228
253
  // Empty/undefined here is fine — the replay transport falls
@@ -244,6 +269,11 @@ var Segi = {
244
269
  close() {
245
270
  try {
246
271
  detachListeners();
272
+ replayEpoch++;
273
+ replayEnabled = false;
274
+ Segi.replay._stop();
275
+ Segi.replay = noopReplay;
276
+ pendingReplayErrors = [];
247
277
  state.initialized = false;
248
278
  state.user = null;
249
279
  state.tags = {};
@@ -269,8 +299,15 @@ var Segi = {
269
299
  runtime: "browser",
270
300
  url: _nullishCoalesce(context.url, () => ( (typeof location !== "undefined" ? location.href : void 0))),
271
301
  userAgent: _nullishCoalesce(context.userAgent, () => ( (typeof navigator !== "undefined" ? navigator.userAgent : void 0))),
272
- ...context
302
+ ...context,
303
+ extra: {
304
+ ...context.extra,
305
+ ...Segi.replay._sessionUid() ? { sessionUid: Segi.replay._sessionUid() } : {}
306
+ }
273
307
  });
308
+ if (replayEnabled && !evt._drop) {
309
+ Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
310
+ }
274
311
  send(state.options.endpoint, state.options.projectKey, evt);
275
312
  } catch (e7) {
276
313
  }
@@ -286,8 +323,15 @@ var Segi = {
286
323
  runtime: "browser",
287
324
  url: typeof location !== "undefined" ? location.href : void 0,
288
325
  userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
289
- ...context
326
+ ...context,
327
+ extra: {
328
+ ...context.extra,
329
+ ...Segi.replay._sessionUid() ? { sessionUid: Segi.replay._sessionUid() } : {}
330
+ }
290
331
  });
332
+ if (replayEnabled && (evt.level === "error" || evt.level === "fatal") && !evt._drop) {
333
+ Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
334
+ }
291
335
  send(state.options.endpoint, state.options.projectKey, evt);
292
336
  } catch (e8) {
293
337
  }
@@ -295,6 +339,7 @@ var Segi = {
295
339
  setUser(user) {
296
340
  try {
297
341
  state.user = user;
342
+ Segi.replay.setUser(user ? { id: user.id, email: user.email } : null);
298
343
  } catch (e9) {
299
344
  }
300
345
  },
package/dist/index.mjs CHANGED
@@ -178,7 +178,18 @@ function detachListeners() {
178
178
  window.removeEventListener("error", captureWindowError, true);
179
179
  window.removeEventListener("unhandledrejection", captureWindowError, true);
180
180
  }
181
+ var pendingReplayErrors = [];
182
+ var replayEnabled = false;
183
+ var replayEpoch = 0;
181
184
  var noopReplay = {
185
+ _captureError(signal) {
186
+ if (pendingReplayErrors.length < 20) pendingReplayErrors.push(signal);
187
+ },
188
+ _sessionUid() {
189
+ return null;
190
+ },
191
+ _stop() {
192
+ },
182
193
  pause() {
183
194
  },
184
195
  resume() {
@@ -215,14 +226,28 @@ var Segi = {
215
226
  return;
216
227
  }
217
228
  if (state.initialized) detachListeners();
229
+ Segi.replay._stop();
230
+ Segi.replay = noopReplay;
231
+ pendingReplayErrors = [];
232
+ const epoch = ++replayEpoch;
218
233
  const { replay, ...core } = options;
234
+ replayEnabled = !!replay?.__segi_replay && replay.options.enabled !== false;
219
235
  state.options = { ...core };
220
236
  state.initialized = true;
221
237
  if (w) w.__segiInitialized = true;
222
238
  attachListeners();
223
239
  if (replay?.__segi_replay) {
224
240
  void import("./replay/index.mjs").then((mod) => {
241
+ if (epoch !== replayEpoch || !state.initialized) return;
225
242
  Segi.replay = mod.replayApi;
243
+ for (const error of pendingReplayErrors) mod.replayApi._captureError(error);
244
+ pendingReplayErrors = [];
245
+ if (state.user) {
246
+ mod.replayApi.setUser({
247
+ id: state.user.id,
248
+ email: state.user.email
249
+ });
250
+ }
226
251
  return mod.activateReplay({
227
252
  projectKey: core.projectKey,
228
253
  // Empty/undefined here is fine — the replay transport falls
@@ -244,6 +269,11 @@ var Segi = {
244
269
  close() {
245
270
  try {
246
271
  detachListeners();
272
+ replayEpoch++;
273
+ replayEnabled = false;
274
+ Segi.replay._stop();
275
+ Segi.replay = noopReplay;
276
+ pendingReplayErrors = [];
247
277
  state.initialized = false;
248
278
  state.user = null;
249
279
  state.tags = {};
@@ -269,8 +299,15 @@ var Segi = {
269
299
  runtime: "browser",
270
300
  url: context.url ?? (typeof location !== "undefined" ? location.href : void 0),
271
301
  userAgent: context.userAgent ?? (typeof navigator !== "undefined" ? navigator.userAgent : void 0),
272
- ...context
302
+ ...context,
303
+ extra: {
304
+ ...context.extra,
305
+ ...Segi.replay._sessionUid() ? { sessionUid: Segi.replay._sessionUid() } : {}
306
+ }
273
307
  });
308
+ if (replayEnabled && !evt._drop) {
309
+ Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
310
+ }
274
311
  send(state.options.endpoint, state.options.projectKey, evt);
275
312
  } catch {
276
313
  }
@@ -286,8 +323,15 @@ var Segi = {
286
323
  runtime: "browser",
287
324
  url: typeof location !== "undefined" ? location.href : void 0,
288
325
  userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
289
- ...context
326
+ ...context,
327
+ extra: {
328
+ ...context.extra,
329
+ ...Segi.replay._sessionUid() ? { sessionUid: Segi.replay._sessionUid() } : {}
330
+ }
290
331
  });
332
+ if (replayEnabled && (evt.level === "error" || evt.level === "fatal") && !evt._drop) {
333
+ Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
334
+ }
291
335
  send(state.options.endpoint, state.options.projectKey, evt);
292
336
  } catch {
293
337
  }
@@ -295,6 +339,7 @@ var Segi = {
295
339
  setUser(user) {
296
340
  try {
297
341
  state.user = user;
342
+ Segi.replay.setUser(user ? { id: user.id, email: user.email } : null);
298
343
  } catch {
299
344
  }
300
345
  },
@@ -30,6 +30,10 @@ import { R as ReplayConfig, a as ReplayOptions } from '../types-CsgcNSc1.mjs';
30
30
  */
31
31
 
32
32
  declare function withReplay(options?: ReplayOptions): ReplayConfig;
33
+ type ErrorSignal = {
34
+ ts: string;
35
+ url?: string;
36
+ };
33
37
  /**
34
38
  * Internal entry-point invoked by Segi.init() when a ReplayConfig was
35
39
  * passed. Not part of the public surface.
@@ -42,6 +46,9 @@ declare function activateReplay(args: {
42
46
  }): Promise<void>;
43
47
  /** Public Segi.replay namespace, attached by the main index.ts. */
44
48
  declare const replayApi: {
49
+ /** Internal bridge from the error SDK; no stack/message is copied to trace. */
50
+ _captureError(signal: ErrorSignal): void;
51
+ _stop(): void;
45
52
  pause(): void;
46
53
  resume(): void;
47
54
  setUser(user: {
@@ -30,6 +30,10 @@ import { R as ReplayConfig, a as ReplayOptions } from '../types-CsgcNSc1.js';
30
30
  */
31
31
 
32
32
  declare function withReplay(options?: ReplayOptions): ReplayConfig;
33
+ type ErrorSignal = {
34
+ ts: string;
35
+ url?: string;
36
+ };
33
37
  /**
34
38
  * Internal entry-point invoked by Segi.init() when a ReplayConfig was
35
39
  * passed. Not part of the public surface.
@@ -42,6 +46,9 @@ declare function activateReplay(args: {
42
46
  }): Promise<void>;
43
47
  /** Public Segi.replay namespace, attached by the main index.ts. */
44
48
  declare const replayApi: {
49
+ /** Internal bridge from the error SDK; no stack/message is copied to trace. */
50
+ _captureError(signal: ErrorSignal): void;
51
+ _stop(): void;
45
52
  pause(): void;
46
53
  resume(): void;
47
54
  setUser(user: {
@@ -2,9 +2,24 @@
2
2
  var UID_KEY = "_bd_session_uid";
3
3
  var UID_TS_KEY = "_bd_session_at";
4
4
  var ANON_KEY = "_bd_anon";
5
+ var PROGRESS_KEY = "_segi_replay_progress";
5
6
  var IDLE_MS = 30 * 6e4;
6
7
  var memUid = null;
7
8
  var memAnon = null;
9
+ function readReplayProgress(sessionUid) {
10
+ try {
11
+ const p = JSON.parse(sessionStorage.getItem(PROGRESS_KEY) || "null");
12
+ if (_optionalChain([p, 'optionalAccess', _ => _.sessionUid]) === sessionUid && Number.isFinite(Date.parse(p.startedAt)) && [p.clickCount, p.pagesVisited].every((n) => Number.isSafeInteger(n) && n >= 0)) return p;
13
+ } catch (e) {
14
+ }
15
+ return { sessionUid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), clickCount: 0, pagesVisited: 0 };
16
+ }
17
+ function writeReplayProgress(progress) {
18
+ try {
19
+ sessionStorage.setItem(PROGRESS_KEY, JSON.stringify(progress));
20
+ } catch (e2) {
21
+ }
22
+ }
8
23
  function uuid() {
9
24
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
10
25
  return crypto.randomUUID();
@@ -22,7 +37,7 @@ function readSession() {
22
37
  const at = Number(_nullishCoalesce(sessionStorage.getItem(UID_TS_KEY), () => ( "0")));
23
38
  if (!uid || !at) return null;
24
39
  return { uid, at };
25
- } catch (e) {
40
+ } catch (e3) {
26
41
  return null;
27
42
  }
28
43
  }
@@ -31,13 +46,13 @@ function writeSession(uid, at) {
31
46
  if (typeof sessionStorage === "undefined") return;
32
47
  sessionStorage.setItem(UID_KEY, uid);
33
48
  sessionStorage.setItem(UID_TS_KEY, String(at));
34
- } catch (e2) {
49
+ } catch (e4) {
35
50
  }
36
51
  }
37
52
  function getOrCreateSessionUid() {
38
53
  const now = Date.now();
39
54
  const existing = readSession();
40
- if (existing && now - existing.at < IDLE_MS) {
55
+ if (existing && now - existing.at < IDLE_MS && now - Date.parse(readReplayProgress(existing.uid).startedAt) < IDLE_MS) {
41
56
  writeSession(existing.uid, now);
42
57
  return existing.uid;
43
58
  }
@@ -61,7 +76,7 @@ function getOrCreateAnonId() {
61
76
  const fresh = uuid();
62
77
  localStorage.setItem(ANON_KEY, fresh);
63
78
  return fresh;
64
- } catch (e3) {
79
+ } catch (e5) {
65
80
  if (!memAnon) memAnon = uuid();
66
81
  return memAnon;
67
82
  }
@@ -90,7 +105,7 @@ async function postTrace(cfg, path, body) {
90
105
  // instead (separate API, no throw).
91
106
  });
92
107
  return res;
93
- } catch (e4) {
108
+ } catch (e6) {
94
109
  return null;
95
110
  }
96
111
  }
@@ -100,7 +115,7 @@ function beaconTrace(cfg, path, body) {
100
115
  const url = `${normalizeBase(cfg.endpoint)}/api/trace${path}?pk=${encodeURIComponent(cfg.projectKey)}`;
101
116
  const blob = new Blob([JSON.stringify(body)], { type: "application/json" });
102
117
  return navigator.sendBeacon(url, blob);
103
- } catch (e5) {
118
+ } catch (e7) {
104
119
  return false;
105
120
  }
106
121
  }
@@ -118,11 +133,34 @@ async function gzipString(str) {
118
133
  void writer.close();
119
134
  const buf = await new Response(cs.readable).arrayBuffer();
120
135
  return new Uint8Array(buf);
121
- } catch (e6) {
136
+ } catch (e8) {
122
137
  return null;
123
138
  }
124
139
  }
125
140
  var active = null;
141
+ var activationEpoch = 0;
142
+ var cleanup = [];
143
+ var pendingErrors = [];
144
+ function saveProgress() {
145
+ if (!active) return;
146
+ writeReplayProgress({
147
+ sessionUid: active.sessionUid,
148
+ startedAt: active.startedAt,
149
+ clickCount: active.clickCount,
150
+ pagesVisited: active.pagesVisited
151
+ });
152
+ }
153
+ function sendError(signal) {
154
+ if (!active || !active.recordingEnabled || active.paused) return;
155
+ void postTrace(active.config, "/events", { events: [{
156
+ sessionUid: active.sessionUid,
157
+ ts: signal.ts,
158
+ url: signal.url,
159
+ type: "error",
160
+ name: "sdk_error"
161
+ }] });
162
+ }
163
+ var pendingUser = void 0;
126
164
  function deviceClass() {
127
165
  if (typeof window === "undefined") return "desktop";
128
166
  const w = window.innerWidth;
@@ -134,7 +172,7 @@ function readQuery(name) {
134
172
  if (typeof location === "undefined") return void 0;
135
173
  try {
136
174
  return _nullishCoalesce(new URLSearchParams(location.search).get(name), () => ( void 0));
137
- } catch (e7) {
175
+ } catch (e9) {
138
176
  return void 0;
139
177
  }
140
178
  }
@@ -145,6 +183,7 @@ function isPathBlocked(opts, path) {
145
183
  async function activateReplay(args) {
146
184
  if (active) return;
147
185
  if (typeof window === "undefined") return;
186
+ const epoch = ++activationEpoch;
148
187
  const options = args.config.options;
149
188
  if (options.enabled === false) return;
150
189
  const sample = Math.max(0, Math.min(100, _nullishCoalesce(options.sample, () => ( 100))));
@@ -152,6 +191,7 @@ async function activateReplay(args) {
152
191
  if (isPathBlocked(options, location.pathname)) return;
153
192
  const sessionUid = getOrCreateSessionUid();
154
193
  const anonId = getOrCreateAnonId();
194
+ const progress = readReplayProgress(sessionUid);
155
195
  const transportCfg = {
156
196
  endpoint: _nullishCoalesce(options.endpoint, () => ( args.endpoint)),
157
197
  projectKey: args.projectKey
@@ -159,11 +199,11 @@ async function activateReplay(args) {
159
199
  const dto = {
160
200
  sessionUid,
161
201
  anonId,
162
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
202
+ startedAt: progress.startedAt,
163
203
  device: deviceClass(),
164
204
  viewportW: window.innerWidth,
165
205
  viewportH: window.innerHeight,
166
- ua: _optionalChain([navigator, 'access', _ => _.userAgent, 'optionalAccess', _2 => _2.slice, 'call', _3 => _3(0, 512)]),
206
+ ua: _optionalChain([navigator, 'access', _2 => _2.userAgent, 'optionalAccess', _3 => _3.slice, 'call', _4 => _4(0, 512)]),
167
207
  referrer: document.referrer || void 0,
168
208
  landingUrl: location.href.slice(0, 512),
169
209
  utmSource: readQuery("utm_source"),
@@ -174,6 +214,19 @@ async function activateReplay(args) {
174
214
  fbclid: readQuery("fbclid"),
175
215
  gclid: readQuery("gclid")
176
216
  };
217
+ const onClick = (event) => {
218
+ if (!event.isTrusted || epoch !== activationEpoch) return;
219
+ if (!active) {
220
+ progress.clickCount++;
221
+ return;
222
+ }
223
+ if (active.paused || active.replayBlocked || !active.recordingEnabled) return;
224
+ active.clickCount++;
225
+ saveProgress();
226
+ bumpSessionActivity();
227
+ };
228
+ window.addEventListener("click", onClick, true);
229
+ cleanup.push(() => window.removeEventListener("click", onClick, true));
177
230
  let recordingEnabled = true;
178
231
  try {
179
232
  const res = await postTrace(transportCfg, "/session/start", dto);
@@ -181,9 +234,12 @@ async function activateReplay(args) {
181
234
  const body = await res.json().catch(() => ({}));
182
235
  if (body.recordingEnabled === false) recordingEnabled = false;
183
236
  }
184
- } catch (e8) {
237
+ } catch (e10) {
185
238
  }
239
+ if (epoch !== activationEpoch) return;
186
240
  if (!recordingEnabled) {
241
+ window.removeEventListener("click", onClick, true);
242
+ pendingErrors = [];
187
243
  active = {
188
244
  sessionUid,
189
245
  config: transportCfg,
@@ -197,6 +253,7 @@ async function activateReplay(args) {
197
253
  clickCount: 0,
198
254
  recordingEnabled: false
199
255
  };
256
+ if (pendingUser !== void 0) replayApi.setUser(pendingUser);
200
257
  return;
201
258
  }
202
259
  active = {
@@ -208,10 +265,14 @@ async function activateReplay(args) {
208
265
  paused: false,
209
266
  userId: null,
210
267
  startedAt: dto.startedAt,
211
- pagesVisited: 1,
212
- clickCount: 0,
268
+ pagesVisited: progress.pagesVisited + 1,
269
+ clickCount: progress.clickCount,
213
270
  recordingEnabled: true
214
271
  };
272
+ saveProgress();
273
+ for (const error of pendingErrors) sendError(error);
274
+ pendingErrors = [];
275
+ if (pendingUser !== void 0) replayApi.setUser(pendingUser);
215
276
  let lastSessionBump = Date.now();
216
277
  const bumpIfStale = () => {
217
278
  const now = Date.now();
@@ -221,6 +282,7 @@ async function activateReplay(args) {
221
282
  };
222
283
  for (const ev of ["mousedown", "keydown", "scroll", "touchstart"]) {
223
284
  window.addEventListener(ev, bumpIfStale, { passive: true, capture: true });
285
+ cleanup.push(() => window.removeEventListener(ev, bumpIfStale, true));
224
286
  }
225
287
  const w = window;
226
288
  const scheduleRrwebStart = (run) => {
@@ -244,11 +306,15 @@ async function activateReplay(args) {
244
306
  void Promise.resolve().then(() => _interopRequireWildcard(require("../rrweb-VXG3W6SS.js"))).then(
245
307
  ({ startRrweb }) => new Promise((resolve) => {
246
308
  scheduleRrwebStart(() => {
309
+ if (epoch !== activationEpoch) {
310
+ resolve(null);
311
+ return;
312
+ }
247
313
  startRrweb({
248
314
  sessionUid,
249
315
  options,
250
316
  sendChunk: async (chunk, useBeacon) => {
251
- if (!active || active.replayBlocked) return;
317
+ if (epoch !== activationEpoch || !active || active.replayBlocked) return;
252
318
  const bodyStr = `{"sessionUid":${JSON.stringify(sessionUid)},"chunk":[${chunk.join(",")}]}`;
253
319
  const base = (transportCfg.endpoint || "https://segiapi.extn.ai").replace(/\/+$/, "").replace(/\/api\/ingest\/events$/, "").replace(/\/api\/ingest$/, "").replace(/\/api$/, "");
254
320
  if (useBeacon) {
@@ -260,7 +326,7 @@ async function activateReplay(args) {
260
326
  if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
261
327
  navigator.sendBeacon(url, blob);
262
328
  }
263
- } catch (e9) {
329
+ } catch (e11) {
264
330
  }
265
331
  return;
266
332
  }
@@ -281,18 +347,19 @@ async function activateReplay(args) {
281
347
  if (res.status === 429) {
282
348
  if (active) {
283
349
  active.replayBlocked = true;
284
- _optionalChain([active, 'access', _4 => _4.rrweb, 'optionalAccess', _5 => _5.stop, 'call', _6 => _6()]);
350
+ _optionalChain([active, 'access', _5 => _5.rrweb, 'optionalAccess', _6 => _6.stop, 'call', _7 => _7()]);
285
351
  active.rrweb = null;
286
352
  }
287
353
  }
288
- } catch (e10) {
354
+ } catch (e12) {
289
355
  }
290
356
  }
291
357
  }).then(resolve, () => resolve(null));
292
358
  });
293
359
  })
294
360
  ).then((handles) => {
295
- if (handles && active) active.rrweb = handles;
361
+ if (handles && active && epoch === activationEpoch) active.rrweb = handles;
362
+ else _optionalChain([handles, 'optionalAccess', _8 => _8.stop, 'call', _9 => _9()]);
296
363
  }).catch(() => {
297
364
  });
298
365
  void postTrace(transportCfg, "/events", {
@@ -306,9 +373,9 @@ async function activateReplay(args) {
306
373
  }
307
374
  ]
308
375
  });
309
- window.addEventListener("pagehide", () => {
376
+ const onPageHide = () => {
310
377
  if (!active) return;
311
- _optionalChain([active, 'access', _7 => _7.rrweb, 'optionalAccess', _8 => _8.flush, 'call', _9 => _9(true)]);
378
+ _optionalChain([active, 'access', _10 => _10.rrweb, 'optionalAccess', _11 => _11.flush, 'call', _12 => _12(true)]);
312
379
  beaconTrace(active.config, "/session/end", {
313
380
  sessionUid: active.sessionUid,
314
381
  endedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -316,12 +383,14 @@ async function activateReplay(args) {
316
383
  pagesVisited: active.pagesVisited,
317
384
  clickCount: active.clickCount
318
385
  });
319
- });
386
+ };
387
+ window.addEventListener("pagehide", onPageHide);
388
+ cleanup.push(() => window.removeEventListener("pagehide", onPageHide));
320
389
  const MAX_SESSION_DURATION_MS = 30 * 6e4;
321
- setTimeout(() => {
390
+ const endTimer = setTimeout(() => {
322
391
  if (!active) return;
323
- _optionalChain([active, 'access', _10 => _10.rrweb, 'optionalAccess', _11 => _11.flush, 'call', _12 => _12(true)]);
324
- _optionalChain([active, 'access', _13 => _13.rrweb, 'optionalAccess', _14 => _14.stop, 'call', _15 => _15()]);
392
+ _optionalChain([active, 'access', _13 => _13.rrweb, 'optionalAccess', _14 => _14.flush, 'call', _15 => _15(true)]);
393
+ _optionalChain([active, 'access', _16 => _16.rrweb, 'optionalAccess', _17 => _17.stop, 'call', _18 => _18()]);
325
394
  active.rrweb = null;
326
395
  beaconTrace(active.config, "/session/end", {
327
396
  sessionUid: active.sessionUid,
@@ -332,21 +401,40 @@ async function activateReplay(args) {
332
401
  });
333
402
  active.paused = true;
334
403
  active.replayBlocked = true;
335
- }, MAX_SESSION_DURATION_MS);
404
+ }, Math.max(0, MAX_SESSION_DURATION_MS - (Date.now() - Date.parse(progress.startedAt))));
405
+ cleanup.push(() => clearTimeout(endTimer));
336
406
  }
337
407
  var replayApi = {
408
+ /** Internal bridge from the error SDK; no stack/message is copied to trace. */
409
+ _captureError(signal) {
410
+ if (!active) {
411
+ if (pendingErrors.length < 20) pendingErrors.push(signal);
412
+ return;
413
+ }
414
+ sendError(signal);
415
+ },
416
+ _stop() {
417
+ activationEpoch++;
418
+ _optionalChain([active, 'optionalAccess', _19 => _19.rrweb, 'optionalAccess', _20 => _20.stop, 'call', _21 => _21()]);
419
+ for (const remove of cleanup) remove();
420
+ cleanup = [];
421
+ active = null;
422
+ pendingErrors = [];
423
+ pendingUser = void 0;
424
+ },
338
425
  pause() {
339
- _optionalChain([active, 'optionalAccess', _16 => _16.rrweb, 'optionalAccess', _17 => _17.pause, 'call', _18 => _18()]);
426
+ _optionalChain([active, 'optionalAccess', _22 => _22.rrweb, 'optionalAccess', _23 => _23.pause, 'call', _24 => _24()]);
340
427
  if (active) active.paused = true;
341
428
  },
342
429
  resume() {
343
- _optionalChain([active, 'optionalAccess', _19 => _19.rrweb, 'optionalAccess', _20 => _20.resume, 'call', _21 => _21()]);
430
+ _optionalChain([active, 'optionalAccess', _25 => _25.rrweb, 'optionalAccess', _26 => _26.resume, 'call', _27 => _27()]);
344
431
  if (active) active.paused = false;
345
432
  bumpSessionActivity();
346
433
  },
347
434
  setUser(user) {
435
+ pendingUser = user;
348
436
  if (!active) return;
349
- active.userId = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _22 => _22.id]), () => ( null));
437
+ active.userId = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _28 => _28.id, 'optionalAccess', _29 => _29.slice, 'call', _30 => _30(0, 128)]), () => ( null));
350
438
  void postTrace(active.config, "/session/start", {
351
439
  sessionUid: active.sessionUid,
352
440
  anonId: getOrCreateAnonId(),
@@ -382,17 +470,18 @@ var replayApi = {
382
470
  const nowBlocked = isPathBlocked(active.options, location.pathname);
383
471
  if (nowBlocked) {
384
472
  if (!active.paused) {
385
- _optionalChain([active, 'access', _23 => _23.rrweb, 'optionalAccess', _24 => _24.pause, 'call', _25 => _25()]);
473
+ _optionalChain([active, 'access', _31 => _31.rrweb, 'optionalAccess', _32 => _32.pause, 'call', _33 => _33()]);
386
474
  active.paused = true;
387
475
  }
388
476
  return;
389
477
  }
390
478
  if (active.paused) {
391
- _optionalChain([active, 'access', _26 => _26.rrweb, 'optionalAccess', _27 => _27.resume, 'call', _28 => _28()]);
479
+ _optionalChain([active, 'access', _34 => _34.rrweb, 'optionalAccess', _35 => _35.resume, 'call', _36 => _36()]);
392
480
  active.paused = false;
393
481
  }
394
482
  active.pagesVisited += 1;
395
- _optionalChain([active, 'access', _29 => _29.rrweb, 'optionalAccess', _30 => _30.takeFullSnapshot, 'call', _31 => _31()]);
483
+ saveProgress();
484
+ _optionalChain([active, 'access', _37 => _37.rrweb, 'optionalAccess', _38 => _38.takeFullSnapshot, 'call', _39 => _39()]);
396
485
  void postTrace(active.config, "/events", {
397
486
  events: [
398
487
  {
@@ -407,7 +496,7 @@ var replayApi = {
407
496
  },
408
497
  /** Test seam: returns null when replay was not activated for this session. */
409
498
  _sessionUid() {
410
- return _nullishCoalesce(_optionalChain([active, 'optionalAccess', _32 => _32.sessionUid]), () => ( null));
499
+ return _nullishCoalesce(_optionalChain([active, 'optionalAccess', _40 => _40.sessionUid]), () => ( null));
411
500
  }
412
501
  };
413
502