@eventra_dev/eventra-sdk 2.0.10 → 2.0.12
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/README.md +24 -15
- package/dist/index.cjs +314 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.mjs +314 -106
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -4
package/dist/index.cjs
CHANGED
|
@@ -193,7 +193,7 @@ var Diagnostics = class {
|
|
|
193
193
|
// src/client.ts
|
|
194
194
|
var SDK_NAME = "@eventra_dev/eventra-sdk";
|
|
195
195
|
var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
|
|
196
|
-
var SDK_VERSION = "2.0.
|
|
196
|
+
var SDK_VERSION = "2.0.12";
|
|
197
197
|
var LEADER_KEY = "__eventra_leader__";
|
|
198
198
|
var LEADER_TTL_MS = 4e3;
|
|
199
199
|
var QUEUE_KEY = "__eventra_q__";
|
|
@@ -213,6 +213,7 @@ var RETRY_AFTER_MAX_MS = 3e4;
|
|
|
213
213
|
var PERSIST_DEBOUNCE_MS = 50;
|
|
214
214
|
var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
|
|
215
215
|
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
216
|
+
var KEEPALIVE_MAX_BYTES = 6e4;
|
|
216
217
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
217
218
|
var activeInstances = 0;
|
|
218
219
|
function detectRuntime() {
|
|
@@ -228,27 +229,97 @@ function uuidV4() {
|
|
|
228
229
|
return crypto.randomUUID();
|
|
229
230
|
}
|
|
230
231
|
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
|
231
|
-
const
|
|
232
|
-
crypto.getRandomValues(
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
return `${
|
|
237
|
-
}
|
|
238
|
-
|
|
232
|
+
const bytes2 = new Uint8Array(16);
|
|
233
|
+
crypto.getRandomValues(bytes2);
|
|
234
|
+
bytes2[6] = bytes2[6] & 15 | 64;
|
|
235
|
+
bytes2[8] = bytes2[8] & 63 | 128;
|
|
236
|
+
const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
237
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
238
|
+
}
|
|
239
|
+
const bytes = new Uint8Array(16);
|
|
240
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
241
|
+
let t = Date.now();
|
|
242
|
+
for (let i = 0; i < 6; i++) {
|
|
243
|
+
bytes[i] ^= t & 255;
|
|
244
|
+
t = Math.floor(t / 256);
|
|
245
|
+
}
|
|
246
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
247
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
248
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
249
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
250
|
+
}
|
|
251
|
+
var MAX_TIMER_MS = 2147483647;
|
|
252
|
+
var MAX_RETRIES = 20;
|
|
253
|
+
function isUrl(value) {
|
|
254
|
+
try {
|
|
255
|
+
new URL(value);
|
|
256
|
+
return true;
|
|
257
|
+
} catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function warnOption(name, value, fallback) {
|
|
262
|
+
if (typeof console !== "undefined") {
|
|
263
|
+
console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
|
|
267
|
+
if (value === void 0) return fallback;
|
|
268
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
|
|
269
|
+
warnOption(name, value, fallback);
|
|
270
|
+
return fallback;
|
|
271
|
+
}
|
|
272
|
+
function callSafely(callback, ...args) {
|
|
273
|
+
if (!callback) return;
|
|
274
|
+
try {
|
|
275
|
+
const result = callback(...args);
|
|
276
|
+
if (result && typeof result.catch === "function") {
|
|
277
|
+
result.catch(() => void 0);
|
|
278
|
+
}
|
|
279
|
+
} catch {
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function raceAbort(request, signal) {
|
|
283
|
+
return new Promise((resolve, reject) => {
|
|
284
|
+
const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
|
|
285
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
286
|
+
request.then(
|
|
287
|
+
(value) => {
|
|
288
|
+
signal.removeEventListener("abort", onAbort);
|
|
289
|
+
resolve(value);
|
|
290
|
+
},
|
|
291
|
+
(error) => {
|
|
292
|
+
signal.removeEventListener("abort", onAbort);
|
|
293
|
+
reject(error);
|
|
294
|
+
}
|
|
295
|
+
);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function discardBody(res) {
|
|
299
|
+
try {
|
|
300
|
+
const closing = res.body?.cancel?.();
|
|
301
|
+
if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
|
|
302
|
+
} catch {
|
|
303
|
+
}
|
|
239
304
|
}
|
|
240
305
|
function sleep(ms) {
|
|
241
306
|
return new Promise((r) => setTimeout(r, ms));
|
|
242
307
|
}
|
|
243
|
-
function
|
|
244
|
-
if (value
|
|
245
|
-
|
|
308
|
+
function cut(value, max) {
|
|
309
|
+
if (value.length <= max) return value;
|
|
310
|
+
const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
|
|
311
|
+
return value.slice(0, end);
|
|
312
|
+
}
|
|
313
|
+
function normalizeUserId(value, max) {
|
|
314
|
+
if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
|
|
315
|
+
if (typeof value !== "string") return void 0;
|
|
316
|
+
return cut(value, max);
|
|
246
317
|
}
|
|
247
318
|
function normalizeEventName(name) {
|
|
248
319
|
if (typeof name !== "string") return null;
|
|
249
320
|
const trimmed = name.trim();
|
|
250
321
|
if (!trimmed) return null;
|
|
251
|
-
return trimmed
|
|
322
|
+
return cut(trimmed, MAX_EVENT_NAME).trimEnd();
|
|
252
323
|
}
|
|
253
324
|
function backoffMs(attempt, base) {
|
|
254
325
|
const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
|
|
@@ -267,46 +338,65 @@ function utf8ByteLength(value) {
|
|
|
267
338
|
}
|
|
268
339
|
return value.length;
|
|
269
340
|
}
|
|
341
|
+
function isStoredEvent(e) {
|
|
342
|
+
if (e === null || typeof e !== "object") return false;
|
|
343
|
+
const ev = e;
|
|
344
|
+
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));
|
|
345
|
+
}
|
|
270
346
|
function mergeQueues(...queues) {
|
|
271
347
|
const seen = /* @__PURE__ */ new Set();
|
|
272
348
|
const out = [];
|
|
273
349
|
for (const q of queues) {
|
|
274
350
|
for (const e of q) {
|
|
351
|
+
if (!isStoredEvent(e)) continue;
|
|
275
352
|
if (seen.has(e.idempotencyKey)) continue;
|
|
276
353
|
seen.add(e.idempotencyKey);
|
|
277
|
-
out.push(e);
|
|
354
|
+
out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
|
|
278
355
|
}
|
|
279
356
|
}
|
|
280
357
|
return out;
|
|
281
358
|
}
|
|
359
|
+
var MAX_PROPERTIES_NODES = 5e4;
|
|
282
360
|
function validateProperties(properties) {
|
|
361
|
+
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
|
|
362
|
+
Object.prototype.toString.call(properties) !== "[object Object]") {
|
|
363
|
+
throw new Error("Eventra: properties must be an object");
|
|
364
|
+
}
|
|
283
365
|
let hasKeys = false;
|
|
284
366
|
for (const _ in properties) {
|
|
285
367
|
hasKeys = true;
|
|
286
368
|
break;
|
|
287
369
|
}
|
|
288
|
-
if (!hasKeys) return
|
|
370
|
+
if (!hasKeys) return {};
|
|
371
|
+
let visited = 0;
|
|
289
372
|
const depth = (obj, level) => {
|
|
290
373
|
if (level > MAX_PROPERTIES_DEPTH) {
|
|
291
374
|
throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
|
|
292
375
|
}
|
|
376
|
+
if (++visited > MAX_PROPERTIES_NODES) {
|
|
377
|
+
throw new Error("Eventra: properties are too large to check");
|
|
378
|
+
}
|
|
293
379
|
if (obj === null || typeof obj !== "object") return;
|
|
294
380
|
if (Array.isArray(obj)) {
|
|
295
381
|
for (const item of obj) depth(item, level + 1);
|
|
296
382
|
return;
|
|
297
383
|
}
|
|
298
|
-
for (const
|
|
299
|
-
depth(
|
|
384
|
+
for (const key in obj) {
|
|
385
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
|
|
300
386
|
}
|
|
301
387
|
};
|
|
302
388
|
depth(properties, 0);
|
|
303
389
|
const json = JSON.stringify(properties);
|
|
304
|
-
if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
390
|
+
if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
305
391
|
throw new Error(
|
|
306
392
|
`Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
|
|
307
393
|
);
|
|
308
394
|
}
|
|
309
|
-
|
|
395
|
+
const copy = JSON.parse(json);
|
|
396
|
+
if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
|
|
397
|
+
throw new Error("Eventra: properties must be an object");
|
|
398
|
+
}
|
|
399
|
+
return copy;
|
|
310
400
|
}
|
|
311
401
|
function parseRetryAfterMs(value) {
|
|
312
402
|
if (!value) return void 0;
|
|
@@ -371,12 +461,19 @@ var Storage = class {
|
|
|
371
461
|
}
|
|
372
462
|
/* v8 ignore stop */
|
|
373
463
|
};
|
|
464
|
+
function storageAvailable() {
|
|
465
|
+
try {
|
|
466
|
+
return typeof localStorage !== "undefined" && localStorage !== null;
|
|
467
|
+
} catch {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
374
471
|
var Leader = class {
|
|
375
472
|
constructor(onLeadershipChange) {
|
|
376
473
|
this.onLeadershipChange = onLeadershipChange;
|
|
377
474
|
this.tabId = uuidV4();
|
|
378
475
|
this.isLeader = false;
|
|
379
|
-
if (
|
|
476
|
+
if (!storageAvailable()) {
|
|
380
477
|
this.isLeader = true;
|
|
381
478
|
return;
|
|
382
479
|
}
|
|
@@ -463,7 +560,7 @@ var Leader = class {
|
|
|
463
560
|
if (this.onStorage && typeof window !== "undefined") {
|
|
464
561
|
window.removeEventListener("storage", this.onStorage);
|
|
465
562
|
}
|
|
466
|
-
if (this.isLeader &&
|
|
563
|
+
if (this.isLeader && storageAvailable()) {
|
|
467
564
|
try {
|
|
468
565
|
const raw = localStorage.getItem(LEADER_KEY);
|
|
469
566
|
if (raw) {
|
|
@@ -490,6 +587,14 @@ function warnIfInsecureEndpoint(endpoint) {
|
|
|
490
587
|
} catch {
|
|
491
588
|
}
|
|
492
589
|
}
|
|
590
|
+
function isRedirectError(err) {
|
|
591
|
+
let current = err;
|
|
592
|
+
for (let depth = 0; depth < 3 && current instanceof Error; depth++) {
|
|
593
|
+
if (/redirect/i.test(current.message)) return true;
|
|
594
|
+
current = current.cause;
|
|
595
|
+
}
|
|
596
|
+
return false;
|
|
597
|
+
}
|
|
493
598
|
var Eventra = class {
|
|
494
599
|
constructor(options) {
|
|
495
600
|
this.queue = [];
|
|
@@ -500,6 +605,7 @@ var Eventra = class {
|
|
|
500
605
|
this.storage = new Storage();
|
|
501
606
|
this.leader = null;
|
|
502
607
|
this.failureCount = 0;
|
|
608
|
+
this.warnedRedirect = false;
|
|
503
609
|
this.circuitOpenUntil = 0;
|
|
504
610
|
this.circuitHalfOpen = false;
|
|
505
611
|
// consecutive times the circuit opened without a success in between; drives
|
|
@@ -513,70 +619,128 @@ var Eventra = class {
|
|
|
513
619
|
this.nextFlushAt = 0;
|
|
514
620
|
// 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
|
|
515
621
|
this.shutdownDeadline = 0;
|
|
622
|
+
this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
623
|
+
// the page is being left (`pagehide`)
|
|
624
|
+
this.leaving = false;
|
|
516
625
|
this.exitHandlers = [];
|
|
517
|
-
if (!options
|
|
626
|
+
if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
|
|
627
|
+
throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
|
|
628
|
+
}
|
|
629
|
+
if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
|
|
630
|
+
throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
|
|
631
|
+
}
|
|
632
|
+
if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
|
|
633
|
+
throw new Error("Eventra: fetchImpl must be a function");
|
|
634
|
+
}
|
|
518
635
|
activeInstances++;
|
|
519
636
|
if (activeInstances > 1 && typeof console !== "undefined") {
|
|
520
637
|
console.warn(
|
|
521
|
-
"Eventra: multiple SDK instances detected
|
|
638
|
+
"Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
|
|
522
639
|
);
|
|
523
640
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
530
|
-
if (!this.fetch) {
|
|
531
|
-
throw new Error("Eventra: fetch not available \u2014 provide fetchImpl");
|
|
532
|
-
}
|
|
533
|
-
this.maxBatch = options.maxBatchSize ?? 50;
|
|
534
|
-
this.maxQueue = options.maxQueueSize ?? 1e4;
|
|
535
|
-
this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
536
|
-
this.flushInterval = options.flushInterval ?? 2e3;
|
|
537
|
-
this.retries = options.maxRetries ?? 3;
|
|
538
|
-
this.retryDelay = options.retryBaseDelayMs ?? 300;
|
|
539
|
-
this.persistQueue = options.persistQueue ?? true;
|
|
540
|
-
this.diagnosticsEnabled = options.diagnostics !== false;
|
|
541
|
-
const shared = this.runtime === "browser" && this.persistQueue;
|
|
542
|
-
this.diagnostics = new Diagnostics(
|
|
543
|
-
shared ? new SharedStore(this.storage) : new MemoryStore(),
|
|
544
|
-
DIAGNOSTICS_KEY,
|
|
545
|
-
uuidV4,
|
|
546
|
-
shared ? () => this.scheduleDiagnosticsSync() : void 0
|
|
547
|
-
);
|
|
548
|
-
this.sdkInfo = {
|
|
549
|
-
name: SDK_NAME,
|
|
550
|
-
version: SDK_VERSION,
|
|
551
|
-
runtime: this.runtime
|
|
552
|
-
};
|
|
553
|
-
if (this.runtime === "browser") {
|
|
554
|
-
if (this.persistQueue) {
|
|
555
|
-
this.loadAndMergeQueue();
|
|
641
|
+
try {
|
|
642
|
+
this.options = options;
|
|
643
|
+
this.apiKey = options.apiKey;
|
|
644
|
+
if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
|
|
645
|
+
warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
|
|
556
646
|
}
|
|
557
|
-
this.
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
647
|
+
this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
|
|
648
|
+
if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
|
|
649
|
+
warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
|
|
650
|
+
this.endpoint = DEFAULT_ENDPOINT;
|
|
651
|
+
}
|
|
652
|
+
if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
|
|
653
|
+
warnOption("multiTabMode", options.multiTabMode, "independent");
|
|
654
|
+
}
|
|
655
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
|
|
656
|
+
warnOption("diagnostics", options.diagnostics, "true");
|
|
657
|
+
}
|
|
658
|
+
for (const name of ["maxBatchSize", "maxQueueSize"]) {
|
|
659
|
+
const value = options[name];
|
|
660
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
|
|
661
|
+
warnOption(name, value, Math.floor(value));
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
this.runtime = detectRuntime();
|
|
665
|
+
warnIfInsecureEndpoint(this.endpoint);
|
|
666
|
+
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
667
|
+
if (!this.fetch) {
|
|
668
|
+
throw new Error("Eventra: fetch not available - provide fetchImpl");
|
|
669
|
+
}
|
|
670
|
+
this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
|
|
671
|
+
this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
|
|
672
|
+
this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
|
|
673
|
+
this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
|
|
674
|
+
this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
|
|
675
|
+
this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
|
|
676
|
+
this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
|
|
677
|
+
this.persistQueue = options.persistQueue ?? true;
|
|
678
|
+
this.diagnosticsEnabled = options.diagnostics !== false;
|
|
679
|
+
const shared = this.runtime === "browser" && this.persistQueue;
|
|
680
|
+
this.diagnostics = new Diagnostics(
|
|
681
|
+
shared ? new SharedStore(this.storage) : new MemoryStore(),
|
|
682
|
+
DIAGNOSTICS_KEY,
|
|
683
|
+
uuidV4,
|
|
684
|
+
shared ? () => this.scheduleDiagnosticsSync() : void 0
|
|
685
|
+
);
|
|
686
|
+
this.sdkInfo = {
|
|
687
|
+
name: SDK_NAME,
|
|
688
|
+
version: SDK_VERSION,
|
|
689
|
+
runtime: this.runtime
|
|
690
|
+
};
|
|
691
|
+
if (this.runtime === "browser") {
|
|
692
|
+
if (this.persistQueue) {
|
|
693
|
+
this.loadAndMergeQueue();
|
|
694
|
+
}
|
|
695
|
+
this.setupQueueSync();
|
|
696
|
+
}
|
|
697
|
+
if (this.runtime === "browser" && options.multiTabMode === "leader") {
|
|
698
|
+
this.leader = new Leader((isLeader) => {
|
|
699
|
+
if (isLeader) void this.flushNow(false);
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
if (!options.disableTimer) {
|
|
703
|
+
this.startTimer();
|
|
704
|
+
}
|
|
705
|
+
if (this.runtime === "browser") {
|
|
706
|
+
this.setupBrowserExit();
|
|
707
|
+
}
|
|
708
|
+
if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
|
|
709
|
+
this.setupProcessExit();
|
|
710
|
+
}
|
|
711
|
+
Object.defineProperty(this, "apiKey", { enumerable: false });
|
|
712
|
+
Object.defineProperty(this, "options", { enumerable: false });
|
|
713
|
+
} catch (error) {
|
|
714
|
+
this.destroyed = true;
|
|
715
|
+
activeInstances = Math.max(0, activeInstances - 1);
|
|
716
|
+
for (const undo of [
|
|
717
|
+
() => clearInterval(this.timer),
|
|
718
|
+
() => this.leader?.destroy(),
|
|
719
|
+
() => this.channel?.close(),
|
|
720
|
+
() => this.exitHandlers.forEach((undoHandler) => undoHandler())
|
|
721
|
+
]) {
|
|
722
|
+
try {
|
|
723
|
+
undo();
|
|
724
|
+
} catch {
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
throw error;
|
|
572
728
|
}
|
|
573
729
|
}
|
|
574
730
|
track(name, options) {
|
|
731
|
+
try {
|
|
732
|
+
this.trackEvent(name, options);
|
|
733
|
+
} catch {
|
|
734
|
+
this.recordDiagnostic("invalid_event");
|
|
735
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
trackEvent(name, options) {
|
|
575
739
|
if (this.destroyed || this.shuttingDown) return;
|
|
576
740
|
const eventName = normalizeEventName(name);
|
|
577
741
|
if (eventName === null) {
|
|
578
742
|
this.recordDiagnostic("invalid_event");
|
|
579
|
-
this.options.onEventsDropped
|
|
743
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
580
744
|
return;
|
|
581
745
|
}
|
|
582
746
|
let properties;
|
|
@@ -584,18 +748,18 @@ var Eventra = class {
|
|
|
584
748
|
properties = validateProperties(options?.properties ?? {});
|
|
585
749
|
} catch {
|
|
586
750
|
this.recordDiagnostic("invalid_event");
|
|
587
|
-
this.options.onEventsDropped
|
|
751
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
588
752
|
return;
|
|
589
753
|
}
|
|
590
754
|
if (this.queue.length >= this.maxQueue) {
|
|
591
755
|
this.recordDiagnostic("queue_full");
|
|
592
|
-
this.options.onEventsDropped
|
|
756
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
593
757
|
return;
|
|
594
758
|
}
|
|
595
759
|
const event = {
|
|
596
760
|
idempotencyKey: uuidV4(),
|
|
597
761
|
name: eventName,
|
|
598
|
-
userId:
|
|
762
|
+
userId: normalizeUserId(options?.userId, MAX_USER_ID),
|
|
599
763
|
properties,
|
|
600
764
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
601
765
|
};
|
|
@@ -605,13 +769,14 @@ var Eventra = class {
|
|
|
605
769
|
this.broadcast({ type: "queue-add", events: [event] });
|
|
606
770
|
}
|
|
607
771
|
if (this.queue.length >= this.maxBatch) {
|
|
608
|
-
void this.
|
|
772
|
+
void this.flushNow(false);
|
|
609
773
|
}
|
|
610
774
|
if (this.runtime === "serverless") {
|
|
611
|
-
void this.
|
|
775
|
+
void this.flushNow(false);
|
|
612
776
|
}
|
|
613
777
|
}
|
|
614
778
|
async flush() {
|
|
779
|
+
if (this.flushPromise) await this.flushPromise.catch(() => void 0);
|
|
615
780
|
return this.flushNow(false);
|
|
616
781
|
}
|
|
617
782
|
// `force` skips only the Retry-After delay (the last chance at shutdown);
|
|
@@ -638,7 +803,7 @@ var Eventra = class {
|
|
|
638
803
|
}
|
|
639
804
|
async runFlush() {
|
|
640
805
|
try {
|
|
641
|
-
while (this.queue.length > 0) {
|
|
806
|
+
while (this.queue.length > 0 && !this.destroyed) {
|
|
642
807
|
const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
|
|
643
808
|
const batch = this.buildBatch(report);
|
|
644
809
|
if (!batch.events.length) break;
|
|
@@ -687,10 +852,13 @@ var Eventra = class {
|
|
|
687
852
|
* `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
|
|
688
853
|
* hold a SIGTERM shutdown past a typical grace period.
|
|
689
854
|
*/
|
|
690
|
-
|
|
691
|
-
|
|
855
|
+
shutdown() {
|
|
856
|
+
this.shutdownPromise ??= this.runShutdown();
|
|
857
|
+
return this.shutdownPromise;
|
|
858
|
+
}
|
|
859
|
+
async runShutdown() {
|
|
692
860
|
this.shuttingDown = true;
|
|
693
|
-
const budget = this.
|
|
861
|
+
const budget = this.shutdownBudget;
|
|
694
862
|
this.shutdownDeadline = Date.now() + Math.max(0, budget);
|
|
695
863
|
let budgetTimer;
|
|
696
864
|
const outOfTime = new Promise((resolve) => {
|
|
@@ -718,7 +886,10 @@ var Eventra = class {
|
|
|
718
886
|
this.persistNow();
|
|
719
887
|
this.leader?.destroy();
|
|
720
888
|
if (this.channel) {
|
|
721
|
-
|
|
889
|
+
try {
|
|
890
|
+
this.channel.close();
|
|
891
|
+
} catch {
|
|
892
|
+
}
|
|
722
893
|
this.channel = void 0;
|
|
723
894
|
}
|
|
724
895
|
if (this.onStorageQueue && typeof window !== "undefined") {
|
|
@@ -745,7 +916,13 @@ var Eventra = class {
|
|
|
745
916
|
let index = 0;
|
|
746
917
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
747
918
|
const event = this.queue[index];
|
|
748
|
-
|
|
919
|
+
let eventJson;
|
|
920
|
+
try {
|
|
921
|
+
eventJson = JSON.stringify(event);
|
|
922
|
+
} catch {
|
|
923
|
+
this.dropPoisonEvent(event);
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
749
926
|
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
750
927
|
if (total2 > this.maxPayloadBytes) {
|
|
751
928
|
if (events.length === 0) {
|
|
@@ -776,12 +953,13 @@ var Eventra = class {
|
|
|
776
953
|
dropPoisonEvent(event) {
|
|
777
954
|
this.recordDiagnostic("too_large");
|
|
778
955
|
this.removeDelivered([event]);
|
|
779
|
-
this.options.onEventsDropped
|
|
780
|
-
this.options.onDeliveryFailed
|
|
956
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
957
|
+
callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
|
|
781
958
|
}
|
|
782
959
|
removeDelivered(batch) {
|
|
783
960
|
const keys = new Set(batch.map((e) => e.idempotencyKey));
|
|
784
|
-
|
|
961
|
+
const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
|
|
962
|
+
this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
|
|
785
963
|
if (this.runtime === "browser") {
|
|
786
964
|
this.rememberDelivered(keys);
|
|
787
965
|
this.schedulePersist();
|
|
@@ -807,7 +985,8 @@ var Eventra = class {
|
|
|
807
985
|
this.dropPoisonEvents(events);
|
|
808
986
|
return false;
|
|
809
987
|
}
|
|
810
|
-
const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" &&
|
|
988
|
+
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
|
|
989
|
+
payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
811
990
|
const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
|
|
812
991
|
let strippedDiagnostics = false;
|
|
813
992
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
@@ -815,20 +994,24 @@ var Eventra = class {
|
|
|
815
994
|
const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
|
|
816
995
|
const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
|
|
817
996
|
try {
|
|
818
|
-
const res = await
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
997
|
+
const res = await raceAbort(
|
|
998
|
+
this.fetch(this.endpoint, {
|
|
999
|
+
method: "POST",
|
|
1000
|
+
headers: {
|
|
1001
|
+
"Content-Type": "application/json",
|
|
1002
|
+
"x-api-key": this.apiKey
|
|
1003
|
+
},
|
|
1004
|
+
body: payload,
|
|
1005
|
+
signal: controller.signal,
|
|
1006
|
+
keepalive: useKeepalive,
|
|
1007
|
+
// never follow a redirect: x-api-key is a custom header, so fetch
|
|
1008
|
+
// would forward it to wherever a compromised or misconfigured
|
|
1009
|
+
// endpoint points
|
|
1010
|
+
redirect: "error"
|
|
1011
|
+
}),
|
|
1012
|
+
controller.signal
|
|
1013
|
+
);
|
|
1014
|
+
discardBody(res);
|
|
832
1015
|
if (res.status === 429 || res.status >= 500) {
|
|
833
1016
|
throw new RetryableDeliveryError(
|
|
834
1017
|
"retryable delivery error",
|
|
@@ -845,7 +1028,7 @@ var Eventra = class {
|
|
|
845
1028
|
continue;
|
|
846
1029
|
}
|
|
847
1030
|
this.recordDiagnostic("rejected", events.length);
|
|
848
|
-
this.options.onDeliveryFailed
|
|
1031
|
+
callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
|
|
849
1032
|
this.removeDelivered(events);
|
|
850
1033
|
return false;
|
|
851
1034
|
}
|
|
@@ -858,6 +1041,12 @@ var Eventra = class {
|
|
|
858
1041
|
}
|
|
859
1042
|
return carriesDiagnostics;
|
|
860
1043
|
} catch (err) {
|
|
1044
|
+
if (!this.warnedRedirect && isRedirectError(err) && typeof console !== "undefined") {
|
|
1045
|
+
this.warnedRedirect = true;
|
|
1046
|
+
console.warn(
|
|
1047
|
+
"Eventra: the endpoint answered with a redirect. It is not followed, so the API key is not forwarded, and events stay queued - check the endpoint URL (for example http instead of https)"
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
861
1050
|
const isLast = attempt >= maxAttempts - 1;
|
|
862
1051
|
const retryAfter = err instanceof RetryableDeliveryError ? err.retryAfterMs : void 0;
|
|
863
1052
|
const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);
|
|
@@ -912,7 +1101,7 @@ var Eventra = class {
|
|
|
912
1101
|
}
|
|
913
1102
|
withoutDelivered(events) {
|
|
914
1103
|
if (!this.deliveredKeys.size) return events;
|
|
915
|
-
return events.filter((e) => !this.deliveredKeys.has(e
|
|
1104
|
+
return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
|
|
916
1105
|
}
|
|
917
1106
|
rememberDelivered(keys) {
|
|
918
1107
|
for (const key of keys) this.deliveredKeys.add(key);
|
|
@@ -955,7 +1144,7 @@ var Eventra = class {
|
|
|
955
1144
|
if (queue.length <= this.maxQueue) return queue;
|
|
956
1145
|
const dropped = queue.length - this.maxQueue;
|
|
957
1146
|
this.recordDiagnostic("queue_full", dropped);
|
|
958
|
-
this.options.onEventsDropped
|
|
1147
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
959
1148
|
return queue.slice(-this.maxQueue);
|
|
960
1149
|
}
|
|
961
1150
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
@@ -968,7 +1157,13 @@ var Eventra = class {
|
|
|
968
1157
|
}
|
|
969
1158
|
setupQueueSync() {
|
|
970
1159
|
if (typeof BroadcastChannel !== "undefined") {
|
|
971
|
-
|
|
1160
|
+
try {
|
|
1161
|
+
this.channel = new BroadcastChannel(CHANNEL_NAME);
|
|
1162
|
+
} catch {
|
|
1163
|
+
this.channel = void 0;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
if (this.channel) {
|
|
972
1167
|
this.channel.onmessage = (e) => {
|
|
973
1168
|
const data = e.data;
|
|
974
1169
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
@@ -994,7 +1189,7 @@ var Eventra = class {
|
|
|
994
1189
|
}
|
|
995
1190
|
startTimer() {
|
|
996
1191
|
this.timer = setInterval(() => {
|
|
997
|
-
void this.
|
|
1192
|
+
void this.flushNow(false);
|
|
998
1193
|
}, this.flushInterval);
|
|
999
1194
|
this.timer.unref?.();
|
|
1000
1195
|
}
|
|
@@ -1006,6 +1201,7 @@ var Eventra = class {
|
|
|
1006
1201
|
}
|
|
1007
1202
|
};
|
|
1008
1203
|
const pageHide = () => {
|
|
1204
|
+
this.leaving = true;
|
|
1009
1205
|
this.persistNow();
|
|
1010
1206
|
void this.flush();
|
|
1011
1207
|
};
|
|
@@ -1034,8 +1230,20 @@ var Eventra = class {
|
|
|
1034
1230
|
SIGINT: onSignal("SIGINT"),
|
|
1035
1231
|
SIGTERM: onSignal("SIGTERM")
|
|
1036
1232
|
};
|
|
1233
|
+
const listenAgain = () => {
|
|
1234
|
+
if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
|
|
1235
|
+
};
|
|
1037
1236
|
const onBeforeExit = () => {
|
|
1038
|
-
if (this.queue.length)
|
|
1237
|
+
if (!this.queue.length) {
|
|
1238
|
+
listenAgain();
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
const own = this.shutdownDeadline === 0;
|
|
1242
|
+
if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
|
|
1243
|
+
void this.flush().finally(() => {
|
|
1244
|
+
if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
|
|
1245
|
+
if (!this.queue.length) listenAgain();
|
|
1246
|
+
});
|
|
1039
1247
|
};
|
|
1040
1248
|
proc.once("SIGINT", handlers.SIGINT);
|
|
1041
1249
|
proc.once("SIGTERM", handlers.SIGTERM);
|