@extn/segi-js 0.2.14 → 0.2.16

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
  }
@@ -73,11 +88,12 @@ function normalizeBase(endpoint) {
73
88
  const raw = endpoint && endpoint.trim() || DEFAULT_API_BASE;
74
89
  return raw.replace(/\/+$/, "").replace(/\/api\/ingest\/events$/, "").replace(/\/api\/ingest$/, "").replace(/\/api$/, "");
75
90
  }
76
- async function postTrace(cfg, path, body) {
91
+ async function postTrace(cfg, path, body, signal) {
77
92
  const url = `${normalizeBase(cfg.endpoint)}/api/trace${path}`;
78
93
  try {
79
94
  const res = await fetch(url, {
80
95
  method: "POST",
96
+ signal,
81
97
  headers: {
82
98
  "Content-Type": "application/json",
83
99
  "X-Segi-Project-Key": cfg.projectKey
@@ -123,6 +139,33 @@ async function gzipString(str) {
123
139
  }
124
140
  }
125
141
  var active = null;
142
+ var activationEpoch = 0;
143
+ var cleanup = [];
144
+ var pendingErrors = [];
145
+ function saveProgress() {
146
+ if (!active) return;
147
+ writeReplayProgress({
148
+ sessionUid: active.sessionUid,
149
+ startedAt: active.startedAt,
150
+ clickCount: active.clickCount,
151
+ pagesVisited: active.pagesVisited
152
+ });
153
+ }
154
+ function sendError(signal) {
155
+ if (!canCollect() || !active) return;
156
+ try {
157
+ if (isPathBlocked(active.options, new URL(signal.url ?? location.href, location.href).pathname)) return;
158
+ } catch {
159
+ return;
160
+ }
161
+ void postTrace(active.config, "/events", { events: [{
162
+ sessionUid: active.sessionUid,
163
+ ts: signal.ts,
164
+ url: signal.url,
165
+ type: "error",
166
+ name: "sdk_error"
167
+ }] });
168
+ }
126
169
  var pendingUser = void 0;
127
170
  function deviceClass() {
128
171
  if (typeof window === "undefined") return "desktop";
@@ -143,16 +186,102 @@ function isPathBlocked(opts, path) {
143
186
  const list = opts.blockRoutes ?? [];
144
187
  return list.some((p) => path.startsWith(p));
145
188
  }
189
+ var waiting = null;
190
+ var starting = false;
191
+ var configured = false;
192
+ var manualPaused = false;
193
+ function pathAllowed() {
194
+ return !!waiting && configured && !isPathBlocked(waiting.config.options, location.pathname);
195
+ }
196
+ function canCollect() {
197
+ return pathAllowed() && !!active && active.recordingEnabled && !active.paused && !active.replayBlocked;
198
+ }
199
+ async function startWhenAllowed() {
200
+ if (!waiting || active || starting || !pathAllowed() || manualPaused) return;
201
+ starting = true;
202
+ try {
203
+ await startReplay(waiting);
204
+ } finally {
205
+ starting = false;
206
+ }
207
+ }
146
208
  async function activateReplay(args) {
209
+ if (waiting || typeof window === "undefined" || args.config.options.enabled === false) return;
210
+ const sample = Math.max(0, Math.min(100, args.config.options.sample ?? 100));
211
+ if (Math.random() * 100 >= sample) return;
212
+ waiting = args;
213
+ const epoch = activationEpoch;
214
+ const suspendExcluded = () => {
215
+ if (active && !pathAllowed()) {
216
+ active.routePaused = true;
217
+ active.paused = true;
218
+ active.rrweb?.pause();
219
+ }
220
+ };
221
+ for (const method of ["pushState", "replaceState"]) {
222
+ const original = history[method];
223
+ const wrapped = function(...params) {
224
+ original.apply(this, params);
225
+ suspendExcluded();
226
+ };
227
+ history[method] = wrapped;
228
+ cleanup.push(() => {
229
+ if (history[method] === wrapped) history[method] = original;
230
+ });
231
+ }
232
+ window.addEventListener("popstate", suspendExcluded);
233
+ cleanup.push(() => window.removeEventListener("popstate", suspendExcluded));
234
+ let inFlight = false;
235
+ const load = async () => {
236
+ if (inFlight || configured || epoch !== activationEpoch) return;
237
+ inFlight = true;
238
+ const controller = new AbortController();
239
+ const timeout = setTimeout(() => controller.abort(), 1e4);
240
+ try {
241
+ const res = await postTrace({ projectKey: args.projectKey, endpoint: args.config.options.endpoint ?? args.endpoint }, "/config", {}, controller.signal);
242
+ if (!res?.ok) return;
243
+ const policy = await res.json();
244
+ if (epoch !== activationEpoch || typeof policy.recordingEnabled !== "boolean" || !Array.isArray(policy.recordingDenyList) || policy.recordingDenyList.some((p) => typeof p !== "string" || !p.startsWith("/"))) return;
245
+ configured = true;
246
+ clearInterval(timer);
247
+ waiting = { ...args, config: withReplay({
248
+ ...args.config.options,
249
+ blockRoutes: [...args.config.options.blockRoutes ?? [], ...policy.recordingDenyList]
250
+ }) };
251
+ if (!policy.recordingEnabled) {
252
+ waiting = null;
253
+ return;
254
+ }
255
+ pendingErrors = pendingErrors.filter((e) => {
256
+ try {
257
+ return !isPathBlocked(waiting.config.options, new URL(e.url ?? location.href, location.href).pathname);
258
+ } catch {
259
+ return false;
260
+ }
261
+ });
262
+ await startWhenAllowed();
263
+ } catch {
264
+ } finally {
265
+ clearTimeout(timeout);
266
+ inFlight = false;
267
+ }
268
+ };
269
+ const timer = setInterval(() => {
270
+ void load();
271
+ }, 3e4);
272
+ cleanup.push(() => clearInterval(timer));
273
+ await load();
274
+ }
275
+ async function startReplay(args) {
147
276
  if (active) return;
148
277
  if (typeof window === "undefined") return;
278
+ const epoch = ++activationEpoch;
149
279
  const options = args.config.options;
150
280
  if (options.enabled === false) return;
151
- const sample = Math.max(0, Math.min(100, options.sample ?? 100));
152
- if (Math.random() * 100 >= sample) return;
153
281
  if (isPathBlocked(options, location.pathname)) return;
154
282
  const sessionUid = getOrCreateSessionUid();
155
283
  const anonId = getOrCreateAnonId();
284
+ const progress = readReplayProgress(sessionUid);
156
285
  const transportCfg = {
157
286
  endpoint: options.endpoint ?? args.endpoint,
158
287
  projectKey: args.projectKey
@@ -160,7 +289,7 @@ async function activateReplay(args) {
160
289
  const dto = {
161
290
  sessionUid,
162
291
  anonId,
163
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
292
+ startedAt: progress.startedAt,
164
293
  device: deviceClass(),
165
294
  viewportW: window.innerWidth,
166
295
  viewportH: window.innerHeight,
@@ -175,16 +304,33 @@ async function activateReplay(args) {
175
304
  fbclid: readQuery("fbclid"),
176
305
  gclid: readQuery("gclid")
177
306
  };
178
- let recordingEnabled = true;
307
+ const onClick = (event) => {
308
+ if (!event.isTrusted || epoch !== activationEpoch) return;
309
+ if (!pathAllowed() || manualPaused) return;
310
+ if (!active) {
311
+ progress.clickCount++;
312
+ return;
313
+ }
314
+ if (active.paused || active.replayBlocked || !active.recordingEnabled) return;
315
+ active.clickCount++;
316
+ saveProgress();
317
+ bumpSessionActivity();
318
+ };
319
+ window.addEventListener("click", onClick, true);
320
+ cleanup.push(() => window.removeEventListener("click", onClick, true));
321
+ let recordingEnabled = false;
179
322
  try {
180
323
  const res = await postTrace(transportCfg, "/session/start", dto);
181
324
  if (res && res.ok) {
182
325
  const body = await res.json().catch(() => ({}));
183
- if (body.recordingEnabled === false) recordingEnabled = false;
326
+ recordingEnabled = body.recordingEnabled === true;
184
327
  }
185
328
  } catch {
186
329
  }
330
+ if (epoch !== activationEpoch) return;
187
331
  if (!recordingEnabled) {
332
+ window.removeEventListener("click", onClick, true);
333
+ pendingErrors = [];
188
334
  active = {
189
335
  sessionUid,
190
336
  config: transportCfg,
@@ -192,6 +338,7 @@ async function activateReplay(args) {
192
338
  rrweb: null,
193
339
  replayBlocked: false,
194
340
  paused: true,
341
+ routePaused: false,
195
342
  userId: null,
196
343
  startedAt: dto.startedAt,
197
344
  pagesVisited: 0,
@@ -207,13 +354,17 @@ async function activateReplay(args) {
207
354
  options,
208
355
  rrweb: null,
209
356
  replayBlocked: false,
210
- paused: false,
357
+ paused: manualPaused || !pathAllowed(),
358
+ routePaused: !pathAllowed(),
211
359
  userId: null,
212
360
  startedAt: dto.startedAt,
213
- pagesVisited: 1,
214
- clickCount: 0,
361
+ pagesVisited: progress.pagesVisited + (pathAllowed() ? 1 : 0),
362
+ clickCount: progress.clickCount,
215
363
  recordingEnabled: true
216
364
  };
365
+ saveProgress();
366
+ for (const error of pendingErrors) sendError(error);
367
+ pendingErrors = [];
217
368
  if (pendingUser !== void 0) replayApi.setUser(pendingUser);
218
369
  let lastSessionBump = Date.now();
219
370
  const bumpIfStale = () => {
@@ -224,6 +375,7 @@ async function activateReplay(args) {
224
375
  };
225
376
  for (const ev of ["mousedown", "keydown", "scroll", "touchstart"]) {
226
377
  window.addEventListener(ev, bumpIfStale, { passive: true, capture: true });
378
+ cleanup.push(() => window.removeEventListener(ev, bumpIfStale, true));
227
379
  }
228
380
  const w = window;
229
381
  const scheduleRrwebStart = (run) => {
@@ -244,14 +396,19 @@ async function activateReplay(args) {
244
396
  setTimeout(onIdle, 5e3);
245
397
  }
246
398
  };
247
- void import("../rrweb-O2KFXCVA.mjs").then(
399
+ void import("../rrweb-I4V7NHNY.mjs").then(
248
400
  ({ startRrweb }) => new Promise((resolve) => {
249
401
  scheduleRrwebStart(() => {
402
+ if (epoch !== activationEpoch) {
403
+ resolve(null);
404
+ return;
405
+ }
250
406
  startRrweb({
251
407
  sessionUid,
252
408
  options,
409
+ shouldRecord: canCollect,
253
410
  sendChunk: async (chunk, useBeacon) => {
254
- if (!active || active.replayBlocked) return;
411
+ if (epoch !== activationEpoch || !active || active.replayBlocked) return;
255
412
  const bodyStr = `{"sessionUid":${JSON.stringify(sessionUid)},"chunk":[${chunk.join(",")}]}`;
256
413
  const base = (transportCfg.endpoint || "https://segiapi.extn.ai").replace(/\/+$/, "").replace(/\/api\/ingest\/events$/, "").replace(/\/api\/ingest$/, "").replace(/\/api$/, "");
257
414
  if (useBeacon) {
@@ -295,10 +452,13 @@ async function activateReplay(args) {
295
452
  });
296
453
  })
297
454
  ).then((handles) => {
298
- if (handles && active) active.rrweb = handles;
455
+ if (handles && active && epoch === activationEpoch) {
456
+ active.rrweb = handles;
457
+ if (!canCollect()) handles.pause();
458
+ } else handles?.stop();
299
459
  }).catch(() => {
300
460
  });
301
- void postTrace(transportCfg, "/events", {
461
+ if (canCollect()) void postTrace(transportCfg, "/events", {
302
462
  events: [
303
463
  {
304
464
  sessionUid,
@@ -309,7 +469,7 @@ async function activateReplay(args) {
309
469
  }
310
470
  ]
311
471
  });
312
- window.addEventListener("pagehide", () => {
472
+ const onPageHide = () => {
313
473
  if (!active) return;
314
474
  active.rrweb?.flush(true);
315
475
  beaconTrace(active.config, "/session/end", {
@@ -319,9 +479,11 @@ async function activateReplay(args) {
319
479
  pagesVisited: active.pagesVisited,
320
480
  clickCount: active.clickCount
321
481
  });
322
- });
482
+ };
483
+ window.addEventListener("pagehide", onPageHide);
484
+ cleanup.push(() => window.removeEventListener("pagehide", onPageHide));
323
485
  const MAX_SESSION_DURATION_MS = 30 * 6e4;
324
- setTimeout(() => {
486
+ const endTimer = setTimeout(() => {
325
487
  if (!active) return;
326
488
  active.rrweb?.flush(true);
327
489
  active.rrweb?.stop();
@@ -335,21 +497,50 @@ async function activateReplay(args) {
335
497
  });
336
498
  active.paused = true;
337
499
  active.replayBlocked = true;
338
- }, MAX_SESSION_DURATION_MS);
500
+ }, Math.max(0, MAX_SESSION_DURATION_MS - (Date.now() - Date.parse(progress.startedAt))));
501
+ cleanup.push(() => clearTimeout(endTimer));
339
502
  }
340
503
  var replayApi = {
504
+ /** Internal bridge from the error SDK; no stack/message is copied to trace. */
505
+ _captureError(signal) {
506
+ if (configured && !pathAllowed()) return;
507
+ if (!active) {
508
+ if (pendingErrors.length < 20) pendingErrors.push(signal);
509
+ return;
510
+ }
511
+ sendError(signal);
512
+ },
513
+ _stop() {
514
+ activationEpoch++;
515
+ waiting = null;
516
+ configured = false;
517
+ manualPaused = false;
518
+ starting = false;
519
+ active?.rrweb?.stop();
520
+ for (const remove of cleanup) remove();
521
+ cleanup = [];
522
+ active = null;
523
+ pendingErrors = [];
524
+ pendingUser = void 0;
525
+ },
341
526
  pause() {
527
+ manualPaused = true;
342
528
  active?.rrweb?.pause();
343
529
  if (active) active.paused = true;
344
530
  },
345
531
  resume() {
346
- active?.rrweb?.resume();
347
- if (active) active.paused = false;
532
+ manualPaused = false;
533
+ if (!pathAllowed() || active?.replayBlocked || active?.recordingEnabled === false) return;
534
+ if (active) {
535
+ active.paused = false;
536
+ active.routePaused = false;
537
+ active.rrweb?.resume();
538
+ } else void startWhenAllowed();
348
539
  bumpSessionActivity();
349
540
  },
350
541
  setUser(user) {
351
542
  pendingUser = user;
352
- if (!active) return;
543
+ if (!active || !canCollect()) return;
353
544
  active.userId = user?.id?.slice(0, 128) ?? null;
354
545
  void postTrace(active.config, "/session/start", {
355
546
  sessionUid: active.sessionUid,
@@ -362,7 +553,7 @@ var replayApi = {
362
553
  });
363
554
  },
364
555
  event(name, meta) {
365
- if (!active || active.paused) return;
556
+ if (!active || !canCollect()) return;
366
557
  void postTrace(active.config, "/events", {
367
558
  events: [
368
559
  {
@@ -381,21 +572,30 @@ var replayApi = {
381
572
  * Bumps the page-views counter and emits a fresh page_view event.
382
573
  */
383
574
  notifyRouteChange(url, title) {
384
- if (!active) return;
575
+ if (!active) {
576
+ void startWhenAllowed();
577
+ return;
578
+ }
579
+ if (!active.recordingEnabled || active.replayBlocked) return;
385
580
  bumpSessionActivity();
386
581
  const nowBlocked = isPathBlocked(active.options, location.pathname);
387
582
  if (nowBlocked) {
583
+ active.routePaused = true;
388
584
  if (!active.paused) {
389
585
  active.rrweb?.pause();
390
586
  active.paused = true;
391
587
  }
392
588
  return;
393
589
  }
394
- if (active.paused) {
395
- active.rrweb?.resume();
590
+ if (manualPaused) return;
591
+ if (active.routePaused) {
592
+ active.routePaused = false;
396
593
  active.paused = false;
594
+ active.rrweb?.resume();
595
+ if (pendingUser !== void 0) replayApi.setUser(pendingUser);
397
596
  }
398
597
  active.pagesVisited += 1;
598
+ saveProgress();
399
599
  active.rrweb?.takeFullSnapshot();
400
600
  void postTrace(active.config, "/events", {
401
601
  events: [
@@ -416,6 +616,7 @@ var replayApi = {
416
616
  };
417
617
  export {
418
618
  activateReplay,
619
+ isPathBlocked,
419
620
  replayApi,
420
621
  withReplay
421
622
  };
@@ -47,10 +47,10 @@ async function startRrweb(args) {
47
47
  }
48
48
  }, IDLE_CHECK_MS);
49
49
  function startRecorder() {
50
- if (stopFn) return;
50
+ if (stopFn || args.shouldRecord?.() === false) return;
51
51
  const stop = rrweb.record({
52
52
  emit(event) {
53
- if (paused || stopped) return;
53
+ if (paused || stopped || args.shouldRecord?.() === false) return;
54
54
  let serialized;
55
55
  try {
56
56
  serialized = JSON.stringify(event);
@@ -81,7 +81,7 @@ async function startRrweb(args) {
81
81
  });
82
82
  stopFn = typeof stop === "function" ? stop : null;
83
83
  const forceSnapshot = () => {
84
- if (stopped || paused) return;
84
+ if (stopped || paused || args.shouldRecord?.() === false) return;
85
85
  try {
86
86
  const rrwebMod = rrweb;
87
87
  if (typeof rrwebMod.record.takeFullSnapshot === "function") {
@@ -157,7 +157,7 @@ async function startRrweb(args) {
157
157
  },
158
158
  flush,
159
159
  takeFullSnapshot() {
160
- if (stopped || paused) return;
160
+ if (stopped || paused || args.shouldRecord?.() === false) return;
161
161
  try {
162
162
  const rec = rrweb.record;
163
163
  rec.takeFullSnapshot?.();
@@ -47,10 +47,10 @@ async function startRrweb(args) {
47
47
  }
48
48
  }, IDLE_CHECK_MS);
49
49
  function startRecorder() {
50
- if (stopFn) return;
50
+ if (stopFn || _optionalChain([args, 'access', _7 => _7.shouldRecord, 'optionalCall', _8 => _8()]) === false) return;
51
51
  const stop = rrweb.record({
52
52
  emit(event) {
53
- if (paused || stopped) return;
53
+ if (paused || stopped || _optionalChain([args, 'access', _9 => _9.shouldRecord, 'optionalCall', _10 => _10()]) === false) return;
54
54
  let serialized;
55
55
  try {
56
56
  serialized = JSON.stringify(event);
@@ -81,7 +81,7 @@ async function startRrweb(args) {
81
81
  });
82
82
  stopFn = typeof stop === "function" ? stop : null;
83
83
  const forceSnapshot = () => {
84
- if (stopped || paused) return;
84
+ if (stopped || paused || _optionalChain([args, 'access', _11 => _11.shouldRecord, 'optionalCall', _12 => _12()]) === false) return;
85
85
  try {
86
86
  const rrwebMod = rrweb;
87
87
  if (typeof rrwebMod.record.takeFullSnapshot === "function") {
@@ -98,7 +98,7 @@ async function startRrweb(args) {
98
98
  }
99
99
  function stopRrwebOnly() {
100
100
  try {
101
- _optionalChain([stopFn, 'optionalCall', _7 => _7()]);
101
+ _optionalChain([stopFn, 'optionalCall', _13 => _13()]);
102
102
  } finally {
103
103
  stopFn = null;
104
104
  }
@@ -157,10 +157,10 @@ async function startRrweb(args) {
157
157
  },
158
158
  flush,
159
159
  takeFullSnapshot() {
160
- if (stopped || paused) return;
160
+ if (stopped || paused || _optionalChain([args, 'access', _14 => _14.shouldRecord, 'optionalCall', _15 => _15()]) === false) return;
161
161
  try {
162
162
  const rec = rrweb.record;
163
- _optionalChain([rec, 'access', _8 => _8.takeFullSnapshot, 'optionalCall', _9 => _9()]);
163
+ _optionalChain([rec, 'access', _16 => _16.takeFullSnapshot, 'optionalCall', _17 => _17()]);
164
164
  } catch (e5) {
165
165
  }
166
166
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extn/segi-js",
3
- "version": "0.2.14",
3
+ "version": "0.2.16",
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"