@eventra_dev/eventra-sdk 2.0.5 → 2.0.7

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.cjs CHANGED
@@ -24,13 +24,180 @@ __export(index_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(index_exports);
26
26
 
27
+ // src/diagnostics.ts
28
+ var DROPPED_REASONS = /* @__PURE__ */ new Set([
29
+ "queue_full",
30
+ "invalid_event",
31
+ "too_large",
32
+ "rejected"
33
+ ]);
34
+ var FAILED_REASONS = /* @__PURE__ */ new Set([
35
+ "network",
36
+ "server_error",
37
+ "rate_limited",
38
+ "circuit_open"
39
+ ]);
40
+ var COUNT_MAX = 1e9;
41
+ var MemoryStore = class {
42
+ constructor() {
43
+ this.data = /* @__PURE__ */ new Map();
44
+ }
45
+ get(key) {
46
+ return this.data.get(key) ?? null;
47
+ }
48
+ set(key, value) {
49
+ this.data.set(key, value);
50
+ }
51
+ };
52
+ var SharedStore = class {
53
+ constructor(storage) {
54
+ this.storage = storage;
55
+ this.memory = new MemoryStore();
56
+ }
57
+ get(key) {
58
+ return this.storage.get(key) ?? this.memory.get(key);
59
+ }
60
+ set(key, value) {
61
+ this.memory.set(key, value);
62
+ this.storage.set(key, value);
63
+ }
64
+ };
65
+ function emptyCounts() {
66
+ return { dropped: 0, failed: 0, byReason: {} };
67
+ }
68
+ function isCount(value) {
69
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= COUNT_MAX;
70
+ }
71
+ function parseCounts(value) {
72
+ if (typeof value !== "object" || value === null) return null;
73
+ const v = value;
74
+ if (!isCount(v.dropped) || !isCount(v.failed)) return null;
75
+ const byReason = {};
76
+ const raw = v.byReason;
77
+ if (typeof raw === "object" && raw !== null) {
78
+ for (const [reason, count] of Object.entries(raw)) {
79
+ if ((DROPPED_REASONS.has(reason) || FAILED_REASONS.has(reason)) && isCount(count)) {
80
+ byReason[reason] = count;
81
+ }
82
+ }
83
+ }
84
+ const since = typeof v.since === "string" && !Number.isNaN(Date.parse(v.since)) ? v.since : void 0;
85
+ return { dropped: v.dropped, failed: v.failed, byReason, since };
86
+ }
87
+ function parseRecord(value) {
88
+ if (typeof value !== "object" || value === null) {
89
+ return { counts: emptyCounts() };
90
+ }
91
+ const v = value;
92
+ const counts = parseCounts(v.counts) ?? emptyCounts();
93
+ let pending;
94
+ const p = v.pending;
95
+ if (typeof p === "object" && p !== null && typeof p.reportId === "string") {
96
+ const pendingCounts = parseCounts(p.counts);
97
+ if (pendingCounts) pending = { reportId: p.reportId, counts: pendingCounts };
98
+ }
99
+ return { counts, pending };
100
+ }
101
+ function total(counts) {
102
+ return counts.dropped + counts.failed;
103
+ }
104
+ function add(into, from) {
105
+ into.dropped = Math.min(COUNT_MAX, into.dropped + from.dropped);
106
+ into.failed = Math.min(COUNT_MAX, into.failed + from.failed);
107
+ for (const [reason, count] of Object.entries(from.byReason)) {
108
+ into.byReason[reason] = Math.min(
109
+ COUNT_MAX,
110
+ (into.byReason[reason] ?? 0) + count
111
+ );
112
+ }
113
+ if (from.since && (!into.since || from.since < into.since)) {
114
+ into.since = from.since;
115
+ }
116
+ }
117
+ var Diagnostics = class {
118
+ constructor(store, key, newId, onChange = () => {
119
+ }) {
120
+ this.store = store;
121
+ this.key = key;
122
+ this.newId = newId;
123
+ this.onChange = onChange;
124
+ // not yet merged into the (possibly shared) record
125
+ this.local = emptyCounts();
126
+ this.dirty = false;
127
+ }
128
+ record(reason, n = 1) {
129
+ if (!(n > 0)) return;
130
+ const isDropped = DROPPED_REASONS.has(reason);
131
+ if (isDropped) {
132
+ this.local.dropped = Math.min(COUNT_MAX, this.local.dropped + n);
133
+ } else if (reason !== "circuit_open") {
134
+ this.local.failed = Math.min(COUNT_MAX, this.local.failed + n);
135
+ }
136
+ this.local.byReason[reason] = Math.min(
137
+ COUNT_MAX,
138
+ (this.local.byReason[reason] ?? 0) + n
139
+ );
140
+ this.local.since ??= (/* @__PURE__ */ new Date()).toISOString();
141
+ this.dirty = true;
142
+ this.onChange();
143
+ }
144
+ // writes the local counters into the shared record (debounced by the client,
145
+ // immediate on pagehide/destroy); a no-op when nothing changed
146
+ sync() {
147
+ if (!this.dirty) return;
148
+ const record = this.read();
149
+ add(record.counts, this.local);
150
+ this.local = emptyCounts();
151
+ this.dirty = false;
152
+ this.store.set(this.key, record);
153
+ }
154
+ // Moves the counters into a pending report and returns it; an unacknowledged
155
+ // pending report is returned again as it is. null when there is nothing to
156
+ // report or another tab claimed the same counters first.
157
+ claim(queued, sdkVersion) {
158
+ this.dirty = this.dirty || total(this.local) > 0;
159
+ this.sync();
160
+ const record = this.read();
161
+ if (!record.pending) {
162
+ if (total(record.counts) === 0) return null;
163
+ const reportId2 = this.newId();
164
+ record.pending = { reportId: reportId2, counts: record.counts };
165
+ record.counts = emptyCounts();
166
+ this.store.set(this.key, record);
167
+ const stored = this.read();
168
+ if (stored.pending?.reportId !== reportId2) return null;
169
+ }
170
+ const { reportId, counts } = record.pending;
171
+ return {
172
+ reportId,
173
+ since: counts.since ?? (/* @__PURE__ */ new Date()).toISOString(),
174
+ droppedTotal: counts.dropped,
175
+ failedTotal: counts.failed,
176
+ byReason: { ...counts.byReason },
177
+ queued,
178
+ sdkVersion
179
+ };
180
+ }
181
+ // the server accepted the batch the report travelled with
182
+ ack(reportId) {
183
+ const record = this.read();
184
+ if (record.pending?.reportId !== reportId) return;
185
+ record.pending = void 0;
186
+ this.store.set(this.key, record);
187
+ }
188
+ read() {
189
+ return parseRecord(this.store.get(this.key));
190
+ }
191
+ };
192
+
27
193
  // src/client.ts
28
194
  var SDK_NAME = "@eventra_dev/eventra-sdk";
29
195
  var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
30
- var SDK_VERSION = "2.0.5";
196
+ var SDK_VERSION = "2.0.7";
31
197
  var LEADER_KEY = "__eventra_leader__";
32
198
  var LEADER_TTL_MS = 4e3;
33
199
  var QUEUE_KEY = "__eventra_q__";
200
+ var DIAGNOSTICS_KEY = "__eventra_d__";
34
201
  var CHANNEL_NAME = "eventra-sdk";
35
202
  var MAX_EVENT_NAME = 64;
36
203
  var MAX_USER_ID = 120;
@@ -41,6 +208,12 @@ var DEFAULT_MAX_RETRY_DELAY_MS = 3e4;
41
208
  var FETCH_TIMEOUT_MS = 5e3;
42
209
  var CIRCUIT_FAILURE_THRESHOLD = 5;
43
210
  var CIRCUIT_COOLDOWN_MS = 5e3;
211
+ var CIRCUIT_COOLDOWN_MAX_MS = 6e4;
212
+ var RETRY_AFTER_MAX_MS = 3e4;
213
+ var PERSIST_DEBOUNCE_MS = 50;
214
+ var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
215
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
216
+ var DELIVERED_KEYS_MAX = 1e4;
44
217
  var activeInstances = 0;
45
218
  function detectRuntime() {
46
219
  const g = globalThis;
@@ -82,9 +255,11 @@ function backoffMs(attempt, base) {
82
255
  const jitter = exp * (0.5 + Math.random() * 0.5);
83
256
  return jitter;
84
257
  }
258
+ var textEncoder;
85
259
  function utf8ByteLength(value) {
86
260
  if (typeof TextEncoder !== "undefined") {
87
- return new TextEncoder().encode(value).length;
261
+ textEncoder ??= new TextEncoder();
262
+ return textEncoder.encode(value).length;
88
263
  }
89
264
  const g = globalThis;
90
265
  if (g.Buffer) {
@@ -105,6 +280,12 @@ function mergeQueues(...queues) {
105
280
  return out;
106
281
  }
107
282
  function validateProperties(properties) {
283
+ let hasKeys = false;
284
+ for (const _ in properties) {
285
+ hasKeys = true;
286
+ break;
287
+ }
288
+ if (!hasKeys) return properties;
108
289
  const depth = (obj, level) => {
109
290
  if (level > MAX_PROPERTIES_DEPTH) {
110
291
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
@@ -127,18 +308,25 @@ function validateProperties(properties) {
127
308
  }
128
309
  return properties;
129
310
  }
130
- function estimateEnvelopeBytes(events, sdk, sentAt) {
131
- return utf8ByteLength(
132
- JSON.stringify({
133
- sentAt,
134
- sdk,
135
- events
136
- })
137
- );
311
+ function parseRetryAfterMs(value) {
312
+ if (!value) return void 0;
313
+ const trimmed = value.trim();
314
+ let ms;
315
+ if (/^\d+$/.test(trimmed)) {
316
+ ms = Number(trimmed) * 1e3;
317
+ } else {
318
+ const at = Date.parse(trimmed);
319
+ if (Number.isNaN(at)) return void 0;
320
+ ms = at - Date.now();
321
+ }
322
+ if (!(ms > 0)) return void 0;
323
+ return Math.min(ms, RETRY_AFTER_MAX_MS);
138
324
  }
139
325
  var RetryableDeliveryError = class extends Error {
140
- constructor(message = "retryable delivery error") {
326
+ constructor(message = "retryable delivery error", retryAfterMs, reason = "server_error") {
141
327
  super(message);
328
+ this.retryAfterMs = retryAfterMs;
329
+ this.reason = reason;
142
330
  this.name = "RetryableDeliveryError";
143
331
  }
144
332
  };
@@ -301,6 +489,17 @@ var Eventra = class {
301
489
  this.failureCount = 0;
302
490
  this.circuitOpenUntil = 0;
303
491
  this.circuitHalfOpen = false;
492
+ // consecutive times the circuit opened without a success in between; drives
493
+ // the exponential cooldown
494
+ this.circuitOpenCount = 0;
495
+ this.flushPromise = null;
496
+ this.persistDirty = false;
497
+ this.deliveredKeys = /* @__PURE__ */ new Set();
498
+ // a 429/5xx Retry-After that outlives the last attempt also delays the next
499
+ // flush (timer, size trigger, manual); shutdown() ignores it
500
+ this.nextFlushAt = 0;
501
+ // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
502
+ this.shutdownDeadline = 0;
304
503
  this.exitHandlers = [];
305
504
  if (!options.apiKey) throw new Error("Eventra: apiKey required");
306
505
  activeInstances++;
@@ -324,6 +523,14 @@ var Eventra = class {
324
523
  this.retries = options.maxRetries ?? 3;
325
524
  this.retryDelay = options.retryBaseDelayMs ?? 300;
326
525
  this.persistQueue = options.persistQueue ?? true;
526
+ this.diagnosticsEnabled = options.diagnostics !== false;
527
+ const shared = this.runtime === "browser" && this.persistQueue;
528
+ this.diagnostics = new Diagnostics(
529
+ shared ? new SharedStore(this.storage) : new MemoryStore(),
530
+ DIAGNOSTICS_KEY,
531
+ uuidV4,
532
+ shared ? () => this.scheduleDiagnosticsSync() : void 0
533
+ );
327
534
  this.sdkInfo = {
328
535
  name: SDK_NAME,
329
536
  version: SDK_VERSION,
@@ -354,6 +561,7 @@ var Eventra = class {
354
561
  if (this.destroyed || this.shuttingDown) return;
355
562
  const eventName = normalizeEventName(name);
356
563
  if (eventName === null) {
564
+ this.recordDiagnostic("invalid_event");
357
565
  this.options.onEventsDropped?.(1);
358
566
  return;
359
567
  }
@@ -361,10 +569,12 @@ var Eventra = class {
361
569
  try {
362
570
  properties = validateProperties(options?.properties ?? {});
363
571
  } catch {
572
+ this.recordDiagnostic("invalid_event");
364
573
  this.options.onEventsDropped?.(1);
365
574
  return;
366
575
  }
367
576
  if (this.queue.length >= this.maxQueue) {
577
+ this.recordDiagnostic("queue_full");
368
578
  this.options.onEventsDropped?.(1);
369
579
  return;
370
580
  }
@@ -377,7 +587,8 @@ var Eventra = class {
377
587
  };
378
588
  this.queue.push(event);
379
589
  if (this.runtime === "browser") {
380
- this.syncQueue();
590
+ this.schedulePersist();
591
+ this.broadcast({ type: "queue-add", events: [event] });
381
592
  }
382
593
  if (this.queue.length >= this.maxBatch) {
383
594
  void this.flush();
@@ -387,8 +598,14 @@ var Eventra = class {
387
598
  }
388
599
  }
389
600
  async flush() {
601
+ return this.flushNow(false);
602
+ }
603
+ // `force` skips only the Retry-After delay (the last chance at shutdown);
604
+ // the circuit breaker still applies
605
+ async flushNow(force) {
390
606
  if (this.inFlight || this.destroyed) return;
391
607
  if (!this.queue.length && !this.sending?.length) return;
608
+ if (!force && Date.now() < this.nextFlushAt) return;
392
609
  if (this.leader && !this.leader.canSend()) return;
393
610
  const now = Date.now();
394
611
  if (now < this.circuitOpenUntil) return;
@@ -397,21 +614,46 @@ var Eventra = class {
397
614
  this.circuitOpenUntil = 0;
398
615
  }
399
616
  this.inFlight = true;
617
+ const run = this.runFlush();
618
+ this.flushPromise = run;
619
+ try {
620
+ await run;
621
+ } finally {
622
+ this.flushPromise = null;
623
+ }
624
+ }
625
+ async runFlush() {
400
626
  try {
401
627
  while (this.queue.length > 0) {
402
- const batch = this.buildBatch();
403
- if (!batch.length) break;
404
- this.sending = batch;
628
+ const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
629
+ const batch = this.buildBatch(report);
630
+ if (!batch.events.length) break;
631
+ this.sending = batch.events;
405
632
  try {
406
- await this.send(batch);
407
- this.removeDelivered(batch);
633
+ const accepted = await this.send(batch);
634
+ if (accepted && batch.diagnostics) {
635
+ this.diagnostics.ack(batch.diagnostics.reportId);
636
+ }
637
+ this.removeDelivered(batch.events);
638
+ this.nextFlushAt = 0;
408
639
  this.failureCount = 0;
409
640
  this.circuitHalfOpen = false;
641
+ this.circuitOpenCount = 0;
410
642
  } catch (err) {
411
643
  if (err instanceof RetryableDeliveryError) {
644
+ this.recordDiagnostic(err.reason);
645
+ if (err.retryAfterMs) {
646
+ this.nextFlushAt = Date.now() + err.retryAfterMs;
647
+ }
412
648
  this.failureCount++;
413
649
  if (this.circuitHalfOpen || this.failureCount >= CIRCUIT_FAILURE_THRESHOLD) {
414
- this.circuitOpenUntil = Date.now() + CIRCUIT_COOLDOWN_MS;
650
+ this.recordDiagnostic("circuit_open");
651
+ const cooldown = Math.min(
652
+ CIRCUIT_COOLDOWN_MAX_MS,
653
+ CIRCUIT_COOLDOWN_MS * 2 ** this.circuitOpenCount
654
+ );
655
+ this.circuitOpenCount++;
656
+ this.circuitOpenUntil = Date.now() + Math.max(cooldown, err.retryAfterMs ?? 0);
415
657
  this.circuitHalfOpen = false;
416
658
  }
417
659
  break;
@@ -422,28 +664,44 @@ var Eventra = class {
422
664
  }
423
665
  if (this.circuitOpenUntil > Date.now()) break;
424
666
  }
425
- if (this.runtime === "browser") {
426
- this.syncQueue();
427
- }
428
667
  } finally {
429
668
  this.inFlight = false;
430
669
  }
431
670
  }
432
- /** Flush pending events, then tear down timers and listeners */
671
+ /**
672
+ * Flush pending events, then tear down timers and listeners. Gives up after
673
+ * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
674
+ * hold a SIGTERM shutdown past a typical grace period.
675
+ */
433
676
  async shutdown() {
434
677
  if (this.shuttingDown) return;
435
678
  this.shuttingDown = true;
679
+ const budget = this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
680
+ this.shutdownDeadline = Date.now() + Math.max(0, budget);
681
+ let budgetTimer;
682
+ const outOfTime = new Promise((resolve) => {
683
+ budgetTimer = setTimeout(resolve, Math.max(0, budget));
684
+ budgetTimer.unref?.();
685
+ });
436
686
  try {
437
- await this.flush();
687
+ await Promise.race([this.flushEverything(), outOfTime]);
438
688
  } finally {
689
+ clearTimeout(budgetTimer);
439
690
  this.destroy();
440
691
  }
441
692
  }
693
+ async flushEverything() {
694
+ if (this.flushPromise) {
695
+ await this.flushPromise;
696
+ }
697
+ await this.flushNow(true);
698
+ }
442
699
  destroy() {
443
700
  if (this.destroyed) return;
444
701
  this.destroyed = true;
445
702
  activeInstances = Math.max(0, activeInstances - 1);
446
703
  if (this.timer) clearInterval(this.timer);
704
+ this.persistNow();
447
705
  this.leader?.destroy();
448
706
  if (this.channel) {
449
707
  this.channel.close();
@@ -456,65 +714,92 @@ var Eventra = class {
456
714
  off();
457
715
  }
458
716
  }
459
- buildBatch() {
460
- const batch = [];
717
+ buildBatch(report) {
718
+ const events = [];
719
+ const json = [];
461
720
  const sentAt = (/* @__PURE__ */ new Date()).toISOString();
721
+ const envelopeBytes = (withReport2) => utf8ByteLength(
722
+ JSON.stringify({
723
+ sentAt,
724
+ sdk: this.sdkInfo,
725
+ ...withReport2 && report ? { diagnostics: report } : {},
726
+ events: []
727
+ })
728
+ );
729
+ let withReport = report !== null;
730
+ let bytes = envelopeBytes(withReport);
462
731
  let index = 0;
463
- while (index < this.queue.length && batch.length < this.maxBatch) {
732
+ while (index < this.queue.length && events.length < this.maxBatch) {
464
733
  const event = this.queue[index];
465
- const candidate = [...batch, event];
466
- const bytes = estimateEnvelopeBytes(candidate, this.sdkInfo, sentAt);
467
- if (bytes > this.maxPayloadBytes) {
468
- if (batch.length === 0) {
469
- const poisonKey = event.idempotencyKey;
470
- this.dropPoisonEvent(event);
471
- if (this.queue[index]?.idempotencyKey === poisonKey) {
472
- index++;
734
+ const eventJson = JSON.stringify(event);
735
+ const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
736
+ if (total2 > this.maxPayloadBytes) {
737
+ if (events.length === 0) {
738
+ if (withReport) {
739
+ withReport = false;
740
+ bytes = envelopeBytes(false);
741
+ continue;
473
742
  }
743
+ this.dropPoisonEvent(event);
744
+ withReport = report !== null;
745
+ bytes = envelopeBytes(withReport);
474
746
  continue;
475
747
  }
476
748
  break;
477
749
  }
478
- batch.push(event);
750
+ events.push(event);
751
+ json.push(eventJson);
752
+ bytes = total2;
479
753
  index++;
480
754
  }
481
- return batch;
755
+ return {
756
+ events,
757
+ json,
758
+ bytes,
759
+ diagnostics: withReport && report ? report : void 0
760
+ };
482
761
  }
483
762
  dropPoisonEvent(event) {
763
+ this.recordDiagnostic("too_large");
484
764
  this.removeDelivered([event]);
485
765
  this.options.onEventsDropped?.(1);
486
766
  this.options.onDeliveryFailed?.({ status: 413, events: [event] });
487
- if (this.runtime === "browser") {
488
- this.syncQueue();
489
- }
490
767
  }
491
768
  removeDelivered(batch) {
492
769
  const keys = new Set(batch.map((e) => e.idempotencyKey));
493
770
  this.queue = this.queue.filter((e) => !keys.has(e.idempotencyKey));
771
+ if (this.runtime === "browser") {
772
+ this.rememberDelivered(keys);
773
+ this.schedulePersist();
774
+ this.broadcast({ type: "delivered", keys: [...keys] });
775
+ }
494
776
  }
495
- async send(events) {
496
- let payload;
497
- try {
498
- payload = JSON.stringify({
777
+ // Resolves true only when the server answered 2xx for a payload that
778
+ // carried the diagnostics report (the only case that acknowledges it).
779
+ async send(batch) {
780
+ const { events } = batch;
781
+ let carriesDiagnostics = batch.diagnostics !== void 0;
782
+ const buildPayload = (withDiagnostics) => {
783
+ const head = JSON.stringify({
499
784
  sentAt: (/* @__PURE__ */ new Date()).toISOString(),
500
785
  sdk: this.sdkInfo,
501
- events
786
+ ...withDiagnostics && batch.diagnostics ? { diagnostics: batch.diagnostics } : {}
502
787
  });
503
- } catch {
504
- this.options.onDeliveryFailed?.({ status: 0, events });
505
- this.removeDelivered(events);
506
- return;
507
- }
508
- const payloadBytes = utf8ByteLength(payload);
788
+ return `${head.slice(0, -1)},"events":[${batch.json.join(",")}]}`;
789
+ };
790
+ let payload = buildPayload(carriesDiagnostics);
791
+ const payloadBytes = batch.bytes;
509
792
  if (payloadBytes > this.maxPayloadBytes) {
510
793
  this.dropPoisonEvents(events);
511
- return;
794
+ return false;
512
795
  }
513
796
  const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" && payloadBytes <= this.maxPayloadBytes;
514
- const maxAttempts = Math.max(1, this.retries);
797
+ const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
798
+ let strippedDiagnostics = false;
515
799
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
516
800
  const controller = new AbortController();
517
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
801
+ const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
802
+ const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
518
803
  try {
519
804
  const res = await this.fetch(this.endpoint, {
520
805
  method: "POST",
@@ -527,27 +812,47 @@ var Eventra = class {
527
812
  keepalive: useKeepalive
528
813
  });
529
814
  if (res.status === 429 || res.status >= 500) {
530
- throw new RetryableDeliveryError();
815
+ throw new RetryableDeliveryError(
816
+ "retryable delivery error",
817
+ parseRetryAfterMs(res.headers?.get?.("retry-after")),
818
+ res.status === 429 ? "rate_limited" : "server_error"
819
+ );
531
820
  }
532
821
  if (res.status >= 400 && res.status < 500) {
822
+ if (carriesDiagnostics && (res.status === 400 || res.status === 422)) {
823
+ carriesDiagnostics = false;
824
+ strippedDiagnostics = true;
825
+ payload = buildPayload(false);
826
+ attempt--;
827
+ continue;
828
+ }
829
+ this.recordDiagnostic("rejected", events.length);
533
830
  this.options.onDeliveryFailed?.({ status: res.status, events });
534
831
  this.removeDelivered(events);
535
- return;
832
+ return false;
536
833
  }
537
834
  if (!res.ok) {
538
835
  throw new RetryableDeliveryError();
539
836
  }
540
- return;
837
+ if (strippedDiagnostics) {
838
+ this.diagnosticsEnabled = false;
839
+ return false;
840
+ }
841
+ return carriesDiagnostics;
541
842
  } catch (err) {
542
843
  const isLast = attempt >= maxAttempts - 1;
543
- if (isLast) {
544
- throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError();
844
+ const retryAfter = err instanceof RetryableDeliveryError ? err.retryAfterMs : void 0;
845
+ const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);
846
+ const outOfBudget = this.shutdownDeadline > 0 && Date.now() + wait >= this.shutdownDeadline;
847
+ if (isLast || outOfBudget) {
848
+ throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
545
849
  }
546
- await sleep(backoffMs(attempt + 1, this.retryDelay));
850
+ await sleep(wait);
547
851
  } finally {
548
852
  clearTimeout(timeout);
549
853
  }
550
854
  }
855
+ return false;
551
856
  }
552
857
  // Only caller is the defensive re-check in send() above, which is itself
553
858
  // unreachable in practice (see comment there) — see the same file's
@@ -559,39 +864,87 @@ var Eventra = class {
559
864
  }
560
865
  }
561
866
  /* v8 ignore stop */
867
+ recordDiagnostic(reason, n = 1) {
868
+ if (this.diagnosticsEnabled) this.diagnostics.record(reason, n);
869
+ }
870
+ // counters reach localStorage on the same debounce as the queue
871
+ scheduleDiagnosticsSync() {
872
+ if (this.persistTimer !== void 0) return;
873
+ this.persistTimer = setTimeout(() => {
874
+ this.persistTimer = void 0;
875
+ this.persistNow();
876
+ }, PERSIST_DEBOUNCE_MS);
877
+ }
562
878
  loadAndMergeQueue() {
563
879
  const remote = this.storage.get(QUEUE_KEY);
564
880
  if (Array.isArray(remote)) {
565
- this.queue = mergeQueues(this.queue, remote);
881
+ const fresh = this.withoutExpired(remote);
882
+ if (fresh.length !== remote.length) this.persistDirty = true;
883
+ this.queue = mergeQueues(this.queue, this.withoutDelivered(fresh));
566
884
  }
567
- this.trimQueue();
885
+ this.queue = this.trimQueue();
568
886
  }
569
- syncQueue() {
570
- if (this.persistQueue) {
571
- const remote = this.storage.get(QUEUE_KEY);
572
- const merged = mergeQueues(
573
- Array.isArray(remote) ? remote : [],
574
- this.queue
575
- );
576
- this.queue = this.trimQueue(merged);
577
- this.storage.set(QUEUE_KEY, this.queue);
578
- } else {
579
- this.queue = this.trimQueue();
887
+ // events whose timestamp is unreadable are kept: their age cannot be judged
888
+ withoutExpired(events) {
889
+ const oldest = Date.now() - PERSISTED_EVENT_MAX_AGE_MS;
890
+ return events.filter((e) => {
891
+ const at = Date.parse(e?.timestamp);
892
+ return Number.isNaN(at) || at >= oldest;
893
+ });
894
+ }
895
+ withoutDelivered(events) {
896
+ if (!this.deliveredKeys.size) return events;
897
+ return events.filter((e) => !this.deliveredKeys.has(e.idempotencyKey));
898
+ }
899
+ rememberDelivered(keys) {
900
+ for (const key of keys) this.deliveredKeys.add(key);
901
+ for (const key of this.deliveredKeys) {
902
+ if (this.deliveredKeys.size <= DELIVERED_KEYS_MAX) break;
903
+ this.deliveredKeys.delete(key);
580
904
  }
581
- this.broadcastQueue();
905
+ }
906
+ // Burst of track() calls = one write. Reading, merging and rewriting the
907
+ // whole queue on every call made each call cost O(queue size).
908
+ schedulePersist() {
909
+ if (!this.persistQueue) return;
910
+ this.persistDirty = true;
911
+ if (this.persistTimer !== void 0) return;
912
+ this.persistTimer = setTimeout(() => {
913
+ this.persistTimer = void 0;
914
+ this.persistNow();
915
+ }, PERSIST_DEBOUNCE_MS);
916
+ }
917
+ // Immediate write of the pending state (pagehide, tab hidden, destroy).
918
+ // Merges what other tabs wrote first, so concurrent tabs never overwrite
919
+ // each other's events; delivered events are filtered out so they stay gone.
920
+ persistNow() {
921
+ if (this.persistTimer !== void 0) {
922
+ clearTimeout(this.persistTimer);
923
+ this.persistTimer = void 0;
924
+ }
925
+ this.diagnostics.sync();
926
+ if (!this.persistQueue || !this.persistDirty) return;
927
+ this.persistDirty = false;
928
+ const remote = this.storage.get(QUEUE_KEY);
929
+ const merged = mergeQueues(
930
+ Array.isArray(remote) ? this.withoutDelivered(this.withoutExpired(remote)) : [],
931
+ this.queue
932
+ );
933
+ this.queue = this.trimQueue(merged);
934
+ this.storage.set(QUEUE_KEY, this.queue);
582
935
  }
583
936
  trimQueue(queue = this.queue) {
584
937
  if (queue.length <= this.maxQueue) return queue;
585
938
  const dropped = queue.length - this.maxQueue;
939
+ this.recordDiagnostic("queue_full", dropped);
586
940
  this.options.onEventsDropped?.(dropped);
587
941
  return queue.slice(-this.maxQueue);
588
942
  }
589
- broadcastQueue() {
943
+ // Sends only what changed (a new event, or the keys just delivered) instead
944
+ // of structured-cloning the whole queue on every call.
945
+ broadcast(message) {
590
946
  try {
591
- this.channel?.postMessage({
592
- type: "queue-sync",
593
- events: this.queue
594
- });
947
+ this.channel?.postMessage(message);
595
948
  } catch {
596
949
  }
597
950
  }
@@ -599,8 +952,17 @@ var Eventra = class {
599
952
  if (typeof BroadcastChannel !== "undefined") {
600
953
  this.channel = new BroadcastChannel(CHANNEL_NAME);
601
954
  this.channel.onmessage = (e) => {
602
- if (e.data?.type !== "queue-sync" || !Array.isArray(e.data.events)) return;
603
- this.queue = mergeQueues(this.queue, e.data.events);
955
+ const data = e.data;
956
+ if (data?.type === "delivered" && Array.isArray(data.keys)) {
957
+ const keys = new Set(data.keys);
958
+ this.rememberDelivered(keys);
959
+ this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
960
+ return;
961
+ }
962
+ if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
963
+ return;
964
+ }
965
+ this.queue = mergeQueues(this.queue, this.withoutDelivered(data.events));
604
966
  this.queue = this.trimQueue();
605
967
  };
606
968
  }
@@ -616,14 +978,17 @@ var Eventra = class {
616
978
  this.timer = setInterval(() => {
617
979
  void this.flush();
618
980
  }, this.flushInterval);
981
+ this.timer.unref?.();
619
982
  }
620
983
  setupBrowserExit() {
621
984
  const handler = () => {
622
985
  if (document.visibilityState === "hidden") {
986
+ this.persistNow();
623
987
  void this.flush();
624
988
  }
625
989
  };
626
990
  const pageHide = () => {
991
+ this.persistNow();
627
992
  void this.flush();
628
993
  };
629
994
  document.addEventListener("visibilitychange", handler);
@@ -636,14 +1001,31 @@ var Eventra = class {
636
1001
  setupProcessExit() {
637
1002
  const proc = globalThis.process;
638
1003
  if (!proc?.on) return;
639
- const onSignal = () => {
640
- void this.shutdown();
1004
+ const exitOnSignal = this.options.exitOnSignal === true;
1005
+ const onSignal = (signal) => () => {
1006
+ void this.shutdown().finally(() => {
1007
+ if (!exitOnSignal) return;
1008
+ proc.off?.(signal, handlers[signal]);
1009
+ const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
1010
+ if (!othersListening && proc.kill && proc.pid !== void 0) {
1011
+ proc.kill(proc.pid, signal);
1012
+ }
1013
+ });
1014
+ };
1015
+ const handlers = {
1016
+ SIGINT: onSignal("SIGINT"),
1017
+ SIGTERM: onSignal("SIGTERM")
1018
+ };
1019
+ const onBeforeExit = () => {
1020
+ if (this.queue.length) void this.flush();
641
1021
  };
642
- proc.once("SIGINT", onSignal);
643
- proc.once("SIGTERM", onSignal);
1022
+ proc.once("SIGINT", handlers.SIGINT);
1023
+ proc.once("SIGTERM", handlers.SIGTERM);
1024
+ proc.once("beforeExit", onBeforeExit);
644
1025
  this.exitHandlers.push(() => {
645
- proc.off?.("SIGINT", onSignal);
646
- proc.off?.("SIGTERM", onSignal);
1026
+ proc.off?.("SIGINT", handlers.SIGINT);
1027
+ proc.off?.("SIGTERM", handlers.SIGTERM);
1028
+ proc.off?.("beforeExit", onBeforeExit);
647
1029
  });
648
1030
  }
649
1031
  };