@eventra_dev/eventra-sdk 2.0.11 → 2.0.13

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.mjs CHANGED
@@ -167,7 +167,7 @@ var Diagnostics = class {
167
167
  // src/client.ts
168
168
  var SDK_NAME = "@eventra_dev/eventra-sdk";
169
169
  var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
170
- var SDK_VERSION = "2.0.11";
170
+ var SDK_VERSION = "2.0.13";
171
171
  var LEADER_KEY = "__eventra_leader__";
172
172
  var LEADER_TTL_MS = 4e3;
173
173
  var QUEUE_KEY = "__eventra_q__";
@@ -187,42 +187,155 @@ var RETRY_AFTER_MAX_MS = 3e4;
187
187
  var PERSIST_DEBOUNCE_MS = 50;
188
188
  var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
189
189
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
190
+ var PERSISTED_QUEUE_MAX_CHARS = 1e6;
191
+ var KEEPALIVE_MAX_BYTES = 6e4;
190
192
  var DELIVERED_KEYS_MAX = 1e4;
191
193
  var activeInstances = 0;
192
194
  function detectRuntime() {
193
195
  const g = globalThis;
194
- if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
195
196
  if (g.EdgeRuntime) return "edge";
197
+ if (hasBrowserEvents()) return "browser";
196
198
  if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
197
199
  if (g.process?.versions?.node) return "node";
198
200
  return "unknown";
199
201
  }
202
+ function hasBrowserEvents() {
203
+ try {
204
+ return typeof window !== "undefined" && window !== null && typeof window.addEventListener === "function" && typeof document !== "undefined" && document !== null && typeof document.addEventListener === "function";
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+ function listen(target, type, listener) {
210
+ const t = target;
211
+ try {
212
+ if (!t || typeof t.addEventListener !== "function") return () => void 0;
213
+ t.addEventListener(type, listener);
214
+ } catch {
215
+ return () => void 0;
216
+ }
217
+ return () => {
218
+ try {
219
+ t.removeEventListener?.(type, listener);
220
+ } catch {
221
+ }
222
+ };
223
+ }
200
224
  function uuidV4() {
201
225
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
202
226
  return crypto.randomUUID();
203
227
  }
204
228
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
205
- const bytes = new Uint8Array(16);
206
- crypto.getRandomValues(bytes);
207
- bytes[6] = bytes[6] & 15 | 64;
208
- bytes[8] = bytes[8] & 63 | 128;
209
- const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
210
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
211
- }
212
- throw new Error("Eventra: crypto API unavailable \u2014 cannot generate idempotencyKey");
229
+ const bytes2 = new Uint8Array(16);
230
+ crypto.getRandomValues(bytes2);
231
+ bytes2[6] = bytes2[6] & 15 | 64;
232
+ bytes2[8] = bytes2[8] & 63 | 128;
233
+ const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
234
+ return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
235
+ }
236
+ const bytes = new Uint8Array(16);
237
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
238
+ let t = Date.now();
239
+ for (let i = 0; i < 6; i++) {
240
+ bytes[i] ^= t & 255;
241
+ t = Math.floor(t / 256);
242
+ }
243
+ bytes[6] = bytes[6] & 15 | 64;
244
+ bytes[8] = bytes[8] & 63 | 128;
245
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
246
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
247
+ }
248
+ var MAX_TIMER_MS = 2147483647;
249
+ var MAX_RETRIES = 20;
250
+ var MAX_BATCH_SIZE = 500;
251
+ function isUrl(value) {
252
+ try {
253
+ new URL(value);
254
+ return true;
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+ function warnOption(name, value, fallback) {
260
+ if (typeof console !== "undefined") {
261
+ console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
262
+ }
263
+ }
264
+ function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
265
+ if (value === void 0) return fallback;
266
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
267
+ warnOption(name, value, fallback);
268
+ return fallback;
269
+ }
270
+ function callSafely(callback, ...args) {
271
+ if (!callback) return;
272
+ try {
273
+ const result = callback(...args);
274
+ if (result && typeof result.catch === "function") {
275
+ result.catch(() => void 0);
276
+ }
277
+ } catch {
278
+ }
279
+ }
280
+ function raceAbort(request, signal) {
281
+ return new Promise((resolve, reject) => {
282
+ const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
283
+ signal.addEventListener("abort", onAbort, { once: true });
284
+ request.then(
285
+ (value) => {
286
+ signal.removeEventListener("abort", onAbort);
287
+ resolve(value);
288
+ },
289
+ (error) => {
290
+ signal.removeEventListener("abort", onAbort);
291
+ reject(error);
292
+ }
293
+ );
294
+ });
295
+ }
296
+ function discardBody(res) {
297
+ try {
298
+ const closing = res.body?.cancel?.();
299
+ if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
300
+ } catch {
301
+ }
213
302
  }
214
303
  function sleep(ms) {
215
304
  return new Promise((r) => setTimeout(r, ms));
216
305
  }
217
- function truncate(value, max) {
218
- if (value === void 0) return void 0;
219
- return value.length > max ? value.slice(0, max) : value;
306
+ function cut(value, max) {
307
+ if (value.length <= max) return value;
308
+ const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
309
+ return value.slice(0, end);
310
+ }
311
+ function normalizeUserId(value, max) {
312
+ if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
313
+ if (typeof value !== "string") return void 0;
314
+ return cut(value, max);
315
+ }
316
+ function stripUnsafeForName(value) {
317
+ let out = "";
318
+ for (let i = 0; i < value.length; i++) {
319
+ const code = value.charCodeAt(i);
320
+ if (code === 0 || code === 10 || code === 13) continue;
321
+ if (code >= 55296 && code <= 56319) {
322
+ const next = value.charCodeAt(i + 1);
323
+ if (next >= 56320 && next <= 57343) {
324
+ out += value[i] + value[i + 1];
325
+ i++;
326
+ }
327
+ continue;
328
+ }
329
+ if (code >= 56320 && code <= 57343) continue;
330
+ out += value[i];
331
+ }
332
+ return out;
220
333
  }
221
334
  function normalizeEventName(name) {
222
335
  if (typeof name !== "string") return null;
223
- const trimmed = name.trim();
336
+ const trimmed = stripUnsafeForName(name).trim();
224
337
  if (!trimmed) return null;
225
- return trimmed.length > MAX_EVENT_NAME ? trimmed.slice(0, MAX_EVENT_NAME) : trimmed;
338
+ return cut(trimmed, MAX_EVENT_NAME).trimEnd();
226
339
  }
227
340
  function backoffMs(attempt, base) {
228
341
  const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
@@ -241,46 +354,83 @@ function utf8ByteLength(value) {
241
354
  }
242
355
  return value.length;
243
356
  }
357
+ function isStoredEvent(e) {
358
+ if (e === null || typeof e !== "object") return false;
359
+ const ev = e;
360
+ return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 && typeof ev.name === "string" && ev.name.length > 0 && ev.name.length <= MAX_EVENT_NAME && typeof ev.timestamp === "string" && (ev.userId === void 0 || typeof ev.userId === "string" && ev.userId.length <= MAX_USER_ID) && (ev.properties === void 0 || ev.properties !== null && typeof ev.properties === "object" && !Array.isArray(ev.properties));
361
+ }
244
362
  function mergeQueues(...queues) {
245
363
  const seen = /* @__PURE__ */ new Set();
246
364
  const out = [];
247
365
  for (const q of queues) {
248
366
  for (const e of q) {
367
+ if (!isStoredEvent(e)) continue;
249
368
  if (seen.has(e.idempotencyKey)) continue;
250
369
  seen.add(e.idempotencyKey);
251
- out.push(e);
370
+ out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
252
371
  }
253
372
  }
254
373
  return out;
255
374
  }
256
- function validateProperties(properties) {
257
- let hasKeys = false;
258
- for (const _ in properties) {
259
- hasKeys = true;
260
- break;
375
+ function persistedQueueJson(queue) {
376
+ const parts = [];
377
+ let chars = 2;
378
+ for (let i = queue.length - 1; i >= 0; i--) {
379
+ let json;
380
+ try {
381
+ json = JSON.stringify(queue[i]);
382
+ } catch {
383
+ continue;
384
+ }
385
+ const next = chars + json.length + (parts.length ? 1 : 0);
386
+ if (next > PERSISTED_QUEUE_MAX_CHARS) break;
387
+ parts.push(json);
388
+ chars = next;
261
389
  }
262
- if (!hasKeys) return properties;
263
- const depth = (obj, level) => {
390
+ return `[${parts.reverse().join(",")}]`;
391
+ }
392
+ var MAX_PROPERTIES_NODES = 5e4;
393
+ function validateProperties(properties) {
394
+ if (properties === null || typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
395
+ Object.prototype.toString.call(properties) !== "[object Object]") {
396
+ throw new Error("Eventra: properties must be an object");
397
+ }
398
+ const topKeys = Object.keys(properties);
399
+ if (topKeys.length === 0) return {};
400
+ let visited = 0;
401
+ const depth = (obj, level, keys) => {
264
402
  if (level > MAX_PROPERTIES_DEPTH) {
265
403
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
266
404
  }
405
+ if (++visited > MAX_PROPERTIES_NODES) {
406
+ throw new Error("Eventra: properties are too large to check");
407
+ }
267
408
  if (obj === null || typeof obj !== "object") return;
268
409
  if (Array.isArray(obj)) {
410
+ if (visited + obj.length > MAX_PROPERTIES_NODES) {
411
+ throw new Error("Eventra: properties are too large to check");
412
+ }
269
413
  for (const item of obj) depth(item, level + 1);
270
414
  return;
271
415
  }
272
- for (const value of Object.values(obj)) {
273
- depth(value, level + 1);
416
+ const own = keys ?? Object.keys(obj);
417
+ if (visited + own.length > MAX_PROPERTIES_NODES) {
418
+ throw new Error("Eventra: properties are too large to check");
274
419
  }
420
+ for (const key of own) depth(obj[key], level + 1);
275
421
  };
276
- depth(properties, 0);
422
+ depth(properties, 0, topKeys);
277
423
  const json = JSON.stringify(properties);
278
- if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
424
+ if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
279
425
  throw new Error(
280
426
  `Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
281
427
  );
282
428
  }
283
- return properties;
429
+ const copy = JSON.parse(json);
430
+ if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
431
+ throw new Error("Eventra: properties must be an object");
432
+ }
433
+ return copy;
284
434
  }
285
435
  function parseRetryAfterMs(value) {
286
436
  if (!value) return void 0;
@@ -325,9 +475,18 @@ var Storage = class {
325
475
  }
326
476
  }
327
477
  set(key, value) {
478
+ let json;
479
+ try {
480
+ json = JSON.stringify(value);
481
+ } catch {
482
+ return;
483
+ }
484
+ this.setRaw(key, json);
485
+ }
486
+ setRaw(key, json) {
328
487
  if (!this.enabled) return;
329
488
  try {
330
- localStorage.setItem(key, JSON.stringify(value));
489
+ localStorage.setItem(key, json);
331
490
  } catch {
332
491
  }
333
492
  }
@@ -345,23 +504,27 @@ var Storage = class {
345
504
  }
346
505
  /* v8 ignore stop */
347
506
  };
507
+ function storageAvailable() {
508
+ try {
509
+ return typeof localStorage !== "undefined" && localStorage !== null;
510
+ } catch {
511
+ return false;
512
+ }
513
+ }
348
514
  var Leader = class {
349
515
  constructor(onLeadershipChange) {
350
516
  this.onLeadershipChange = onLeadershipChange;
351
517
  this.tabId = uuidV4();
352
518
  this.isLeader = false;
353
- if (typeof localStorage === "undefined") {
519
+ if (!storageAvailable()) {
354
520
  this.isLeader = true;
355
521
  return;
356
522
  }
357
523
  this.tick();
358
524
  this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
359
- if (typeof window !== "undefined") {
360
- this.onStorage = (e) => {
361
- if (e.key === LEADER_KEY) this.tick();
362
- };
363
- window.addEventListener("storage", this.onStorage);
364
- }
525
+ this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
526
+ if (e.key === LEADER_KEY) this.tick();
527
+ });
365
528
  }
366
529
  tick() {
367
530
  const was = this.isLeader;
@@ -434,10 +597,8 @@ var Leader = class {
434
597
  destroy() {
435
598
  if (this.election) clearInterval(this.election);
436
599
  if (this.heartbeat) clearInterval(this.heartbeat);
437
- if (this.onStorage && typeof window !== "undefined") {
438
- window.removeEventListener("storage", this.onStorage);
439
- }
440
- if (this.isLeader && typeof localStorage !== "undefined") {
600
+ this.offStorage?.();
601
+ if (this.isLeader && storageAvailable()) {
441
602
  try {
442
603
  const raw = localStorage.getItem(LEADER_KEY);
443
604
  if (raw) {
@@ -496,70 +657,131 @@ var Eventra = class {
496
657
  this.nextFlushAt = 0;
497
658
  // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
498
659
  this.shutdownDeadline = 0;
660
+ this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
661
+ // the page is being left (`pagehide`)
662
+ this.leaving = false;
499
663
  this.exitHandlers = [];
500
- if (!options.apiKey) throw new Error("Eventra: apiKey required");
664
+ if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
665
+ throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
666
+ }
667
+ if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
668
+ throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
669
+ }
670
+ if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
671
+ throw new Error("Eventra: fetchImpl must be a function");
672
+ }
501
673
  activeInstances++;
502
674
  if (activeInstances > 1 && typeof console !== "undefined") {
503
675
  console.warn(
504
- "Eventra: multiple SDK instances detected \u2014 duplicate timers and sends are possible"
676
+ "Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
505
677
  );
506
678
  }
507
- this.options = options;
508
- this.apiKey = options.apiKey;
509
- this.endpoint = options.endpoint ?? DEFAULT_ENDPOINT;
510
- this.runtime = detectRuntime();
511
- warnIfInsecureEndpoint(this.endpoint);
512
- this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
513
- if (!this.fetch) {
514
- throw new Error("Eventra: fetch not available \u2014 provide fetchImpl");
515
- }
516
- this.maxBatch = options.maxBatchSize ?? 50;
517
- this.maxQueue = options.maxQueueSize ?? 1e4;
518
- this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
519
- this.flushInterval = options.flushInterval ?? 2e3;
520
- this.retries = options.maxRetries ?? 3;
521
- this.retryDelay = options.retryBaseDelayMs ?? 300;
522
- this.persistQueue = options.persistQueue ?? true;
523
- this.diagnosticsEnabled = options.diagnostics !== false;
524
- const shared = this.runtime === "browser" && this.persistQueue;
525
- this.diagnostics = new Diagnostics(
526
- shared ? new SharedStore(this.storage) : new MemoryStore(),
527
- DIAGNOSTICS_KEY,
528
- uuidV4,
529
- shared ? () => this.scheduleDiagnosticsSync() : void 0
530
- );
531
- this.sdkInfo = {
532
- name: SDK_NAME,
533
- version: SDK_VERSION,
534
- runtime: this.runtime
535
- };
536
- if (this.runtime === "browser") {
537
- if (this.persistQueue) {
538
- this.loadAndMergeQueue();
679
+ try {
680
+ this.options = options;
681
+ this.apiKey = options.apiKey;
682
+ if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
683
+ warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
539
684
  }
540
- this.setupQueueSync();
541
- }
542
- if (this.runtime === "browser" && options.multiTabMode === "leader") {
543
- this.leader = new Leader((isLeader) => {
544
- if (isLeader) void this.flush();
545
- });
546
- }
547
- if (!options.disableTimer) {
548
- this.startTimer();
549
- }
550
- if (this.runtime === "browser") {
551
- this.setupBrowserExit();
552
- }
553
- if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
554
- this.setupProcessExit();
685
+ this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
686
+ if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
687
+ warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
688
+ this.endpoint = DEFAULT_ENDPOINT;
689
+ }
690
+ if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
691
+ warnOption("multiTabMode", options.multiTabMode, "independent");
692
+ }
693
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
694
+ warnOption("diagnostics", options.diagnostics, "true");
695
+ }
696
+ for (const name of ["maxBatchSize", "maxQueueSize"]) {
697
+ const value = options[name];
698
+ if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
699
+ warnOption(name, value, Math.floor(value));
700
+ }
701
+ }
702
+ this.runtime = detectRuntime();
703
+ warnIfInsecureEndpoint(this.endpoint);
704
+ this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
705
+ if (!this.fetch) {
706
+ throw new Error("Eventra: fetch not available - provide fetchImpl");
707
+ }
708
+ if (typeof options.maxBatchSize === "number" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {
709
+ warnOption("maxBatchSize", options.maxBatchSize, MAX_BATCH_SIZE);
710
+ }
711
+ this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1)));
712
+ this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
713
+ this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
714
+ this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
715
+ this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
716
+ this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
717
+ this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
718
+ this.persistQueue = options.persistQueue ?? true;
719
+ this.diagnosticsEnabled = options.diagnostics !== false;
720
+ const shared = this.runtime === "browser" && this.persistQueue;
721
+ this.diagnostics = new Diagnostics(
722
+ shared ? new SharedStore(this.storage) : new MemoryStore(),
723
+ DIAGNOSTICS_KEY,
724
+ uuidV4,
725
+ shared ? () => this.scheduleDiagnosticsSync() : void 0
726
+ );
727
+ this.sdkInfo = {
728
+ name: SDK_NAME,
729
+ version: SDK_VERSION,
730
+ runtime: this.runtime
731
+ };
732
+ if (this.runtime === "browser") {
733
+ if (this.persistQueue) {
734
+ this.loadAndMergeQueue();
735
+ }
736
+ this.setupQueueSync();
737
+ }
738
+ if (this.runtime === "browser" && options.multiTabMode === "leader") {
739
+ this.leader = new Leader((isLeader) => {
740
+ if (isLeader) void this.flushNow(false);
741
+ });
742
+ }
743
+ if (!options.disableTimer) {
744
+ this.startTimer();
745
+ }
746
+ if (this.runtime === "browser") {
747
+ this.setupBrowserExit();
748
+ }
749
+ if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
750
+ this.setupProcessExit();
751
+ }
752
+ Object.defineProperty(this, "apiKey", { enumerable: false });
753
+ Object.defineProperty(this, "options", { enumerable: false });
754
+ } catch (error) {
755
+ this.destroyed = true;
756
+ activeInstances = Math.max(0, activeInstances - 1);
757
+ for (const undo of [
758
+ () => clearInterval(this.timer),
759
+ () => this.leader?.destroy(),
760
+ () => this.channel?.close(),
761
+ () => this.exitHandlers.forEach((undoHandler) => undoHandler())
762
+ ]) {
763
+ try {
764
+ undo();
765
+ } catch {
766
+ }
767
+ }
768
+ throw error;
555
769
  }
556
770
  }
557
771
  track(name, options) {
772
+ try {
773
+ this.trackEvent(name, options);
774
+ } catch {
775
+ this.recordDiagnostic("invalid_event");
776
+ callSafely(this.options.onEventsDropped, 1);
777
+ }
778
+ }
779
+ trackEvent(name, options) {
558
780
  if (this.destroyed || this.shuttingDown) return;
559
781
  const eventName = normalizeEventName(name);
560
782
  if (eventName === null) {
561
783
  this.recordDiagnostic("invalid_event");
562
- this.options.onEventsDropped?.(1);
784
+ callSafely(this.options.onEventsDropped, 1);
563
785
  return;
564
786
  }
565
787
  let properties;
@@ -567,18 +789,18 @@ var Eventra = class {
567
789
  properties = validateProperties(options?.properties ?? {});
568
790
  } catch {
569
791
  this.recordDiagnostic("invalid_event");
570
- this.options.onEventsDropped?.(1);
792
+ callSafely(this.options.onEventsDropped, 1);
571
793
  return;
572
794
  }
573
795
  if (this.queue.length >= this.maxQueue) {
574
796
  this.recordDiagnostic("queue_full");
575
- this.options.onEventsDropped?.(1);
797
+ callSafely(this.options.onEventsDropped, 1);
576
798
  return;
577
799
  }
578
800
  const event = {
579
801
  idempotencyKey: uuidV4(),
580
802
  name: eventName,
581
- userId: truncate(options?.userId, MAX_USER_ID),
803
+ userId: normalizeUserId(options?.userId, MAX_USER_ID),
582
804
  properties,
583
805
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
584
806
  };
@@ -588,13 +810,14 @@ var Eventra = class {
588
810
  this.broadcast({ type: "queue-add", events: [event] });
589
811
  }
590
812
  if (this.queue.length >= this.maxBatch) {
591
- void this.flush();
813
+ void this.flushNow(false);
592
814
  }
593
815
  if (this.runtime === "serverless") {
594
- void this.flush();
816
+ void this.flushNow(false);
595
817
  }
596
818
  }
597
819
  async flush() {
820
+ if (this.flushPromise) await this.flushPromise.catch(() => void 0);
598
821
  return this.flushNow(false);
599
822
  }
600
823
  // `force` skips only the Retry-After delay (the last chance at shutdown);
@@ -621,7 +844,7 @@ var Eventra = class {
621
844
  }
622
845
  async runFlush() {
623
846
  try {
624
- while (this.queue.length > 0) {
847
+ while (this.queue.length > 0 && !this.destroyed) {
625
848
  const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
626
849
  const batch = this.buildBatch(report);
627
850
  if (!batch.events.length) break;
@@ -670,10 +893,13 @@ var Eventra = class {
670
893
  * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
671
894
  * hold a SIGTERM shutdown past a typical grace period.
672
895
  */
673
- async shutdown() {
674
- if (this.shuttingDown) return;
896
+ shutdown() {
897
+ this.shutdownPromise ??= this.runShutdown();
898
+ return this.shutdownPromise;
899
+ }
900
+ async runShutdown() {
675
901
  this.shuttingDown = true;
676
- const budget = this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
902
+ const budget = this.shutdownBudget;
677
903
  this.shutdownDeadline = Date.now() + Math.max(0, budget);
678
904
  let budgetTimer;
679
905
  const outOfTime = new Promise((resolve) => {
@@ -701,12 +927,13 @@ var Eventra = class {
701
927
  this.persistNow();
702
928
  this.leader?.destroy();
703
929
  if (this.channel) {
704
- this.channel.close();
930
+ try {
931
+ this.channel.close();
932
+ } catch {
933
+ }
705
934
  this.channel = void 0;
706
935
  }
707
- if (this.onStorageQueue && typeof window !== "undefined") {
708
- window.removeEventListener("storage", this.onStorageQueue);
709
- }
936
+ this.offStorageQueue?.();
710
937
  for (const off of this.exitHandlers) {
711
938
  off();
712
939
  }
@@ -728,7 +955,13 @@ var Eventra = class {
728
955
  let index = 0;
729
956
  while (index < this.queue.length && events.length < this.maxBatch) {
730
957
  const event = this.queue[index];
731
- const eventJson = JSON.stringify(event);
958
+ let eventJson;
959
+ try {
960
+ eventJson = JSON.stringify(event);
961
+ } catch {
962
+ this.dropPoisonEvent(event);
963
+ continue;
964
+ }
732
965
  const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
733
966
  if (total2 > this.maxPayloadBytes) {
734
967
  if (events.length === 0) {
@@ -759,12 +992,13 @@ var Eventra = class {
759
992
  dropPoisonEvent(event) {
760
993
  this.recordDiagnostic("too_large");
761
994
  this.removeDelivered([event]);
762
- this.options.onEventsDropped?.(1);
763
- this.options.onDeliveryFailed?.({ status: 413, events: [event] });
995
+ callSafely(this.options.onEventsDropped, 1);
996
+ callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
764
997
  }
765
998
  removeDelivered(batch) {
766
999
  const keys = new Set(batch.map((e) => e.idempotencyKey));
767
- this.queue = this.queue.filter((e) => !keys.has(e.idempotencyKey));
1000
+ const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
1001
+ this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
768
1002
  if (this.runtime === "browser") {
769
1003
  this.rememberDelivered(keys);
770
1004
  this.schedulePersist();
@@ -790,7 +1024,8 @@ var Eventra = class {
790
1024
  this.dropPoisonEvents(events);
791
1025
  return false;
792
1026
  }
793
- const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" && payloadBytes <= this.maxPayloadBytes;
1027
+ const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
1028
+ payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
794
1029
  const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
795
1030
  let strippedDiagnostics = false;
796
1031
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -798,20 +1033,24 @@ var Eventra = class {
798
1033
  const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
799
1034
  const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
800
1035
  try {
801
- const res = await this.fetch(this.endpoint, {
802
- method: "POST",
803
- headers: {
804
- "Content-Type": "application/json",
805
- "x-api-key": this.apiKey
806
- },
807
- body: payload,
808
- signal: controller.signal,
809
- keepalive: useKeepalive,
810
- // never follow a redirect: x-api-key is a custom header, so fetch
811
- // would forward it to wherever a compromised or misconfigured
812
- // endpoint points
813
- redirect: "error"
814
- });
1036
+ const res = await raceAbort(
1037
+ this.fetch(this.endpoint, {
1038
+ method: "POST",
1039
+ headers: {
1040
+ "Content-Type": "application/json",
1041
+ "x-api-key": this.apiKey
1042
+ },
1043
+ body: payload,
1044
+ signal: controller.signal,
1045
+ keepalive: useKeepalive,
1046
+ // never follow a redirect: x-api-key is a custom header, so fetch
1047
+ // would forward it to wherever a compromised or misconfigured
1048
+ // endpoint points
1049
+ redirect: "error"
1050
+ }),
1051
+ controller.signal
1052
+ );
1053
+ discardBody(res);
815
1054
  if (res.status === 429 || res.status >= 500) {
816
1055
  throw new RetryableDeliveryError(
817
1056
  "retryable delivery error",
@@ -828,7 +1067,7 @@ var Eventra = class {
828
1067
  continue;
829
1068
  }
830
1069
  this.recordDiagnostic("rejected", events.length);
831
- this.options.onDeliveryFailed?.({ status: res.status, events });
1070
+ callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
832
1071
  this.removeDelivered(events);
833
1072
  return false;
834
1073
  }
@@ -901,7 +1140,7 @@ var Eventra = class {
901
1140
  }
902
1141
  withoutDelivered(events) {
903
1142
  if (!this.deliveredKeys.size) return events;
904
- return events.filter((e) => !this.deliveredKeys.has(e.idempotencyKey));
1143
+ return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
905
1144
  }
906
1145
  rememberDelivered(keys) {
907
1146
  for (const key of keys) this.deliveredKeys.add(key);
@@ -938,13 +1177,13 @@ var Eventra = class {
938
1177
  this.queue
939
1178
  );
940
1179
  this.queue = this.trimQueue(merged);
941
- this.storage.set(QUEUE_KEY, this.queue);
1180
+ this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
942
1181
  }
943
1182
  trimQueue(queue = this.queue) {
944
1183
  if (queue.length <= this.maxQueue) return queue;
945
1184
  const dropped = queue.length - this.maxQueue;
946
1185
  this.recordDiagnostic("queue_full", dropped);
947
- this.options.onEventsDropped?.(dropped);
1186
+ callSafely(this.options.onEventsDropped, dropped);
948
1187
  return queue.slice(-this.maxQueue);
949
1188
  }
950
1189
  // Sends only what changed (a new event, or the keys just delivered) instead
@@ -957,7 +1196,13 @@ var Eventra = class {
957
1196
  }
958
1197
  setupQueueSync() {
959
1198
  if (typeof BroadcastChannel !== "undefined") {
960
- this.channel = new BroadcastChannel(CHANNEL_NAME);
1199
+ try {
1200
+ this.channel = new BroadcastChannel(CHANNEL_NAME);
1201
+ } catch {
1202
+ this.channel = void 0;
1203
+ }
1204
+ }
1205
+ if (this.channel) {
961
1206
  this.channel.onmessage = (e) => {
962
1207
  const data = e.data;
963
1208
  if (data?.type === "delivered" && Array.isArray(data.keys)) {
@@ -974,16 +1219,15 @@ var Eventra = class {
974
1219
  };
975
1220
  }
976
1221
  if (this.persistQueue && typeof window !== "undefined") {
977
- this.onStorageQueue = (e) => {
1222
+ this.offStorageQueue = listen(window, "storage", (e) => {
978
1223
  if (e.key !== QUEUE_KEY) return;
979
1224
  this.loadAndMergeQueue();
980
- };
981
- window.addEventListener("storage", this.onStorageQueue);
1225
+ });
982
1226
  }
983
1227
  }
984
1228
  startTimer() {
985
1229
  this.timer = setInterval(() => {
986
- void this.flush();
1230
+ void this.flushNow(false);
987
1231
  }, this.flushInterval);
988
1232
  this.timer.unref?.();
989
1233
  }
@@ -995,39 +1239,122 @@ var Eventra = class {
995
1239
  }
996
1240
  };
997
1241
  const pageHide = () => {
1242
+ this.leaving = true;
998
1243
  this.persistNow();
999
- void this.flush();
1244
+ if (this.inFlight) {
1245
+ this.sendOnLeave();
1246
+ } else {
1247
+ void this.flush();
1248
+ }
1000
1249
  };
1001
- document.addEventListener("visibilitychange", handler);
1002
- window.addEventListener("pagehide", pageHide);
1003
- this.exitHandlers.push(() => {
1004
- document.removeEventListener("visibilitychange", handler);
1005
- window.removeEventListener("pagehide", pageHide);
1006
- });
1250
+ const pageShow = () => {
1251
+ this.leaving = false;
1252
+ };
1253
+ const offs = [
1254
+ listen(document, "visibilitychange", handler),
1255
+ listen(window, "pagehide", pageHide),
1256
+ listen(window, "pageshow", pageShow)
1257
+ ];
1258
+ this.exitHandlers.push(() => offs.forEach((off) => off()));
1259
+ }
1260
+ /**
1261
+ * The page is being left while a request is in flight: send what is queued at once with keepalive, without
1262
+ * waiting for that request. The events of the batch in flight go along too (after the others, as far as the
1263
+ * keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
1264
+ * drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
1265
+ */
1266
+ sendOnLeave() {
1267
+ if (this.leader && !this.leader.canSend()) return;
1268
+ const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));
1269
+ const candidates = [
1270
+ ...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),
1271
+ ...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey))
1272
+ ];
1273
+ const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
1274
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
1275
+ let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));
1276
+ const events = [];
1277
+ const json = [];
1278
+ for (const event of candidates) {
1279
+ if (events.length >= MAX_BATCH_SIZE) break;
1280
+ let eventJson;
1281
+ try {
1282
+ eventJson = JSON.stringify(event);
1283
+ } catch {
1284
+ continue;
1285
+ }
1286
+ const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
1287
+ if (total2 > limit) continue;
1288
+ events.push(event);
1289
+ json.push(eventJson);
1290
+ bytes = total2;
1291
+ }
1292
+ if (!events.length) return;
1293
+ const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });
1294
+ const body = `${head.slice(0, -1)},"events":[${json.join(",")}]}`;
1295
+ try {
1296
+ const request = this.fetch(this.endpoint, {
1297
+ method: "POST",
1298
+ headers: {
1299
+ "Content-Type": "application/json",
1300
+ "x-api-key": this.apiKey
1301
+ },
1302
+ body,
1303
+ keepalive: true,
1304
+ redirect: "error"
1305
+ });
1306
+ Promise.resolve(request).then(
1307
+ (res) => {
1308
+ discardBody(res);
1309
+ if (res.ok && !this.destroyed) this.removeDelivered(events);
1310
+ },
1311
+ () => void 0
1312
+ );
1313
+ } catch {
1314
+ }
1007
1315
  }
1008
1316
  setupProcessExit() {
1009
1317
  const proc = globalThis.process;
1010
1318
  if (!proc?.on) return;
1011
- const exitOnSignal = this.options.exitOnSignal === true;
1319
+ const exitOnSignal = this.options.exitOnSignal !== false;
1012
1320
  const onSignal = (signal) => () => {
1321
+ proc.off?.(signal, handlers[signal]);
1322
+ const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
1013
1323
  void this.shutdown().finally(() => {
1014
- if (!exitOnSignal) return;
1015
- proc.off?.(signal, handlers[signal]);
1324
+ if (!exitOnSignal || othersAtSignal) return;
1016
1325
  const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
1017
- if (!othersListening && proc.kill && proc.pid !== void 0) {
1326
+ if (othersListening) return;
1327
+ if (proc.pid === 1 && proc.exit) {
1328
+ proc.exit(128 + (signal === "SIGINT" ? 2 : 15));
1329
+ return;
1330
+ }
1331
+ if (proc.kill && proc.pid !== void 0) {
1018
1332
  proc.kill(proc.pid, signal);
1019
1333
  }
1020
1334
  });
1021
1335
  };
1336
+ const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
1022
1337
  const handlers = {
1023
1338
  SIGINT: onSignal("SIGINT"),
1024
1339
  SIGTERM: onSignal("SIGTERM")
1025
1340
  };
1341
+ const listenAgain = () => {
1342
+ if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
1343
+ };
1026
1344
  const onBeforeExit = () => {
1027
- if (this.queue.length) void this.flush();
1345
+ if (!this.queue.length) {
1346
+ listenAgain();
1347
+ return;
1348
+ }
1349
+ const own = this.shutdownDeadline === 0;
1350
+ if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
1351
+ void this.flush().finally(() => {
1352
+ if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
1353
+ if (!this.queue.length) listenAgain();
1354
+ });
1028
1355
  };
1029
- proc.once("SIGINT", handlers.SIGINT);
1030
- proc.once("SIGTERM", handlers.SIGTERM);
1356
+ listenFirst("SIGINT", handlers.SIGINT);
1357
+ listenFirst("SIGTERM", handlers.SIGTERM);
1031
1358
  proc.once("beforeExit", onBeforeExit);
1032
1359
  this.exitHandlers.push(() => {
1033
1360
  proc.off?.("SIGINT", handlers.SIGINT);