@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.
@@ -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 (p?.sessionUid === sessionUid && Number.isFinite(Date.parse(p.startedAt)) && [p.clickCount, p.pagesVisited].every((n) => Number.isSafeInteger(n) && n >= 0)) return p;
13
+ } catch {
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 {
21
+ }
22
+ }
8
23
  function uuid() {
9
24
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
10
25
  return crypto.randomUUID();
@@ -37,7 +52,7 @@ function writeSession(uid, at) {
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
  }
@@ -123,6 +138,29 @@ async function gzipString(str) {
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;
@@ -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, 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: options.endpoint ?? args.endpoint,
157
197
  projectKey: args.projectKey
@@ -159,7 +199,7 @@ 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,
@@ -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);
@@ -183,7 +236,10 @@ async function activateReplay(args) {
183
236
  }
184
237
  } catch {
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 import("../rrweb-O2KFXCVA.mjs").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) {
@@ -292,7 +358,8 @@ async function activateReplay(args) {
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 handles?.stop();
296
363
  }).catch(() => {
297
364
  });
298
365
  void postTrace(transportCfg, "/events", {
@@ -306,7 +373,7 @@ async function activateReplay(args) {
306
373
  }
307
374
  ]
308
375
  });
309
- window.addEventListener("pagehide", () => {
376
+ const onPageHide = () => {
310
377
  if (!active) return;
311
378
  active.rrweb?.flush(true);
312
379
  beaconTrace(active.config, "/session/end", {
@@ -316,9 +383,11 @@ 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
392
  active.rrweb?.flush(true);
324
393
  active.rrweb?.stop();
@@ -332,9 +401,27 @@ 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
+ active?.rrweb?.stop();
419
+ for (const remove of cleanup) remove();
420
+ cleanup = [];
421
+ active = null;
422
+ pendingErrors = [];
423
+ pendingUser = void 0;
424
+ },
338
425
  pause() {
339
426
  active?.rrweb?.pause();
340
427
  if (active) active.paused = true;
@@ -345,8 +432,9 @@ var replayApi = {
345
432
  bumpSessionActivity();
346
433
  },
347
434
  setUser(user) {
435
+ pendingUser = user;
348
436
  if (!active) return;
349
- active.userId = user?.id ?? null;
437
+ active.userId = user?.id?.slice(0, 128) ?? null;
350
438
  void postTrace(active.config, "/session/start", {
351
439
  sessionUid: active.sessionUid,
352
440
  anonId: getOrCreateAnonId(),
@@ -392,6 +480,7 @@ var replayApi = {
392
480
  active.paused = false;
393
481
  }
394
482
  active.pagesVisited += 1;
483
+ saveProgress();
395
484
  active.rrweb?.takeFullSnapshot();
396
485
  void postTrace(active.config, "/events", {
397
486
  events: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extn/segi-js",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "Browser JavaScript SDK for the segi error monitoring service",
5
5
  "license": "UNLICENSED",
6
6
  "main": "./dist/index.js",
@@ -37,6 +37,7 @@
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsup",
40
+ "test:browser": "node test/browser-runtime.cjs",
40
41
  "dev": "tsup --watch",
41
42
  "typecheck": "tsc -p tsconfig.json --noEmit",
42
43
  "clean": "rm -rf dist"