@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/README.md +53 -21
- package/dist/index.cjs +472 -145
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -7
- package/dist/index.d.ts +22 -7
- package/dist/index.mjs +472 -145
- 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.13";
|
|
197
197
|
var LEADER_KEY = "__eventra_leader__";
|
|
198
198
|
var LEADER_TTL_MS = 4e3;
|
|
199
199
|
var QUEUE_KEY = "__eventra_q__";
|
|
@@ -213,42 +213,155 @@ 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 PERSISTED_QUEUE_MAX_CHARS = 1e6;
|
|
217
|
+
var KEEPALIVE_MAX_BYTES = 6e4;
|
|
216
218
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
217
219
|
var activeInstances = 0;
|
|
218
220
|
function detectRuntime() {
|
|
219
221
|
const g = globalThis;
|
|
220
|
-
if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
|
|
221
222
|
if (g.EdgeRuntime) return "edge";
|
|
223
|
+
if (hasBrowserEvents()) return "browser";
|
|
222
224
|
if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
|
|
223
225
|
if (g.process?.versions?.node) return "node";
|
|
224
226
|
return "unknown";
|
|
225
227
|
}
|
|
228
|
+
function hasBrowserEvents() {
|
|
229
|
+
try {
|
|
230
|
+
return typeof window !== "undefined" && window !== null && typeof window.addEventListener === "function" && typeof document !== "undefined" && document !== null && typeof document.addEventListener === "function";
|
|
231
|
+
} catch {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function listen(target, type, listener) {
|
|
236
|
+
const t = target;
|
|
237
|
+
try {
|
|
238
|
+
if (!t || typeof t.addEventListener !== "function") return () => void 0;
|
|
239
|
+
t.addEventListener(type, listener);
|
|
240
|
+
} catch {
|
|
241
|
+
return () => void 0;
|
|
242
|
+
}
|
|
243
|
+
return () => {
|
|
244
|
+
try {
|
|
245
|
+
t.removeEventListener?.(type, listener);
|
|
246
|
+
} catch {
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
226
250
|
function uuidV4() {
|
|
227
251
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
228
252
|
return crypto.randomUUID();
|
|
229
253
|
}
|
|
230
254
|
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
|
231
|
-
const
|
|
232
|
-
crypto.getRandomValues(
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
return `${
|
|
237
|
-
}
|
|
238
|
-
|
|
255
|
+
const bytes2 = new Uint8Array(16);
|
|
256
|
+
crypto.getRandomValues(bytes2);
|
|
257
|
+
bytes2[6] = bytes2[6] & 15 | 64;
|
|
258
|
+
bytes2[8] = bytes2[8] & 63 | 128;
|
|
259
|
+
const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
260
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
261
|
+
}
|
|
262
|
+
const bytes = new Uint8Array(16);
|
|
263
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
264
|
+
let t = Date.now();
|
|
265
|
+
for (let i = 0; i < 6; i++) {
|
|
266
|
+
bytes[i] ^= t & 255;
|
|
267
|
+
t = Math.floor(t / 256);
|
|
268
|
+
}
|
|
269
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
270
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
271
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
272
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
273
|
+
}
|
|
274
|
+
var MAX_TIMER_MS = 2147483647;
|
|
275
|
+
var MAX_RETRIES = 20;
|
|
276
|
+
var MAX_BATCH_SIZE = 500;
|
|
277
|
+
function isUrl(value) {
|
|
278
|
+
try {
|
|
279
|
+
new URL(value);
|
|
280
|
+
return true;
|
|
281
|
+
} catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
function warnOption(name, value, fallback) {
|
|
286
|
+
if (typeof console !== "undefined") {
|
|
287
|
+
console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
|
|
291
|
+
if (value === void 0) return fallback;
|
|
292
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
|
|
293
|
+
warnOption(name, value, fallback);
|
|
294
|
+
return fallback;
|
|
295
|
+
}
|
|
296
|
+
function callSafely(callback, ...args) {
|
|
297
|
+
if (!callback) return;
|
|
298
|
+
try {
|
|
299
|
+
const result = callback(...args);
|
|
300
|
+
if (result && typeof result.catch === "function") {
|
|
301
|
+
result.catch(() => void 0);
|
|
302
|
+
}
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function raceAbort(request, signal) {
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
|
|
309
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
310
|
+
request.then(
|
|
311
|
+
(value) => {
|
|
312
|
+
signal.removeEventListener("abort", onAbort);
|
|
313
|
+
resolve(value);
|
|
314
|
+
},
|
|
315
|
+
(error) => {
|
|
316
|
+
signal.removeEventListener("abort", onAbort);
|
|
317
|
+
reject(error);
|
|
318
|
+
}
|
|
319
|
+
);
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
function discardBody(res) {
|
|
323
|
+
try {
|
|
324
|
+
const closing = res.body?.cancel?.();
|
|
325
|
+
if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
239
328
|
}
|
|
240
329
|
function sleep(ms) {
|
|
241
330
|
return new Promise((r) => setTimeout(r, ms));
|
|
242
331
|
}
|
|
243
|
-
function
|
|
244
|
-
if (value
|
|
245
|
-
|
|
332
|
+
function cut(value, max) {
|
|
333
|
+
if (value.length <= max) return value;
|
|
334
|
+
const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
|
|
335
|
+
return value.slice(0, end);
|
|
336
|
+
}
|
|
337
|
+
function normalizeUserId(value, max) {
|
|
338
|
+
if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
|
|
339
|
+
if (typeof value !== "string") return void 0;
|
|
340
|
+
return cut(value, max);
|
|
341
|
+
}
|
|
342
|
+
function stripUnsafeForName(value) {
|
|
343
|
+
let out = "";
|
|
344
|
+
for (let i = 0; i < value.length; i++) {
|
|
345
|
+
const code = value.charCodeAt(i);
|
|
346
|
+
if (code === 0 || code === 10 || code === 13) continue;
|
|
347
|
+
if (code >= 55296 && code <= 56319) {
|
|
348
|
+
const next = value.charCodeAt(i + 1);
|
|
349
|
+
if (next >= 56320 && next <= 57343) {
|
|
350
|
+
out += value[i] + value[i + 1];
|
|
351
|
+
i++;
|
|
352
|
+
}
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (code >= 56320 && code <= 57343) continue;
|
|
356
|
+
out += value[i];
|
|
357
|
+
}
|
|
358
|
+
return out;
|
|
246
359
|
}
|
|
247
360
|
function normalizeEventName(name) {
|
|
248
361
|
if (typeof name !== "string") return null;
|
|
249
|
-
const trimmed = name.trim();
|
|
362
|
+
const trimmed = stripUnsafeForName(name).trim();
|
|
250
363
|
if (!trimmed) return null;
|
|
251
|
-
return trimmed
|
|
364
|
+
return cut(trimmed, MAX_EVENT_NAME).trimEnd();
|
|
252
365
|
}
|
|
253
366
|
function backoffMs(attempt, base) {
|
|
254
367
|
const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
|
|
@@ -267,46 +380,83 @@ function utf8ByteLength(value) {
|
|
|
267
380
|
}
|
|
268
381
|
return value.length;
|
|
269
382
|
}
|
|
383
|
+
function isStoredEvent(e) {
|
|
384
|
+
if (e === null || typeof e !== "object") return false;
|
|
385
|
+
const ev = e;
|
|
386
|
+
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));
|
|
387
|
+
}
|
|
270
388
|
function mergeQueues(...queues) {
|
|
271
389
|
const seen = /* @__PURE__ */ new Set();
|
|
272
390
|
const out = [];
|
|
273
391
|
for (const q of queues) {
|
|
274
392
|
for (const e of q) {
|
|
393
|
+
if (!isStoredEvent(e)) continue;
|
|
275
394
|
if (seen.has(e.idempotencyKey)) continue;
|
|
276
395
|
seen.add(e.idempotencyKey);
|
|
277
|
-
out.push(e);
|
|
396
|
+
out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
|
|
278
397
|
}
|
|
279
398
|
}
|
|
280
399
|
return out;
|
|
281
400
|
}
|
|
282
|
-
function
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
401
|
+
function persistedQueueJson(queue) {
|
|
402
|
+
const parts = [];
|
|
403
|
+
let chars = 2;
|
|
404
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
405
|
+
let json;
|
|
406
|
+
try {
|
|
407
|
+
json = JSON.stringify(queue[i]);
|
|
408
|
+
} catch {
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const next = chars + json.length + (parts.length ? 1 : 0);
|
|
412
|
+
if (next > PERSISTED_QUEUE_MAX_CHARS) break;
|
|
413
|
+
parts.push(json);
|
|
414
|
+
chars = next;
|
|
287
415
|
}
|
|
288
|
-
|
|
289
|
-
|
|
416
|
+
return `[${parts.reverse().join(",")}]`;
|
|
417
|
+
}
|
|
418
|
+
var MAX_PROPERTIES_NODES = 5e4;
|
|
419
|
+
function validateProperties(properties) {
|
|
420
|
+
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
|
|
421
|
+
Object.prototype.toString.call(properties) !== "[object Object]") {
|
|
422
|
+
throw new Error("Eventra: properties must be an object");
|
|
423
|
+
}
|
|
424
|
+
const topKeys = Object.keys(properties);
|
|
425
|
+
if (topKeys.length === 0) return {};
|
|
426
|
+
let visited = 0;
|
|
427
|
+
const depth = (obj, level, keys) => {
|
|
290
428
|
if (level > MAX_PROPERTIES_DEPTH) {
|
|
291
429
|
throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
|
|
292
430
|
}
|
|
431
|
+
if (++visited > MAX_PROPERTIES_NODES) {
|
|
432
|
+
throw new Error("Eventra: properties are too large to check");
|
|
433
|
+
}
|
|
293
434
|
if (obj === null || typeof obj !== "object") return;
|
|
294
435
|
if (Array.isArray(obj)) {
|
|
436
|
+
if (visited + obj.length > MAX_PROPERTIES_NODES) {
|
|
437
|
+
throw new Error("Eventra: properties are too large to check");
|
|
438
|
+
}
|
|
295
439
|
for (const item of obj) depth(item, level + 1);
|
|
296
440
|
return;
|
|
297
441
|
}
|
|
298
|
-
|
|
299
|
-
|
|
442
|
+
const own = keys ?? Object.keys(obj);
|
|
443
|
+
if (visited + own.length > MAX_PROPERTIES_NODES) {
|
|
444
|
+
throw new Error("Eventra: properties are too large to check");
|
|
300
445
|
}
|
|
446
|
+
for (const key of own) depth(obj[key], level + 1);
|
|
301
447
|
};
|
|
302
|
-
depth(properties, 0);
|
|
448
|
+
depth(properties, 0, topKeys);
|
|
303
449
|
const json = JSON.stringify(properties);
|
|
304
|
-
if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
450
|
+
if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
305
451
|
throw new Error(
|
|
306
452
|
`Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
|
|
307
453
|
);
|
|
308
454
|
}
|
|
309
|
-
|
|
455
|
+
const copy = JSON.parse(json);
|
|
456
|
+
if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
|
|
457
|
+
throw new Error("Eventra: properties must be an object");
|
|
458
|
+
}
|
|
459
|
+
return copy;
|
|
310
460
|
}
|
|
311
461
|
function parseRetryAfterMs(value) {
|
|
312
462
|
if (!value) return void 0;
|
|
@@ -351,9 +501,18 @@ var Storage = class {
|
|
|
351
501
|
}
|
|
352
502
|
}
|
|
353
503
|
set(key, value) {
|
|
504
|
+
let json;
|
|
505
|
+
try {
|
|
506
|
+
json = JSON.stringify(value);
|
|
507
|
+
} catch {
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
this.setRaw(key, json);
|
|
511
|
+
}
|
|
512
|
+
setRaw(key, json) {
|
|
354
513
|
if (!this.enabled) return;
|
|
355
514
|
try {
|
|
356
|
-
localStorage.setItem(key,
|
|
515
|
+
localStorage.setItem(key, json);
|
|
357
516
|
} catch {
|
|
358
517
|
}
|
|
359
518
|
}
|
|
@@ -371,23 +530,27 @@ var Storage = class {
|
|
|
371
530
|
}
|
|
372
531
|
/* v8 ignore stop */
|
|
373
532
|
};
|
|
533
|
+
function storageAvailable() {
|
|
534
|
+
try {
|
|
535
|
+
return typeof localStorage !== "undefined" && localStorage !== null;
|
|
536
|
+
} catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
374
540
|
var Leader = class {
|
|
375
541
|
constructor(onLeadershipChange) {
|
|
376
542
|
this.onLeadershipChange = onLeadershipChange;
|
|
377
543
|
this.tabId = uuidV4();
|
|
378
544
|
this.isLeader = false;
|
|
379
|
-
if (
|
|
545
|
+
if (!storageAvailable()) {
|
|
380
546
|
this.isLeader = true;
|
|
381
547
|
return;
|
|
382
548
|
}
|
|
383
549
|
this.tick();
|
|
384
550
|
this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
};
|
|
389
|
-
window.addEventListener("storage", this.onStorage);
|
|
390
|
-
}
|
|
551
|
+
this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
|
|
552
|
+
if (e.key === LEADER_KEY) this.tick();
|
|
553
|
+
});
|
|
391
554
|
}
|
|
392
555
|
tick() {
|
|
393
556
|
const was = this.isLeader;
|
|
@@ -460,10 +623,8 @@ var Leader = class {
|
|
|
460
623
|
destroy() {
|
|
461
624
|
if (this.election) clearInterval(this.election);
|
|
462
625
|
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
466
|
-
if (this.isLeader && typeof localStorage !== "undefined") {
|
|
626
|
+
this.offStorage?.();
|
|
627
|
+
if (this.isLeader && storageAvailable()) {
|
|
467
628
|
try {
|
|
468
629
|
const raw = localStorage.getItem(LEADER_KEY);
|
|
469
630
|
if (raw) {
|
|
@@ -522,70 +683,131 @@ var Eventra = class {
|
|
|
522
683
|
this.nextFlushAt = 0;
|
|
523
684
|
// 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
|
|
524
685
|
this.shutdownDeadline = 0;
|
|
686
|
+
this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
687
|
+
// the page is being left (`pagehide`)
|
|
688
|
+
this.leaving = false;
|
|
525
689
|
this.exitHandlers = [];
|
|
526
|
-
if (!options
|
|
690
|
+
if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
|
|
691
|
+
throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
|
|
692
|
+
}
|
|
693
|
+
if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
|
|
694
|
+
throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
|
|
695
|
+
}
|
|
696
|
+
if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
|
|
697
|
+
throw new Error("Eventra: fetchImpl must be a function");
|
|
698
|
+
}
|
|
527
699
|
activeInstances++;
|
|
528
700
|
if (activeInstances > 1 && typeof console !== "undefined") {
|
|
529
701
|
console.warn(
|
|
530
|
-
"Eventra: multiple SDK instances detected
|
|
702
|
+
"Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
|
|
531
703
|
);
|
|
532
704
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
539
|
-
if (!this.fetch) {
|
|
540
|
-
throw new Error("Eventra: fetch not available \u2014 provide fetchImpl");
|
|
541
|
-
}
|
|
542
|
-
this.maxBatch = options.maxBatchSize ?? 50;
|
|
543
|
-
this.maxQueue = options.maxQueueSize ?? 1e4;
|
|
544
|
-
this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
545
|
-
this.flushInterval = options.flushInterval ?? 2e3;
|
|
546
|
-
this.retries = options.maxRetries ?? 3;
|
|
547
|
-
this.retryDelay = options.retryBaseDelayMs ?? 300;
|
|
548
|
-
this.persistQueue = options.persistQueue ?? true;
|
|
549
|
-
this.diagnosticsEnabled = options.diagnostics !== false;
|
|
550
|
-
const shared = this.runtime === "browser" && this.persistQueue;
|
|
551
|
-
this.diagnostics = new Diagnostics(
|
|
552
|
-
shared ? new SharedStore(this.storage) : new MemoryStore(),
|
|
553
|
-
DIAGNOSTICS_KEY,
|
|
554
|
-
uuidV4,
|
|
555
|
-
shared ? () => this.scheduleDiagnosticsSync() : void 0
|
|
556
|
-
);
|
|
557
|
-
this.sdkInfo = {
|
|
558
|
-
name: SDK_NAME,
|
|
559
|
-
version: SDK_VERSION,
|
|
560
|
-
runtime: this.runtime
|
|
561
|
-
};
|
|
562
|
-
if (this.runtime === "browser") {
|
|
563
|
-
if (this.persistQueue) {
|
|
564
|
-
this.loadAndMergeQueue();
|
|
705
|
+
try {
|
|
706
|
+
this.options = options;
|
|
707
|
+
this.apiKey = options.apiKey;
|
|
708
|
+
if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
|
|
709
|
+
warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
|
|
565
710
|
}
|
|
566
|
-
this.
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
711
|
+
this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
|
|
712
|
+
if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
|
|
713
|
+
warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
|
|
714
|
+
this.endpoint = DEFAULT_ENDPOINT;
|
|
715
|
+
}
|
|
716
|
+
if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
|
|
717
|
+
warnOption("multiTabMode", options.multiTabMode, "independent");
|
|
718
|
+
}
|
|
719
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
|
|
720
|
+
warnOption("diagnostics", options.diagnostics, "true");
|
|
721
|
+
}
|
|
722
|
+
for (const name of ["maxBatchSize", "maxQueueSize"]) {
|
|
723
|
+
const value = options[name];
|
|
724
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
|
|
725
|
+
warnOption(name, value, Math.floor(value));
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
this.runtime = detectRuntime();
|
|
729
|
+
warnIfInsecureEndpoint(this.endpoint);
|
|
730
|
+
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
731
|
+
if (!this.fetch) {
|
|
732
|
+
throw new Error("Eventra: fetch not available - provide fetchImpl");
|
|
733
|
+
}
|
|
734
|
+
if (typeof options.maxBatchSize === "number" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {
|
|
735
|
+
warnOption("maxBatchSize", options.maxBatchSize, MAX_BATCH_SIZE);
|
|
736
|
+
}
|
|
737
|
+
this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1)));
|
|
738
|
+
this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
|
|
739
|
+
this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
|
|
740
|
+
this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
|
|
741
|
+
this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
|
|
742
|
+
this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
|
|
743
|
+
this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
|
|
744
|
+
this.persistQueue = options.persistQueue ?? true;
|
|
745
|
+
this.diagnosticsEnabled = options.diagnostics !== false;
|
|
746
|
+
const shared = this.runtime === "browser" && this.persistQueue;
|
|
747
|
+
this.diagnostics = new Diagnostics(
|
|
748
|
+
shared ? new SharedStore(this.storage) : new MemoryStore(),
|
|
749
|
+
DIAGNOSTICS_KEY,
|
|
750
|
+
uuidV4,
|
|
751
|
+
shared ? () => this.scheduleDiagnosticsSync() : void 0
|
|
752
|
+
);
|
|
753
|
+
this.sdkInfo = {
|
|
754
|
+
name: SDK_NAME,
|
|
755
|
+
version: SDK_VERSION,
|
|
756
|
+
runtime: this.runtime
|
|
757
|
+
};
|
|
758
|
+
if (this.runtime === "browser") {
|
|
759
|
+
if (this.persistQueue) {
|
|
760
|
+
this.loadAndMergeQueue();
|
|
761
|
+
}
|
|
762
|
+
this.setupQueueSync();
|
|
763
|
+
}
|
|
764
|
+
if (this.runtime === "browser" && options.multiTabMode === "leader") {
|
|
765
|
+
this.leader = new Leader((isLeader) => {
|
|
766
|
+
if (isLeader) void this.flushNow(false);
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
if (!options.disableTimer) {
|
|
770
|
+
this.startTimer();
|
|
771
|
+
}
|
|
772
|
+
if (this.runtime === "browser") {
|
|
773
|
+
this.setupBrowserExit();
|
|
774
|
+
}
|
|
775
|
+
if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
|
|
776
|
+
this.setupProcessExit();
|
|
777
|
+
}
|
|
778
|
+
Object.defineProperty(this, "apiKey", { enumerable: false });
|
|
779
|
+
Object.defineProperty(this, "options", { enumerable: false });
|
|
780
|
+
} catch (error) {
|
|
781
|
+
this.destroyed = true;
|
|
782
|
+
activeInstances = Math.max(0, activeInstances - 1);
|
|
783
|
+
for (const undo of [
|
|
784
|
+
() => clearInterval(this.timer),
|
|
785
|
+
() => this.leader?.destroy(),
|
|
786
|
+
() => this.channel?.close(),
|
|
787
|
+
() => this.exitHandlers.forEach((undoHandler) => undoHandler())
|
|
788
|
+
]) {
|
|
789
|
+
try {
|
|
790
|
+
undo();
|
|
791
|
+
} catch {
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
throw error;
|
|
581
795
|
}
|
|
582
796
|
}
|
|
583
797
|
track(name, options) {
|
|
798
|
+
try {
|
|
799
|
+
this.trackEvent(name, options);
|
|
800
|
+
} catch {
|
|
801
|
+
this.recordDiagnostic("invalid_event");
|
|
802
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
trackEvent(name, options) {
|
|
584
806
|
if (this.destroyed || this.shuttingDown) return;
|
|
585
807
|
const eventName = normalizeEventName(name);
|
|
586
808
|
if (eventName === null) {
|
|
587
809
|
this.recordDiagnostic("invalid_event");
|
|
588
|
-
this.options.onEventsDropped
|
|
810
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
589
811
|
return;
|
|
590
812
|
}
|
|
591
813
|
let properties;
|
|
@@ -593,18 +815,18 @@ var Eventra = class {
|
|
|
593
815
|
properties = validateProperties(options?.properties ?? {});
|
|
594
816
|
} catch {
|
|
595
817
|
this.recordDiagnostic("invalid_event");
|
|
596
|
-
this.options.onEventsDropped
|
|
818
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
597
819
|
return;
|
|
598
820
|
}
|
|
599
821
|
if (this.queue.length >= this.maxQueue) {
|
|
600
822
|
this.recordDiagnostic("queue_full");
|
|
601
|
-
this.options.onEventsDropped
|
|
823
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
602
824
|
return;
|
|
603
825
|
}
|
|
604
826
|
const event = {
|
|
605
827
|
idempotencyKey: uuidV4(),
|
|
606
828
|
name: eventName,
|
|
607
|
-
userId:
|
|
829
|
+
userId: normalizeUserId(options?.userId, MAX_USER_ID),
|
|
608
830
|
properties,
|
|
609
831
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
610
832
|
};
|
|
@@ -614,13 +836,14 @@ var Eventra = class {
|
|
|
614
836
|
this.broadcast({ type: "queue-add", events: [event] });
|
|
615
837
|
}
|
|
616
838
|
if (this.queue.length >= this.maxBatch) {
|
|
617
|
-
void this.
|
|
839
|
+
void this.flushNow(false);
|
|
618
840
|
}
|
|
619
841
|
if (this.runtime === "serverless") {
|
|
620
|
-
void this.
|
|
842
|
+
void this.flushNow(false);
|
|
621
843
|
}
|
|
622
844
|
}
|
|
623
845
|
async flush() {
|
|
846
|
+
if (this.flushPromise) await this.flushPromise.catch(() => void 0);
|
|
624
847
|
return this.flushNow(false);
|
|
625
848
|
}
|
|
626
849
|
// `force` skips only the Retry-After delay (the last chance at shutdown);
|
|
@@ -647,7 +870,7 @@ var Eventra = class {
|
|
|
647
870
|
}
|
|
648
871
|
async runFlush() {
|
|
649
872
|
try {
|
|
650
|
-
while (this.queue.length > 0) {
|
|
873
|
+
while (this.queue.length > 0 && !this.destroyed) {
|
|
651
874
|
const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
|
|
652
875
|
const batch = this.buildBatch(report);
|
|
653
876
|
if (!batch.events.length) break;
|
|
@@ -696,10 +919,13 @@ var Eventra = class {
|
|
|
696
919
|
* `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
|
|
697
920
|
* hold a SIGTERM shutdown past a typical grace period.
|
|
698
921
|
*/
|
|
699
|
-
|
|
700
|
-
|
|
922
|
+
shutdown() {
|
|
923
|
+
this.shutdownPromise ??= this.runShutdown();
|
|
924
|
+
return this.shutdownPromise;
|
|
925
|
+
}
|
|
926
|
+
async runShutdown() {
|
|
701
927
|
this.shuttingDown = true;
|
|
702
|
-
const budget = this.
|
|
928
|
+
const budget = this.shutdownBudget;
|
|
703
929
|
this.shutdownDeadline = Date.now() + Math.max(0, budget);
|
|
704
930
|
let budgetTimer;
|
|
705
931
|
const outOfTime = new Promise((resolve) => {
|
|
@@ -727,12 +953,13 @@ var Eventra = class {
|
|
|
727
953
|
this.persistNow();
|
|
728
954
|
this.leader?.destroy();
|
|
729
955
|
if (this.channel) {
|
|
730
|
-
|
|
956
|
+
try {
|
|
957
|
+
this.channel.close();
|
|
958
|
+
} catch {
|
|
959
|
+
}
|
|
731
960
|
this.channel = void 0;
|
|
732
961
|
}
|
|
733
|
-
|
|
734
|
-
window.removeEventListener("storage", this.onStorageQueue);
|
|
735
|
-
}
|
|
962
|
+
this.offStorageQueue?.();
|
|
736
963
|
for (const off of this.exitHandlers) {
|
|
737
964
|
off();
|
|
738
965
|
}
|
|
@@ -754,7 +981,13 @@ var Eventra = class {
|
|
|
754
981
|
let index = 0;
|
|
755
982
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
756
983
|
const event = this.queue[index];
|
|
757
|
-
|
|
984
|
+
let eventJson;
|
|
985
|
+
try {
|
|
986
|
+
eventJson = JSON.stringify(event);
|
|
987
|
+
} catch {
|
|
988
|
+
this.dropPoisonEvent(event);
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
758
991
|
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
759
992
|
if (total2 > this.maxPayloadBytes) {
|
|
760
993
|
if (events.length === 0) {
|
|
@@ -785,12 +1018,13 @@ var Eventra = class {
|
|
|
785
1018
|
dropPoisonEvent(event) {
|
|
786
1019
|
this.recordDiagnostic("too_large");
|
|
787
1020
|
this.removeDelivered([event]);
|
|
788
|
-
this.options.onEventsDropped
|
|
789
|
-
this.options.onDeliveryFailed
|
|
1021
|
+
callSafely(this.options.onEventsDropped, 1);
|
|
1022
|
+
callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
|
|
790
1023
|
}
|
|
791
1024
|
removeDelivered(batch) {
|
|
792
1025
|
const keys = new Set(batch.map((e) => e.idempotencyKey));
|
|
793
|
-
|
|
1026
|
+
const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
|
|
1027
|
+
this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
|
|
794
1028
|
if (this.runtime === "browser") {
|
|
795
1029
|
this.rememberDelivered(keys);
|
|
796
1030
|
this.schedulePersist();
|
|
@@ -816,7 +1050,8 @@ var Eventra = class {
|
|
|
816
1050
|
this.dropPoisonEvents(events);
|
|
817
1051
|
return false;
|
|
818
1052
|
}
|
|
819
|
-
const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" &&
|
|
1053
|
+
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
|
|
1054
|
+
payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
820
1055
|
const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
|
|
821
1056
|
let strippedDiagnostics = false;
|
|
822
1057
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
@@ -824,20 +1059,24 @@ var Eventra = class {
|
|
|
824
1059
|
const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
|
|
825
1060
|
const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
|
|
826
1061
|
try {
|
|
827
|
-
const res = await
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
1062
|
+
const res = await raceAbort(
|
|
1063
|
+
this.fetch(this.endpoint, {
|
|
1064
|
+
method: "POST",
|
|
1065
|
+
headers: {
|
|
1066
|
+
"Content-Type": "application/json",
|
|
1067
|
+
"x-api-key": this.apiKey
|
|
1068
|
+
},
|
|
1069
|
+
body: payload,
|
|
1070
|
+
signal: controller.signal,
|
|
1071
|
+
keepalive: useKeepalive,
|
|
1072
|
+
// never follow a redirect: x-api-key is a custom header, so fetch
|
|
1073
|
+
// would forward it to wherever a compromised or misconfigured
|
|
1074
|
+
// endpoint points
|
|
1075
|
+
redirect: "error"
|
|
1076
|
+
}),
|
|
1077
|
+
controller.signal
|
|
1078
|
+
);
|
|
1079
|
+
discardBody(res);
|
|
841
1080
|
if (res.status === 429 || res.status >= 500) {
|
|
842
1081
|
throw new RetryableDeliveryError(
|
|
843
1082
|
"retryable delivery error",
|
|
@@ -854,7 +1093,7 @@ var Eventra = class {
|
|
|
854
1093
|
continue;
|
|
855
1094
|
}
|
|
856
1095
|
this.recordDiagnostic("rejected", events.length);
|
|
857
|
-
this.options.onDeliveryFailed
|
|
1096
|
+
callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
|
|
858
1097
|
this.removeDelivered(events);
|
|
859
1098
|
return false;
|
|
860
1099
|
}
|
|
@@ -927,7 +1166,7 @@ var Eventra = class {
|
|
|
927
1166
|
}
|
|
928
1167
|
withoutDelivered(events) {
|
|
929
1168
|
if (!this.deliveredKeys.size) return events;
|
|
930
|
-
return events.filter((e) => !this.deliveredKeys.has(e
|
|
1169
|
+
return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
|
|
931
1170
|
}
|
|
932
1171
|
rememberDelivered(keys) {
|
|
933
1172
|
for (const key of keys) this.deliveredKeys.add(key);
|
|
@@ -964,13 +1203,13 @@ var Eventra = class {
|
|
|
964
1203
|
this.queue
|
|
965
1204
|
);
|
|
966
1205
|
this.queue = this.trimQueue(merged);
|
|
967
|
-
this.storage.
|
|
1206
|
+
this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
|
|
968
1207
|
}
|
|
969
1208
|
trimQueue(queue = this.queue) {
|
|
970
1209
|
if (queue.length <= this.maxQueue) return queue;
|
|
971
1210
|
const dropped = queue.length - this.maxQueue;
|
|
972
1211
|
this.recordDiagnostic("queue_full", dropped);
|
|
973
|
-
this.options.onEventsDropped
|
|
1212
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
974
1213
|
return queue.slice(-this.maxQueue);
|
|
975
1214
|
}
|
|
976
1215
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
@@ -983,7 +1222,13 @@ var Eventra = class {
|
|
|
983
1222
|
}
|
|
984
1223
|
setupQueueSync() {
|
|
985
1224
|
if (typeof BroadcastChannel !== "undefined") {
|
|
986
|
-
|
|
1225
|
+
try {
|
|
1226
|
+
this.channel = new BroadcastChannel(CHANNEL_NAME);
|
|
1227
|
+
} catch {
|
|
1228
|
+
this.channel = void 0;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
if (this.channel) {
|
|
987
1232
|
this.channel.onmessage = (e) => {
|
|
988
1233
|
const data = e.data;
|
|
989
1234
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
@@ -1000,16 +1245,15 @@ var Eventra = class {
|
|
|
1000
1245
|
};
|
|
1001
1246
|
}
|
|
1002
1247
|
if (this.persistQueue && typeof window !== "undefined") {
|
|
1003
|
-
this.
|
|
1248
|
+
this.offStorageQueue = listen(window, "storage", (e) => {
|
|
1004
1249
|
if (e.key !== QUEUE_KEY) return;
|
|
1005
1250
|
this.loadAndMergeQueue();
|
|
1006
|
-
};
|
|
1007
|
-
window.addEventListener("storage", this.onStorageQueue);
|
|
1251
|
+
});
|
|
1008
1252
|
}
|
|
1009
1253
|
}
|
|
1010
1254
|
startTimer() {
|
|
1011
1255
|
this.timer = setInterval(() => {
|
|
1012
|
-
void this.
|
|
1256
|
+
void this.flushNow(false);
|
|
1013
1257
|
}, this.flushInterval);
|
|
1014
1258
|
this.timer.unref?.();
|
|
1015
1259
|
}
|
|
@@ -1021,39 +1265,122 @@ var Eventra = class {
|
|
|
1021
1265
|
}
|
|
1022
1266
|
};
|
|
1023
1267
|
const pageHide = () => {
|
|
1268
|
+
this.leaving = true;
|
|
1024
1269
|
this.persistNow();
|
|
1025
|
-
|
|
1270
|
+
if (this.inFlight) {
|
|
1271
|
+
this.sendOnLeave();
|
|
1272
|
+
} else {
|
|
1273
|
+
void this.flush();
|
|
1274
|
+
}
|
|
1026
1275
|
};
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1276
|
+
const pageShow = () => {
|
|
1277
|
+
this.leaving = false;
|
|
1278
|
+
};
|
|
1279
|
+
const offs = [
|
|
1280
|
+
listen(document, "visibilitychange", handler),
|
|
1281
|
+
listen(window, "pagehide", pageHide),
|
|
1282
|
+
listen(window, "pageshow", pageShow)
|
|
1283
|
+
];
|
|
1284
|
+
this.exitHandlers.push(() => offs.forEach((off) => off()));
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* The page is being left while a request is in flight: send what is queued at once with keepalive, without
|
|
1288
|
+
* waiting for that request. The events of the batch in flight go along too (after the others, as far as the
|
|
1289
|
+
* keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
|
|
1290
|
+
* drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
|
|
1291
|
+
*/
|
|
1292
|
+
sendOnLeave() {
|
|
1293
|
+
if (this.leader && !this.leader.canSend()) return;
|
|
1294
|
+
const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));
|
|
1295
|
+
const candidates = [
|
|
1296
|
+
...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),
|
|
1297
|
+
...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey))
|
|
1298
|
+
];
|
|
1299
|
+
const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
1300
|
+
const sentAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1301
|
+
let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));
|
|
1302
|
+
const events = [];
|
|
1303
|
+
const json = [];
|
|
1304
|
+
for (const event of candidates) {
|
|
1305
|
+
if (events.length >= MAX_BATCH_SIZE) break;
|
|
1306
|
+
let eventJson;
|
|
1307
|
+
try {
|
|
1308
|
+
eventJson = JSON.stringify(event);
|
|
1309
|
+
} catch {
|
|
1310
|
+
continue;
|
|
1311
|
+
}
|
|
1312
|
+
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
1313
|
+
if (total2 > limit) continue;
|
|
1314
|
+
events.push(event);
|
|
1315
|
+
json.push(eventJson);
|
|
1316
|
+
bytes = total2;
|
|
1317
|
+
}
|
|
1318
|
+
if (!events.length) return;
|
|
1319
|
+
const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });
|
|
1320
|
+
const body = `${head.slice(0, -1)},"events":[${json.join(",")}]}`;
|
|
1321
|
+
try {
|
|
1322
|
+
const request = this.fetch(this.endpoint, {
|
|
1323
|
+
method: "POST",
|
|
1324
|
+
headers: {
|
|
1325
|
+
"Content-Type": "application/json",
|
|
1326
|
+
"x-api-key": this.apiKey
|
|
1327
|
+
},
|
|
1328
|
+
body,
|
|
1329
|
+
keepalive: true,
|
|
1330
|
+
redirect: "error"
|
|
1331
|
+
});
|
|
1332
|
+
Promise.resolve(request).then(
|
|
1333
|
+
(res) => {
|
|
1334
|
+
discardBody(res);
|
|
1335
|
+
if (res.ok && !this.destroyed) this.removeDelivered(events);
|
|
1336
|
+
},
|
|
1337
|
+
() => void 0
|
|
1338
|
+
);
|
|
1339
|
+
} catch {
|
|
1340
|
+
}
|
|
1033
1341
|
}
|
|
1034
1342
|
setupProcessExit() {
|
|
1035
1343
|
const proc = globalThis.process;
|
|
1036
1344
|
if (!proc?.on) return;
|
|
1037
|
-
const exitOnSignal = this.options.exitOnSignal
|
|
1345
|
+
const exitOnSignal = this.options.exitOnSignal !== false;
|
|
1038
1346
|
const onSignal = (signal) => () => {
|
|
1347
|
+
proc.off?.(signal, handlers[signal]);
|
|
1348
|
+
const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1039
1349
|
void this.shutdown().finally(() => {
|
|
1040
|
-
if (!exitOnSignal) return;
|
|
1041
|
-
proc.off?.(signal, handlers[signal]);
|
|
1350
|
+
if (!exitOnSignal || othersAtSignal) return;
|
|
1042
1351
|
const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1043
|
-
if (
|
|
1352
|
+
if (othersListening) return;
|
|
1353
|
+
if (proc.pid === 1 && proc.exit) {
|
|
1354
|
+
proc.exit(128 + (signal === "SIGINT" ? 2 : 15));
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (proc.kill && proc.pid !== void 0) {
|
|
1044
1358
|
proc.kill(proc.pid, signal);
|
|
1045
1359
|
}
|
|
1046
1360
|
});
|
|
1047
1361
|
};
|
|
1362
|
+
const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
|
|
1048
1363
|
const handlers = {
|
|
1049
1364
|
SIGINT: onSignal("SIGINT"),
|
|
1050
1365
|
SIGTERM: onSignal("SIGTERM")
|
|
1051
1366
|
};
|
|
1367
|
+
const listenAgain = () => {
|
|
1368
|
+
if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
|
|
1369
|
+
};
|
|
1052
1370
|
const onBeforeExit = () => {
|
|
1053
|
-
if (this.queue.length)
|
|
1371
|
+
if (!this.queue.length) {
|
|
1372
|
+
listenAgain();
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
const own = this.shutdownDeadline === 0;
|
|
1376
|
+
if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
|
|
1377
|
+
void this.flush().finally(() => {
|
|
1378
|
+
if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
|
|
1379
|
+
if (!this.queue.length) listenAgain();
|
|
1380
|
+
});
|
|
1054
1381
|
};
|
|
1055
|
-
|
|
1056
|
-
|
|
1382
|
+
listenFirst("SIGINT", handlers.SIGINT);
|
|
1383
|
+
listenFirst("SIGTERM", handlers.SIGTERM);
|
|
1057
1384
|
proc.once("beforeExit", onBeforeExit);
|
|
1058
1385
|
this.exitHandlers.push(() => {
|
|
1059
1386
|
proc.off?.("SIGINT", handlers.SIGINT);
|