@eventra_dev/eventra-sdk 2.0.11 → 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 +23 -14
- package/dist/index.cjs +299 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +299 -106
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -4
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.
|
|
170
|
+
var SDK_VERSION = "2.0.12";
|
|
171
171
|
var LEADER_KEY = "__eventra_leader__";
|
|
172
172
|
var LEADER_TTL_MS = 4e3;
|
|
173
173
|
var QUEUE_KEY = "__eventra_q__";
|
|
@@ -187,6 +187,7 @@ 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 KEEPALIVE_MAX_BYTES = 6e4;
|
|
190
191
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
191
192
|
var activeInstances = 0;
|
|
192
193
|
function detectRuntime() {
|
|
@@ -202,27 +203,97 @@ function uuidV4() {
|
|
|
202
203
|
return crypto.randomUUID();
|
|
203
204
|
}
|
|
204
205
|
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
|
205
|
-
const
|
|
206
|
-
crypto.getRandomValues(
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const
|
|
210
|
-
return `${
|
|
211
|
-
}
|
|
212
|
-
|
|
206
|
+
const bytes2 = new Uint8Array(16);
|
|
207
|
+
crypto.getRandomValues(bytes2);
|
|
208
|
+
bytes2[6] = bytes2[6] & 15 | 64;
|
|
209
|
+
bytes2[8] = bytes2[8] & 63 | 128;
|
|
210
|
+
const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
211
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
212
|
+
}
|
|
213
|
+
const bytes = new Uint8Array(16);
|
|
214
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
215
|
+
let t = Date.now();
|
|
216
|
+
for (let i = 0; i < 6; i++) {
|
|
217
|
+
bytes[i] ^= t & 255;
|
|
218
|
+
t = Math.floor(t / 256);
|
|
219
|
+
}
|
|
220
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
221
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
222
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
223
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
224
|
+
}
|
|
225
|
+
var MAX_TIMER_MS = 2147483647;
|
|
226
|
+
var MAX_RETRIES = 20;
|
|
227
|
+
function isUrl(value) {
|
|
228
|
+
try {
|
|
229
|
+
new URL(value);
|
|
230
|
+
return true;
|
|
231
|
+
} catch {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function warnOption(name, value, fallback) {
|
|
236
|
+
if (typeof console !== "undefined") {
|
|
237
|
+
console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
|
|
241
|
+
if (value === void 0) return fallback;
|
|
242
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
|
|
243
|
+
warnOption(name, value, fallback);
|
|
244
|
+
return fallback;
|
|
245
|
+
}
|
|
246
|
+
function callSafely(callback, ...args) {
|
|
247
|
+
if (!callback) return;
|
|
248
|
+
try {
|
|
249
|
+
const result = callback(...args);
|
|
250
|
+
if (result && typeof result.catch === "function") {
|
|
251
|
+
result.catch(() => void 0);
|
|
252
|
+
}
|
|
253
|
+
} catch {
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function raceAbort(request, signal) {
|
|
257
|
+
return new Promise((resolve, reject) => {
|
|
258
|
+
const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
|
|
259
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
260
|
+
request.then(
|
|
261
|
+
(value) => {
|
|
262
|
+
signal.removeEventListener("abort", onAbort);
|
|
263
|
+
resolve(value);
|
|
264
|
+
},
|
|
265
|
+
(error) => {
|
|
266
|
+
signal.removeEventListener("abort", onAbort);
|
|
267
|
+
reject(error);
|
|
268
|
+
}
|
|
269
|
+
);
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
function discardBody(res) {
|
|
273
|
+
try {
|
|
274
|
+
const closing = res.body?.cancel?.();
|
|
275
|
+
if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
|
|
276
|
+
} catch {
|
|
277
|
+
}
|
|
213
278
|
}
|
|
214
279
|
function sleep(ms) {
|
|
215
280
|
return new Promise((r) => setTimeout(r, ms));
|
|
216
281
|
}
|
|
217
|
-
function
|
|
218
|
-
if (value
|
|
219
|
-
|
|
282
|
+
function cut(value, max) {
|
|
283
|
+
if (value.length <= max) return value;
|
|
284
|
+
const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
|
|
285
|
+
return value.slice(0, end);
|
|
286
|
+
}
|
|
287
|
+
function normalizeUserId(value, max) {
|
|
288
|
+
if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
|
|
289
|
+
if (typeof value !== "string") return void 0;
|
|
290
|
+
return cut(value, max);
|
|
220
291
|
}
|
|
221
292
|
function normalizeEventName(name) {
|
|
222
293
|
if (typeof name !== "string") return null;
|
|
223
294
|
const trimmed = name.trim();
|
|
224
295
|
if (!trimmed) return null;
|
|
225
|
-
return trimmed
|
|
296
|
+
return cut(trimmed, MAX_EVENT_NAME).trimEnd();
|
|
226
297
|
}
|
|
227
298
|
function backoffMs(attempt, base) {
|
|
228
299
|
const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
|
|
@@ -241,46 +312,65 @@ function utf8ByteLength(value) {
|
|
|
241
312
|
}
|
|
242
313
|
return value.length;
|
|
243
314
|
}
|
|
315
|
+
function isStoredEvent(e) {
|
|
316
|
+
if (e === null || typeof e !== "object") return false;
|
|
317
|
+
const ev = e;
|
|
318
|
+
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));
|
|
319
|
+
}
|
|
244
320
|
function mergeQueues(...queues) {
|
|
245
321
|
const seen = /* @__PURE__ */ new Set();
|
|
246
322
|
const out = [];
|
|
247
323
|
for (const q of queues) {
|
|
248
324
|
for (const e of q) {
|
|
325
|
+
if (!isStoredEvent(e)) continue;
|
|
249
326
|
if (seen.has(e.idempotencyKey)) continue;
|
|
250
327
|
seen.add(e.idempotencyKey);
|
|
251
|
-
out.push(e);
|
|
328
|
+
out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
|
|
252
329
|
}
|
|
253
330
|
}
|
|
254
331
|
return out;
|
|
255
332
|
}
|
|
333
|
+
var MAX_PROPERTIES_NODES = 5e4;
|
|
256
334
|
function validateProperties(properties) {
|
|
335
|
+
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
|
|
336
|
+
Object.prototype.toString.call(properties) !== "[object Object]") {
|
|
337
|
+
throw new Error("Eventra: properties must be an object");
|
|
338
|
+
}
|
|
257
339
|
let hasKeys = false;
|
|
258
340
|
for (const _ in properties) {
|
|
259
341
|
hasKeys = true;
|
|
260
342
|
break;
|
|
261
343
|
}
|
|
262
|
-
if (!hasKeys) return
|
|
344
|
+
if (!hasKeys) return {};
|
|
345
|
+
let visited = 0;
|
|
263
346
|
const depth = (obj, level) => {
|
|
264
347
|
if (level > MAX_PROPERTIES_DEPTH) {
|
|
265
348
|
throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
|
|
266
349
|
}
|
|
350
|
+
if (++visited > MAX_PROPERTIES_NODES) {
|
|
351
|
+
throw new Error("Eventra: properties are too large to check");
|
|
352
|
+
}
|
|
267
353
|
if (obj === null || typeof obj !== "object") return;
|
|
268
354
|
if (Array.isArray(obj)) {
|
|
269
355
|
for (const item of obj) depth(item, level + 1);
|
|
270
356
|
return;
|
|
271
357
|
}
|
|
272
|
-
for (const
|
|
273
|
-
depth(
|
|
358
|
+
for (const key in obj) {
|
|
359
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
|
|
274
360
|
}
|
|
275
361
|
};
|
|
276
362
|
depth(properties, 0);
|
|
277
363
|
const json = JSON.stringify(properties);
|
|
278
|
-
if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
364
|
+
if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
279
365
|
throw new Error(
|
|
280
366
|
`Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
|
|
281
367
|
);
|
|
282
368
|
}
|
|
283
|
-
|
|
369
|
+
const copy = JSON.parse(json);
|
|
370
|
+
if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
|
|
371
|
+
throw new Error("Eventra: properties must be an object");
|
|
372
|
+
}
|
|
373
|
+
return copy;
|
|
284
374
|
}
|
|
285
375
|
function parseRetryAfterMs(value) {
|
|
286
376
|
if (!value) return void 0;
|
|
@@ -345,12 +435,19 @@ var Storage = class {
|
|
|
345
435
|
}
|
|
346
436
|
/* v8 ignore stop */
|
|
347
437
|
};
|
|
438
|
+
function storageAvailable() {
|
|
439
|
+
try {
|
|
440
|
+
return typeof localStorage !== "undefined" && localStorage !== null;
|
|
441
|
+
} catch {
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
348
445
|
var Leader = class {
|
|
349
446
|
constructor(onLeadershipChange) {
|
|
350
447
|
this.onLeadershipChange = onLeadershipChange;
|
|
351
448
|
this.tabId = uuidV4();
|
|
352
449
|
this.isLeader = false;
|
|
353
|
-
if (
|
|
450
|
+
if (!storageAvailable()) {
|
|
354
451
|
this.isLeader = true;
|
|
355
452
|
return;
|
|
356
453
|
}
|
|
@@ -437,7 +534,7 @@ var Leader = class {
|
|
|
437
534
|
if (this.onStorage && typeof window !== "undefined") {
|
|
438
535
|
window.removeEventListener("storage", this.onStorage);
|
|
439
536
|
}
|
|
440
|
-
if (this.isLeader &&
|
|
537
|
+
if (this.isLeader && storageAvailable()) {
|
|
441
538
|
try {
|
|
442
539
|
const raw = localStorage.getItem(LEADER_KEY);
|
|
443
540
|
if (raw) {
|
|
@@ -496,70 +593,128 @@ var Eventra = class {
|
|
|
496
593
|
this.nextFlushAt = 0;
|
|
497
594
|
// 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
|
|
498
595
|
this.shutdownDeadline = 0;
|
|
596
|
+
this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
597
|
+
// the page is being left (`pagehide`)
|
|
598
|
+
this.leaving = false;
|
|
499
599
|
this.exitHandlers = [];
|
|
500
|
-
if (!options
|
|
600
|
+
if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
|
|
601
|
+
throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
|
|
602
|
+
}
|
|
603
|
+
if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
|
|
604
|
+
throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
|
|
605
|
+
}
|
|
606
|
+
if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
|
|
607
|
+
throw new Error("Eventra: fetchImpl must be a function");
|
|
608
|
+
}
|
|
501
609
|
activeInstances++;
|
|
502
610
|
if (activeInstances > 1 && typeof console !== "undefined") {
|
|
503
611
|
console.warn(
|
|
504
|
-
"Eventra: multiple SDK instances detected
|
|
612
|
+
"Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
|
|
505
613
|
);
|
|
506
614
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
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();
|
|
615
|
+
try {
|
|
616
|
+
this.options = options;
|
|
617
|
+
this.apiKey = options.apiKey;
|
|
618
|
+
if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
|
|
619
|
+
warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
|
|
539
620
|
}
|
|
540
|
-
this.
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
621
|
+
this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
|
|
622
|
+
if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
|
|
623
|
+
warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
|
|
624
|
+
this.endpoint = DEFAULT_ENDPOINT;
|
|
625
|
+
}
|
|
626
|
+
if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
|
|
627
|
+
warnOption("multiTabMode", options.multiTabMode, "independent");
|
|
628
|
+
}
|
|
629
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
|
|
630
|
+
warnOption("diagnostics", options.diagnostics, "true");
|
|
631
|
+
}
|
|
632
|
+
for (const name of ["maxBatchSize", "maxQueueSize"]) {
|
|
633
|
+
const value = options[name];
|
|
634
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
|
|
635
|
+
warnOption(name, value, Math.floor(value));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
this.runtime = detectRuntime();
|
|
639
|
+
warnIfInsecureEndpoint(this.endpoint);
|
|
640
|
+
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
641
|
+
if (!this.fetch) {
|
|
642
|
+
throw new Error("Eventra: fetch not available - provide fetchImpl");
|
|
643
|
+
}
|
|
644
|
+
this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
|
|
645
|
+
this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
|
|
646
|
+
this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
|
|
647
|
+
this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
|
|
648
|
+
this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
|
|
649
|
+
this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
|
|
650
|
+
this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
|
|
651
|
+
this.persistQueue = options.persistQueue ?? true;
|
|
652
|
+
this.diagnosticsEnabled = options.diagnostics !== false;
|
|
653
|
+
const shared = this.runtime === "browser" && this.persistQueue;
|
|
654
|
+
this.diagnostics = new Diagnostics(
|
|
655
|
+
shared ? new SharedStore(this.storage) : new MemoryStore(),
|
|
656
|
+
DIAGNOSTICS_KEY,
|
|
657
|
+
uuidV4,
|
|
658
|
+
shared ? () => this.scheduleDiagnosticsSync() : void 0
|
|
659
|
+
);
|
|
660
|
+
this.sdkInfo = {
|
|
661
|
+
name: SDK_NAME,
|
|
662
|
+
version: SDK_VERSION,
|
|
663
|
+
runtime: this.runtime
|
|
664
|
+
};
|
|
665
|
+
if (this.runtime === "browser") {
|
|
666
|
+
if (this.persistQueue) {
|
|
667
|
+
this.loadAndMergeQueue();
|
|
668
|
+
}
|
|
669
|
+
this.setupQueueSync();
|
|
670
|
+
}
|
|
671
|
+
if (this.runtime === "browser" && options.multiTabMode === "leader") {
|
|
672
|
+
this.leader = new Leader((isLeader) => {
|
|
673
|
+
if (isLeader) void this.flushNow(false);
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
if (!options.disableTimer) {
|
|
677
|
+
this.startTimer();
|
|
678
|
+
}
|
|
679
|
+
if (this.runtime === "browser") {
|
|
680
|
+
this.setupBrowserExit();
|
|
681
|
+
}
|
|
682
|
+
if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
|
|
683
|
+
this.setupProcessExit();
|
|
684
|
+
}
|
|
685
|
+
Object.defineProperty(this, "apiKey", { enumerable: false });
|
|
686
|
+
Object.defineProperty(this, "options", { enumerable: false });
|
|
687
|
+
} catch (error) {
|
|
688
|
+
this.destroyed = true;
|
|
689
|
+
activeInstances = Math.max(0, activeInstances - 1);
|
|
690
|
+
for (const undo of [
|
|
691
|
+
() => clearInterval(this.timer),
|
|
692
|
+
() => this.leader?.destroy(),
|
|
693
|
+
() => this.channel?.close(),
|
|
694
|
+
() => this.exitHandlers.forEach((undoHandler) => undoHandler())
|
|
695
|
+
]) {
|
|
696
|
+
try {
|
|
697
|
+
undo();
|
|
698
|
+
} catch {
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
throw error;
|
|
555
702
|
}
|
|
556
703
|
}
|
|
557
704
|
track(name, options) {
|
|
705
|
+
try {
|
|
706
|
+
this.trackEvent(name, options);
|
|
707
|
+
} catch {
|
|
708
|
+
this.recordDiagnostic("invalid_event");
|
|
709
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
trackEvent(name, options) {
|
|
558
713
|
if (this.destroyed || this.shuttingDown) return;
|
|
559
714
|
const eventName = normalizeEventName(name);
|
|
560
715
|
if (eventName === null) {
|
|
561
716
|
this.recordDiagnostic("invalid_event");
|
|
562
|
-
this.options.onEventsDropped
|
|
717
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
563
718
|
return;
|
|
564
719
|
}
|
|
565
720
|
let properties;
|
|
@@ -567,18 +722,18 @@ var Eventra = class {
|
|
|
567
722
|
properties = validateProperties(options?.properties ?? {});
|
|
568
723
|
} catch {
|
|
569
724
|
this.recordDiagnostic("invalid_event");
|
|
570
|
-
this.options.onEventsDropped
|
|
725
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
571
726
|
return;
|
|
572
727
|
}
|
|
573
728
|
if (this.queue.length >= this.maxQueue) {
|
|
574
729
|
this.recordDiagnostic("queue_full");
|
|
575
|
-
this.options.onEventsDropped
|
|
730
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
576
731
|
return;
|
|
577
732
|
}
|
|
578
733
|
const event = {
|
|
579
734
|
idempotencyKey: uuidV4(),
|
|
580
735
|
name: eventName,
|
|
581
|
-
userId:
|
|
736
|
+
userId: normalizeUserId(options?.userId, MAX_USER_ID),
|
|
582
737
|
properties,
|
|
583
738
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
584
739
|
};
|
|
@@ -588,13 +743,14 @@ var Eventra = class {
|
|
|
588
743
|
this.broadcast({ type: "queue-add", events: [event] });
|
|
589
744
|
}
|
|
590
745
|
if (this.queue.length >= this.maxBatch) {
|
|
591
|
-
void this.
|
|
746
|
+
void this.flushNow(false);
|
|
592
747
|
}
|
|
593
748
|
if (this.runtime === "serverless") {
|
|
594
|
-
void this.
|
|
749
|
+
void this.flushNow(false);
|
|
595
750
|
}
|
|
596
751
|
}
|
|
597
752
|
async flush() {
|
|
753
|
+
if (this.flushPromise) await this.flushPromise.catch(() => void 0);
|
|
598
754
|
return this.flushNow(false);
|
|
599
755
|
}
|
|
600
756
|
// `force` skips only the Retry-After delay (the last chance at shutdown);
|
|
@@ -621,7 +777,7 @@ var Eventra = class {
|
|
|
621
777
|
}
|
|
622
778
|
async runFlush() {
|
|
623
779
|
try {
|
|
624
|
-
while (this.queue.length > 0) {
|
|
780
|
+
while (this.queue.length > 0 && !this.destroyed) {
|
|
625
781
|
const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
|
|
626
782
|
const batch = this.buildBatch(report);
|
|
627
783
|
if (!batch.events.length) break;
|
|
@@ -670,10 +826,13 @@ var Eventra = class {
|
|
|
670
826
|
* `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
|
|
671
827
|
* hold a SIGTERM shutdown past a typical grace period.
|
|
672
828
|
*/
|
|
673
|
-
|
|
674
|
-
|
|
829
|
+
shutdown() {
|
|
830
|
+
this.shutdownPromise ??= this.runShutdown();
|
|
831
|
+
return this.shutdownPromise;
|
|
832
|
+
}
|
|
833
|
+
async runShutdown() {
|
|
675
834
|
this.shuttingDown = true;
|
|
676
|
-
const budget = this.
|
|
835
|
+
const budget = this.shutdownBudget;
|
|
677
836
|
this.shutdownDeadline = Date.now() + Math.max(0, budget);
|
|
678
837
|
let budgetTimer;
|
|
679
838
|
const outOfTime = new Promise((resolve) => {
|
|
@@ -701,7 +860,10 @@ var Eventra = class {
|
|
|
701
860
|
this.persistNow();
|
|
702
861
|
this.leader?.destroy();
|
|
703
862
|
if (this.channel) {
|
|
704
|
-
|
|
863
|
+
try {
|
|
864
|
+
this.channel.close();
|
|
865
|
+
} catch {
|
|
866
|
+
}
|
|
705
867
|
this.channel = void 0;
|
|
706
868
|
}
|
|
707
869
|
if (this.onStorageQueue && typeof window !== "undefined") {
|
|
@@ -728,7 +890,13 @@ var Eventra = class {
|
|
|
728
890
|
let index = 0;
|
|
729
891
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
730
892
|
const event = this.queue[index];
|
|
731
|
-
|
|
893
|
+
let eventJson;
|
|
894
|
+
try {
|
|
895
|
+
eventJson = JSON.stringify(event);
|
|
896
|
+
} catch {
|
|
897
|
+
this.dropPoisonEvent(event);
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
732
900
|
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
733
901
|
if (total2 > this.maxPayloadBytes) {
|
|
734
902
|
if (events.length === 0) {
|
|
@@ -759,12 +927,13 @@ var Eventra = class {
|
|
|
759
927
|
dropPoisonEvent(event) {
|
|
760
928
|
this.recordDiagnostic("too_large");
|
|
761
929
|
this.removeDelivered([event]);
|
|
762
|
-
this.options.onEventsDropped
|
|
763
|
-
this.options.onDeliveryFailed
|
|
930
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
931
|
+
callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
|
|
764
932
|
}
|
|
765
933
|
removeDelivered(batch) {
|
|
766
934
|
const keys = new Set(batch.map((e) => e.idempotencyKey));
|
|
767
|
-
|
|
935
|
+
const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
|
|
936
|
+
this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
|
|
768
937
|
if (this.runtime === "browser") {
|
|
769
938
|
this.rememberDelivered(keys);
|
|
770
939
|
this.schedulePersist();
|
|
@@ -790,7 +959,8 @@ var Eventra = class {
|
|
|
790
959
|
this.dropPoisonEvents(events);
|
|
791
960
|
return false;
|
|
792
961
|
}
|
|
793
|
-
const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" &&
|
|
962
|
+
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
|
|
963
|
+
payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
794
964
|
const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
|
|
795
965
|
let strippedDiagnostics = false;
|
|
796
966
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
@@ -798,20 +968,24 @@ var Eventra = class {
|
|
|
798
968
|
const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
|
|
799
969
|
const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
|
|
800
970
|
try {
|
|
801
|
-
const res = await
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
971
|
+
const res = await raceAbort(
|
|
972
|
+
this.fetch(this.endpoint, {
|
|
973
|
+
method: "POST",
|
|
974
|
+
headers: {
|
|
975
|
+
"Content-Type": "application/json",
|
|
976
|
+
"x-api-key": this.apiKey
|
|
977
|
+
},
|
|
978
|
+
body: payload,
|
|
979
|
+
signal: controller.signal,
|
|
980
|
+
keepalive: useKeepalive,
|
|
981
|
+
// never follow a redirect: x-api-key is a custom header, so fetch
|
|
982
|
+
// would forward it to wherever a compromised or misconfigured
|
|
983
|
+
// endpoint points
|
|
984
|
+
redirect: "error"
|
|
985
|
+
}),
|
|
986
|
+
controller.signal
|
|
987
|
+
);
|
|
988
|
+
discardBody(res);
|
|
815
989
|
if (res.status === 429 || res.status >= 500) {
|
|
816
990
|
throw new RetryableDeliveryError(
|
|
817
991
|
"retryable delivery error",
|
|
@@ -828,7 +1002,7 @@ var Eventra = class {
|
|
|
828
1002
|
continue;
|
|
829
1003
|
}
|
|
830
1004
|
this.recordDiagnostic("rejected", events.length);
|
|
831
|
-
this.options.onDeliveryFailed
|
|
1005
|
+
callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
|
|
832
1006
|
this.removeDelivered(events);
|
|
833
1007
|
return false;
|
|
834
1008
|
}
|
|
@@ -901,7 +1075,7 @@ var Eventra = class {
|
|
|
901
1075
|
}
|
|
902
1076
|
withoutDelivered(events) {
|
|
903
1077
|
if (!this.deliveredKeys.size) return events;
|
|
904
|
-
return events.filter((e) => !this.deliveredKeys.has(e
|
|
1078
|
+
return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
|
|
905
1079
|
}
|
|
906
1080
|
rememberDelivered(keys) {
|
|
907
1081
|
for (const key of keys) this.deliveredKeys.add(key);
|
|
@@ -944,7 +1118,7 @@ var Eventra = class {
|
|
|
944
1118
|
if (queue.length <= this.maxQueue) return queue;
|
|
945
1119
|
const dropped = queue.length - this.maxQueue;
|
|
946
1120
|
this.recordDiagnostic("queue_full", dropped);
|
|
947
|
-
this.options.onEventsDropped
|
|
1121
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
948
1122
|
return queue.slice(-this.maxQueue);
|
|
949
1123
|
}
|
|
950
1124
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
@@ -957,7 +1131,13 @@ var Eventra = class {
|
|
|
957
1131
|
}
|
|
958
1132
|
setupQueueSync() {
|
|
959
1133
|
if (typeof BroadcastChannel !== "undefined") {
|
|
960
|
-
|
|
1134
|
+
try {
|
|
1135
|
+
this.channel = new BroadcastChannel(CHANNEL_NAME);
|
|
1136
|
+
} catch {
|
|
1137
|
+
this.channel = void 0;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
if (this.channel) {
|
|
961
1141
|
this.channel.onmessage = (e) => {
|
|
962
1142
|
const data = e.data;
|
|
963
1143
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
@@ -983,7 +1163,7 @@ var Eventra = class {
|
|
|
983
1163
|
}
|
|
984
1164
|
startTimer() {
|
|
985
1165
|
this.timer = setInterval(() => {
|
|
986
|
-
void this.
|
|
1166
|
+
void this.flushNow(false);
|
|
987
1167
|
}, this.flushInterval);
|
|
988
1168
|
this.timer.unref?.();
|
|
989
1169
|
}
|
|
@@ -995,6 +1175,7 @@ var Eventra = class {
|
|
|
995
1175
|
}
|
|
996
1176
|
};
|
|
997
1177
|
const pageHide = () => {
|
|
1178
|
+
this.leaving = true;
|
|
998
1179
|
this.persistNow();
|
|
999
1180
|
void this.flush();
|
|
1000
1181
|
};
|
|
@@ -1023,8 +1204,20 @@ var Eventra = class {
|
|
|
1023
1204
|
SIGINT: onSignal("SIGINT"),
|
|
1024
1205
|
SIGTERM: onSignal("SIGTERM")
|
|
1025
1206
|
};
|
|
1207
|
+
const listenAgain = () => {
|
|
1208
|
+
if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
|
|
1209
|
+
};
|
|
1026
1210
|
const onBeforeExit = () => {
|
|
1027
|
-
if (this.queue.length)
|
|
1211
|
+
if (!this.queue.length) {
|
|
1212
|
+
listenAgain();
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
const own = this.shutdownDeadline === 0;
|
|
1216
|
+
if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
|
|
1217
|
+
void this.flush().finally(() => {
|
|
1218
|
+
if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
|
|
1219
|
+
if (!this.queue.length) listenAgain();
|
|
1220
|
+
});
|
|
1028
1221
|
};
|
|
1029
1222
|
proc.once("SIGINT", handlers.SIGINT);
|
|
1030
1223
|
proc.once("SIGTERM", handlers.SIGTERM);
|