@extn/segi-js 0.2.15 → 0.2.17

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.
@@ -88,11 +88,12 @@ function normalizeBase(endpoint) {
88
88
  const raw = endpoint && endpoint.trim() || DEFAULT_API_BASE;
89
89
  return raw.replace(/\/+$/, "").replace(/\/api\/ingest\/events$/, "").replace(/\/api\/ingest$/, "").replace(/\/api$/, "");
90
90
  }
91
- async function postTrace(cfg, path, body) {
91
+ async function postTrace(cfg, path, body, signal) {
92
92
  const url = `${normalizeBase(cfg.endpoint)}/api/trace${path}`;
93
93
  try {
94
94
  const res = await fetch(url, {
95
95
  method: "POST",
96
+ signal,
96
97
  headers: {
97
98
  "Content-Type": "application/json",
98
99
  "X-Segi-Project-Key": cfg.projectKey
@@ -151,7 +152,12 @@ function saveProgress() {
151
152
  });
152
153
  }
153
154
  function sendError(signal) {
154
- if (!active || !active.recordingEnabled || active.paused) return;
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
+ }
155
161
  void postTrace(active.config, "/events", { events: [{
156
162
  sessionUid: active.sessionUid,
157
163
  ts: signal.ts,
@@ -180,14 +186,98 @@ function isPathBlocked(opts, path) {
180
186
  const list = opts.blockRoutes ?? [];
181
187
  return list.some((p) => path.startsWith(p));
182
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
+ }
183
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) {
184
276
  if (active) return;
185
277
  if (typeof window === "undefined") return;
186
278
  const epoch = ++activationEpoch;
187
279
  const options = args.config.options;
188
280
  if (options.enabled === false) return;
189
- const sample = Math.max(0, Math.min(100, options.sample ?? 100));
190
- if (Math.random() * 100 >= sample) return;
191
281
  if (isPathBlocked(options, location.pathname)) return;
192
282
  const sessionUid = getOrCreateSessionUid();
193
283
  const anonId = getOrCreateAnonId();
@@ -216,6 +306,7 @@ async function activateReplay(args) {
216
306
  };
217
307
  const onClick = (event) => {
218
308
  if (!event.isTrusted || epoch !== activationEpoch) return;
309
+ if (!pathAllowed() || manualPaused) return;
219
310
  if (!active) {
220
311
  progress.clickCount++;
221
312
  return;
@@ -227,12 +318,12 @@ async function activateReplay(args) {
227
318
  };
228
319
  window.addEventListener("click", onClick, true);
229
320
  cleanup.push(() => window.removeEventListener("click", onClick, true));
230
- let recordingEnabled = true;
321
+ let recordingEnabled = false;
231
322
  try {
232
323
  const res = await postTrace(transportCfg, "/session/start", dto);
233
324
  if (res && res.ok) {
234
325
  const body = await res.json().catch(() => ({}));
235
- if (body.recordingEnabled === false) recordingEnabled = false;
326
+ recordingEnabled = body.recordingEnabled === true;
236
327
  }
237
328
  } catch {
238
329
  }
@@ -247,6 +338,7 @@ async function activateReplay(args) {
247
338
  rrweb: null,
248
339
  replayBlocked: false,
249
340
  paused: true,
341
+ routePaused: false,
250
342
  userId: null,
251
343
  startedAt: dto.startedAt,
252
344
  pagesVisited: 0,
@@ -262,10 +354,11 @@ async function activateReplay(args) {
262
354
  options,
263
355
  rrweb: null,
264
356
  replayBlocked: false,
265
- paused: false,
357
+ paused: manualPaused || !pathAllowed(),
358
+ routePaused: !pathAllowed(),
266
359
  userId: null,
267
360
  startedAt: dto.startedAt,
268
- pagesVisited: progress.pagesVisited + 1,
361
+ pagesVisited: progress.pagesVisited + (pathAllowed() ? 1 : 0),
269
362
  clickCount: progress.clickCount,
270
363
  recordingEnabled: true
271
364
  };
@@ -303,7 +396,7 @@ async function activateReplay(args) {
303
396
  setTimeout(onIdle, 5e3);
304
397
  }
305
398
  };
306
- void import("../rrweb-O2KFXCVA.mjs").then(
399
+ void import("../rrweb-I4V7NHNY.mjs").then(
307
400
  ({ startRrweb }) => new Promise((resolve) => {
308
401
  scheduleRrwebStart(() => {
309
402
  if (epoch !== activationEpoch) {
@@ -313,6 +406,7 @@ async function activateReplay(args) {
313
406
  startRrweb({
314
407
  sessionUid,
315
408
  options,
409
+ shouldRecord: canCollect,
316
410
  sendChunk: async (chunk, useBeacon) => {
317
411
  if (epoch !== activationEpoch || !active || active.replayBlocked) return;
318
412
  const bodyStr = `{"sessionUid":${JSON.stringify(sessionUid)},"chunk":[${chunk.join(",")}]}`;
@@ -358,11 +452,13 @@ async function activateReplay(args) {
358
452
  });
359
453
  })
360
454
  ).then((handles) => {
361
- if (handles && active && epoch === activationEpoch) active.rrweb = handles;
362
- else handles?.stop();
455
+ if (handles && active && epoch === activationEpoch) {
456
+ active.rrweb = handles;
457
+ if (!canCollect()) handles.pause();
458
+ } else handles?.stop();
363
459
  }).catch(() => {
364
460
  });
365
- void postTrace(transportCfg, "/events", {
461
+ if (canCollect()) void postTrace(transportCfg, "/events", {
366
462
  events: [
367
463
  {
368
464
  sessionUid,
@@ -407,6 +503,7 @@ async function activateReplay(args) {
407
503
  var replayApi = {
408
504
  /** Internal bridge from the error SDK; no stack/message is copied to trace. */
409
505
  _captureError(signal) {
506
+ if (configured && !pathAllowed()) return;
410
507
  if (!active) {
411
508
  if (pendingErrors.length < 20) pendingErrors.push(signal);
412
509
  return;
@@ -415,6 +512,10 @@ var replayApi = {
415
512
  },
416
513
  _stop() {
417
514
  activationEpoch++;
515
+ waiting = null;
516
+ configured = false;
517
+ manualPaused = false;
518
+ starting = false;
418
519
  active?.rrweb?.stop();
419
520
  for (const remove of cleanup) remove();
420
521
  cleanup = [];
@@ -423,17 +524,23 @@ var replayApi = {
423
524
  pendingUser = void 0;
424
525
  },
425
526
  pause() {
527
+ manualPaused = true;
426
528
  active?.rrweb?.pause();
427
529
  if (active) active.paused = true;
428
530
  },
429
531
  resume() {
430
- active?.rrweb?.resume();
431
- 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();
432
539
  bumpSessionActivity();
433
540
  },
434
541
  setUser(user) {
435
542
  pendingUser = user;
436
- if (!active) return;
543
+ if (!active || !canCollect()) return;
437
544
  active.userId = user?.id?.slice(0, 128) ?? null;
438
545
  void postTrace(active.config, "/session/start", {
439
546
  sessionUid: active.sessionUid,
@@ -446,7 +553,7 @@ var replayApi = {
446
553
  });
447
554
  },
448
555
  event(name, meta) {
449
- if (!active || active.paused) return;
556
+ if (!active || !canCollect()) return;
450
557
  void postTrace(active.config, "/events", {
451
558
  events: [
452
559
  {
@@ -465,19 +572,27 @@ var replayApi = {
465
572
  * Bumps the page-views counter and emits a fresh page_view event.
466
573
  */
467
574
  notifyRouteChange(url, title) {
468
- if (!active) return;
575
+ if (!active) {
576
+ void startWhenAllowed();
577
+ return;
578
+ }
579
+ if (!active.recordingEnabled || active.replayBlocked) return;
469
580
  bumpSessionActivity();
470
581
  const nowBlocked = isPathBlocked(active.options, location.pathname);
471
582
  if (nowBlocked) {
583
+ active.routePaused = true;
472
584
  if (!active.paused) {
473
585
  active.rrweb?.pause();
474
586
  active.paused = true;
475
587
  }
476
588
  return;
477
589
  }
478
- if (active.paused) {
479
- active.rrweb?.resume();
590
+ if (manualPaused) return;
591
+ if (active.routePaused) {
592
+ active.routePaused = false;
480
593
  active.paused = false;
594
+ active.rrweb?.resume();
595
+ if (pendingUser !== void 0) replayApi.setUser(pendingUser);
481
596
  }
482
597
  active.pagesVisited += 1;
483
598
  saveProgress();
@@ -501,6 +616,7 @@ var replayApi = {
501
616
  };
502
617
  export {
503
618
  activateReplay,
619
+ isPathBlocked,
504
620
  replayApi,
505
621
  withReplay
506
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.15",
3
+ "version": "0.2.17",
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": "node --test test/normalize-error.test.cjs",
40
41
  "test:browser": "node test/browser-runtime.cjs",
41
42
  "dev": "tsup --watch",
42
43
  "typecheck": "tsc -p tsconfig.json --noEmit",