@eventra_dev/eventra-sdk 2.0.12 → 2.0.14
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 +36 -13
- package/dist/index.cjs +233 -48
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -6
- package/dist/index.d.ts +18 -6
- package/dist/index.mjs +233 -48
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -2
package/dist/index.d.ts
CHANGED
|
@@ -35,11 +35,13 @@ interface TrackerOptions {
|
|
|
35
35
|
*/
|
|
36
36
|
diagnostics?: boolean;
|
|
37
37
|
/**
|
|
38
|
-
* Node only. On SIGINT/SIGTERM the SDK flushes its queue
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
38
|
+
* Node only. On SIGINT/SIGTERM the SDK flushes its queue (bounded by
|
|
39
|
+
* `shutdownTimeoutMs`). By default (`true`), when no other listener for the
|
|
40
|
+
* signal exists, it then re-raises the signal so the process ends as Node
|
|
41
|
+
* would end it without the SDK; when the app has its own listener the SDK
|
|
42
|
+
* only flushes and the app owns its shutdown. Set `false` to only flush and
|
|
43
|
+
* never re-raise: then, if the SDK is the only handler, the app must exit
|
|
44
|
+
* itself (a signal listener cancels Node's default "exit on signal").
|
|
43
45
|
*/
|
|
44
46
|
exitOnSignal?: boolean;
|
|
45
47
|
/**
|
|
@@ -78,6 +80,7 @@ declare class Eventra {
|
|
|
78
80
|
private fetch;
|
|
79
81
|
private queue;
|
|
80
82
|
private sending;
|
|
83
|
+
private liveTabEvents;
|
|
81
84
|
private inFlight;
|
|
82
85
|
private destroyed;
|
|
83
86
|
private shuttingDown;
|
|
@@ -94,7 +97,7 @@ declare class Eventra {
|
|
|
94
97
|
private storage;
|
|
95
98
|
private leader;
|
|
96
99
|
private channel?;
|
|
97
|
-
private
|
|
100
|
+
private offStorageQueue?;
|
|
98
101
|
private failureCount;
|
|
99
102
|
private warnedRedirect;
|
|
100
103
|
private circuitOpenUntil;
|
|
@@ -141,10 +144,19 @@ declare class Eventra {
|
|
|
141
144
|
private schedulePersist;
|
|
142
145
|
private persistNow;
|
|
143
146
|
private trimQueue;
|
|
147
|
+
private rememberLiveTabEvents;
|
|
148
|
+
private leftToItsTab;
|
|
144
149
|
private broadcast;
|
|
145
150
|
private setupQueueSync;
|
|
146
151
|
private startTimer;
|
|
147
152
|
private setupBrowserExit;
|
|
153
|
+
/**
|
|
154
|
+
* The page is being left while a request is in flight: send what is queued at once with keepalive, without
|
|
155
|
+
* waiting for that request. The events of the batch in flight go along too (after the others, as far as the
|
|
156
|
+
* keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
|
|
157
|
+
* drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
|
|
158
|
+
*/
|
|
159
|
+
private sendOnLeave;
|
|
148
160
|
private setupProcessExit;
|
|
149
161
|
}
|
|
150
162
|
|
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.14";
|
|
171
171
|
var LEADER_KEY = "__eventra_leader__";
|
|
172
172
|
var LEADER_TTL_MS = 4e3;
|
|
173
173
|
var QUEUE_KEY = "__eventra_q__";
|
|
@@ -187,17 +187,42 @@ var RETRY_AFTER_MAX_MS = 3e4;
|
|
|
187
187
|
var PERSIST_DEBOUNCE_MS = 50;
|
|
188
188
|
var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
|
|
189
189
|
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
190
|
+
var PERSISTED_QUEUE_MAX_CHARS = 1e6;
|
|
190
191
|
var KEEPALIVE_MAX_BYTES = 6e4;
|
|
191
192
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
193
|
+
var LIVE_TAB_GRACE_MS = 15e3;
|
|
194
|
+
var LIVE_TAB_KEYS_MAX = 1e4;
|
|
192
195
|
var activeInstances = 0;
|
|
193
196
|
function detectRuntime() {
|
|
194
197
|
const g = globalThis;
|
|
195
|
-
if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
|
|
196
198
|
if (g.EdgeRuntime) return "edge";
|
|
199
|
+
if (hasBrowserEvents()) return "browser";
|
|
197
200
|
if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
|
|
198
201
|
if (g.process?.versions?.node) return "node";
|
|
199
202
|
return "unknown";
|
|
200
203
|
}
|
|
204
|
+
function hasBrowserEvents() {
|
|
205
|
+
try {
|
|
206
|
+
return typeof window !== "undefined" && window !== null && typeof window.addEventListener === "function" && typeof document !== "undefined" && document !== null && typeof document.addEventListener === "function";
|
|
207
|
+
} catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function listen(target, type, listener) {
|
|
212
|
+
const t = target;
|
|
213
|
+
try {
|
|
214
|
+
if (!t || typeof t.addEventListener !== "function") return () => void 0;
|
|
215
|
+
t.addEventListener(type, listener);
|
|
216
|
+
} catch {
|
|
217
|
+
return () => void 0;
|
|
218
|
+
}
|
|
219
|
+
return () => {
|
|
220
|
+
try {
|
|
221
|
+
t.removeEventListener?.(type, listener);
|
|
222
|
+
} catch {
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
201
226
|
function uuidV4() {
|
|
202
227
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
203
228
|
return crypto.randomUUID();
|
|
@@ -224,6 +249,7 @@ function uuidV4() {
|
|
|
224
249
|
}
|
|
225
250
|
var MAX_TIMER_MS = 2147483647;
|
|
226
251
|
var MAX_RETRIES = 20;
|
|
252
|
+
var MAX_BATCH_SIZE = 500;
|
|
227
253
|
function isUrl(value) {
|
|
228
254
|
try {
|
|
229
255
|
new URL(value);
|
|
@@ -289,9 +315,27 @@ function normalizeUserId(value, max) {
|
|
|
289
315
|
if (typeof value !== "string") return void 0;
|
|
290
316
|
return cut(value, max);
|
|
291
317
|
}
|
|
318
|
+
function stripUnsafeForName(value) {
|
|
319
|
+
let out = "";
|
|
320
|
+
for (let i = 0; i < value.length; i++) {
|
|
321
|
+
const code = value.charCodeAt(i);
|
|
322
|
+
if (code === 0 || code === 10 || code === 13) continue;
|
|
323
|
+
if (code >= 55296 && code <= 56319) {
|
|
324
|
+
const next = value.charCodeAt(i + 1);
|
|
325
|
+
if (next >= 56320 && next <= 57343) {
|
|
326
|
+
out += value[i] + value[i + 1];
|
|
327
|
+
i++;
|
|
328
|
+
}
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (code >= 56320 && code <= 57343) continue;
|
|
332
|
+
out += value[i];
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
292
336
|
function normalizeEventName(name) {
|
|
293
337
|
if (typeof name !== "string") return null;
|
|
294
|
-
const trimmed = name.trim();
|
|
338
|
+
const trimmed = stripUnsafeForName(name).trim();
|
|
295
339
|
if (!trimmed) return null;
|
|
296
340
|
return cut(trimmed, MAX_EVENT_NAME).trimEnd();
|
|
297
341
|
}
|
|
@@ -330,20 +374,33 @@ function mergeQueues(...queues) {
|
|
|
330
374
|
}
|
|
331
375
|
return out;
|
|
332
376
|
}
|
|
377
|
+
function persistedQueueJson(queue) {
|
|
378
|
+
const parts = [];
|
|
379
|
+
let chars = 2;
|
|
380
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
381
|
+
let json;
|
|
382
|
+
try {
|
|
383
|
+
json = JSON.stringify(queue[i]);
|
|
384
|
+
} catch {
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const next = chars + json.length + (parts.length ? 1 : 0);
|
|
388
|
+
if (next > PERSISTED_QUEUE_MAX_CHARS) break;
|
|
389
|
+
parts.push(json);
|
|
390
|
+
chars = next;
|
|
391
|
+
}
|
|
392
|
+
return `[${parts.reverse().join(",")}]`;
|
|
393
|
+
}
|
|
333
394
|
var MAX_PROPERTIES_NODES = 5e4;
|
|
334
395
|
function validateProperties(properties) {
|
|
335
396
|
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
397
|
Object.prototype.toString.call(properties) !== "[object Object]") {
|
|
337
398
|
throw new Error("Eventra: properties must be an object");
|
|
338
399
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
hasKeys = true;
|
|
342
|
-
break;
|
|
343
|
-
}
|
|
344
|
-
if (!hasKeys) return {};
|
|
400
|
+
const topKeys = Object.keys(properties);
|
|
401
|
+
if (topKeys.length === 0) return {};
|
|
345
402
|
let visited = 0;
|
|
346
|
-
const depth = (obj, level) => {
|
|
403
|
+
const depth = (obj, level, keys) => {
|
|
347
404
|
if (level > MAX_PROPERTIES_DEPTH) {
|
|
348
405
|
throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
|
|
349
406
|
}
|
|
@@ -352,14 +409,19 @@ function validateProperties(properties) {
|
|
|
352
409
|
}
|
|
353
410
|
if (obj === null || typeof obj !== "object") return;
|
|
354
411
|
if (Array.isArray(obj)) {
|
|
412
|
+
if (visited + obj.length > MAX_PROPERTIES_NODES) {
|
|
413
|
+
throw new Error("Eventra: properties are too large to check");
|
|
414
|
+
}
|
|
355
415
|
for (const item of obj) depth(item, level + 1);
|
|
356
416
|
return;
|
|
357
417
|
}
|
|
358
|
-
|
|
359
|
-
|
|
418
|
+
const own = keys ?? Object.keys(obj);
|
|
419
|
+
if (visited + own.length > MAX_PROPERTIES_NODES) {
|
|
420
|
+
throw new Error("Eventra: properties are too large to check");
|
|
360
421
|
}
|
|
422
|
+
for (const key of own) depth(obj[key], level + 1);
|
|
361
423
|
};
|
|
362
|
-
depth(properties, 0);
|
|
424
|
+
depth(properties, 0, topKeys);
|
|
363
425
|
const json = JSON.stringify(properties);
|
|
364
426
|
if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
365
427
|
throw new Error(
|
|
@@ -394,6 +456,12 @@ var RetryableDeliveryError = class extends Error {
|
|
|
394
456
|
this.name = "RetryableDeliveryError";
|
|
395
457
|
}
|
|
396
458
|
};
|
|
459
|
+
var DeliveryStopped = class extends Error {
|
|
460
|
+
constructor() {
|
|
461
|
+
super("delivery stopped by destroy()");
|
|
462
|
+
this.name = "DeliveryStopped";
|
|
463
|
+
}
|
|
464
|
+
};
|
|
397
465
|
var Storage = class {
|
|
398
466
|
constructor() {
|
|
399
467
|
this.enabled = false;
|
|
@@ -406,6 +474,10 @@ var Storage = class {
|
|
|
406
474
|
} catch {
|
|
407
475
|
}
|
|
408
476
|
}
|
|
477
|
+
// localStorage works here (not in Node, a blocked or private-mode browser)
|
|
478
|
+
get isEnabled() {
|
|
479
|
+
return this.enabled;
|
|
480
|
+
}
|
|
409
481
|
get(key) {
|
|
410
482
|
if (!this.enabled) return null;
|
|
411
483
|
try {
|
|
@@ -415,9 +487,18 @@ var Storage = class {
|
|
|
415
487
|
}
|
|
416
488
|
}
|
|
417
489
|
set(key, value) {
|
|
490
|
+
let json;
|
|
491
|
+
try {
|
|
492
|
+
json = JSON.stringify(value);
|
|
493
|
+
} catch {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
this.setRaw(key, json);
|
|
497
|
+
}
|
|
498
|
+
setRaw(key, json) {
|
|
418
499
|
if (!this.enabled) return;
|
|
419
500
|
try {
|
|
420
|
-
localStorage.setItem(key,
|
|
501
|
+
localStorage.setItem(key, json);
|
|
421
502
|
} catch {
|
|
422
503
|
}
|
|
423
504
|
}
|
|
@@ -453,12 +534,9 @@ var Leader = class {
|
|
|
453
534
|
}
|
|
454
535
|
this.tick();
|
|
455
536
|
this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
};
|
|
460
|
-
window.addEventListener("storage", this.onStorage);
|
|
461
|
-
}
|
|
537
|
+
this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
|
|
538
|
+
if (e.key === LEADER_KEY) this.tick();
|
|
539
|
+
});
|
|
462
540
|
}
|
|
463
541
|
tick() {
|
|
464
542
|
const was = this.isLeader;
|
|
@@ -531,9 +609,7 @@ var Leader = class {
|
|
|
531
609
|
destroy() {
|
|
532
610
|
if (this.election) clearInterval(this.election);
|
|
533
611
|
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
534
|
-
|
|
535
|
-
window.removeEventListener("storage", this.onStorage);
|
|
536
|
-
}
|
|
612
|
+
this.offStorage?.();
|
|
537
613
|
if (this.isLeader && storageAvailable()) {
|
|
538
614
|
try {
|
|
539
615
|
const raw = localStorage.getItem(LEADER_KEY);
|
|
@@ -573,6 +649,8 @@ var Eventra = class {
|
|
|
573
649
|
constructor(options) {
|
|
574
650
|
this.queue = [];
|
|
575
651
|
this.sending = null;
|
|
652
|
+
// events other open tabs announced on the channel, by key, and until when they are theirs to send
|
|
653
|
+
this.liveTabEvents = /* @__PURE__ */ new Map();
|
|
576
654
|
this.inFlight = false;
|
|
577
655
|
this.destroyed = false;
|
|
578
656
|
this.shuttingDown = false;
|
|
@@ -641,7 +719,10 @@ var Eventra = class {
|
|
|
641
719
|
if (!this.fetch) {
|
|
642
720
|
throw new Error("Eventra: fetch not available - provide fetchImpl");
|
|
643
721
|
}
|
|
644
|
-
|
|
722
|
+
if (typeof options.maxBatchSize === "number" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {
|
|
723
|
+
warnOption("maxBatchSize", options.maxBatchSize, MAX_BATCH_SIZE);
|
|
724
|
+
}
|
|
725
|
+
this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1)));
|
|
645
726
|
this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
|
|
646
727
|
this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
|
|
647
728
|
this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
|
|
@@ -858,6 +939,12 @@ var Eventra = class {
|
|
|
858
939
|
activeInstances = Math.max(0, activeInstances - 1);
|
|
859
940
|
if (this.timer) clearInterval(this.timer);
|
|
860
941
|
this.persistNow();
|
|
942
|
+
const kept = this.runtime === "browser" && this.persistQueue && this.storage.isEnabled;
|
|
943
|
+
if (!kept) {
|
|
944
|
+
const inFlight = new Set(this.sending ?? []);
|
|
945
|
+
const lost = this.queue.filter((event) => !inFlight.has(event)).length;
|
|
946
|
+
if (lost > 0) callSafely(this.options.onEventsDropped, lost);
|
|
947
|
+
}
|
|
861
948
|
this.leader?.destroy();
|
|
862
949
|
if (this.channel) {
|
|
863
950
|
try {
|
|
@@ -866,9 +953,7 @@ var Eventra = class {
|
|
|
866
953
|
}
|
|
867
954
|
this.channel = void 0;
|
|
868
955
|
}
|
|
869
|
-
|
|
870
|
-
window.removeEventListener("storage", this.onStorageQueue);
|
|
871
|
-
}
|
|
956
|
+
this.offStorageQueue?.();
|
|
872
957
|
for (const off of this.exitHandlers) {
|
|
873
958
|
off();
|
|
874
959
|
}
|
|
@@ -890,6 +975,10 @@ var Eventra = class {
|
|
|
890
975
|
let index = 0;
|
|
891
976
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
892
977
|
const event = this.queue[index];
|
|
978
|
+
if (this.leftToItsTab(event)) {
|
|
979
|
+
index++;
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
893
982
|
let eventJson;
|
|
894
983
|
try {
|
|
895
984
|
eventJson = JSON.stringify(event);
|
|
@@ -1029,6 +1118,7 @@ var Eventra = class {
|
|
|
1029
1118
|
throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
|
|
1030
1119
|
}
|
|
1031
1120
|
await sleep(wait);
|
|
1121
|
+
if (this.destroyed) throw new DeliveryStopped();
|
|
1032
1122
|
} finally {
|
|
1033
1123
|
clearTimeout(timeout);
|
|
1034
1124
|
}
|
|
@@ -1112,15 +1202,38 @@ var Eventra = class {
|
|
|
1112
1202
|
this.queue
|
|
1113
1203
|
);
|
|
1114
1204
|
this.queue = this.trimQueue(merged);
|
|
1115
|
-
this.storage.
|
|
1205
|
+
this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
|
|
1116
1206
|
}
|
|
1117
1207
|
trimQueue(queue = this.queue) {
|
|
1118
1208
|
if (queue.length <= this.maxQueue) return queue;
|
|
1119
|
-
const
|
|
1120
|
-
this.
|
|
1121
|
-
|
|
1209
|
+
const removed = queue.slice(0, queue.length - this.maxQueue);
|
|
1210
|
+
const dropped = removed.filter((e) => !this.liveTabEvents.has(e?.idempotencyKey)).length;
|
|
1211
|
+
if (dropped > 0) {
|
|
1212
|
+
this.recordDiagnostic("queue_full", dropped);
|
|
1213
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
1214
|
+
}
|
|
1122
1215
|
return queue.slice(-this.maxQueue);
|
|
1123
1216
|
}
|
|
1217
|
+
// events another open tab just announced on the channel, with the time until which that tab sends them
|
|
1218
|
+
rememberLiveTabEvents(events) {
|
|
1219
|
+
const until = Date.now() + LIVE_TAB_GRACE_MS;
|
|
1220
|
+
for (const event of events) {
|
|
1221
|
+
const key = event?.idempotencyKey;
|
|
1222
|
+
if (typeof key === "string" && !this.liveTabEvents.has(key)) this.liveTabEvents.set(key, until);
|
|
1223
|
+
}
|
|
1224
|
+
for (const key of this.liveTabEvents.keys()) {
|
|
1225
|
+
if (this.liveTabEvents.size <= LIVE_TAB_KEYS_MAX) break;
|
|
1226
|
+
this.liveTabEvents.delete(key);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
// In `independent` mode, an event another open tab announced less than LIVE_TAB_GRACE_MS ago is that
|
|
1230
|
+
// tab's to send. After that (the tab was closed, or it cannot reach the server either) anyone sends it.
|
|
1231
|
+
// The leader in `leader` mode sends everything, so it never waits.
|
|
1232
|
+
leftToItsTab(event) {
|
|
1233
|
+
if (this.leader) return false;
|
|
1234
|
+
const until = this.liveTabEvents.get(event?.idempotencyKey);
|
|
1235
|
+
return until !== void 0 && Date.now() < until;
|
|
1236
|
+
}
|
|
1124
1237
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
1125
1238
|
// of structured-cloning the whole queue on every call.
|
|
1126
1239
|
broadcast(message) {
|
|
@@ -1143,22 +1256,24 @@ var Eventra = class {
|
|
|
1143
1256
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
1144
1257
|
const keys = new Set(data.keys);
|
|
1145
1258
|
this.rememberDelivered(keys);
|
|
1259
|
+
for (const key of keys) this.liveTabEvents.delete(key);
|
|
1146
1260
|
this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
|
|
1147
1261
|
return;
|
|
1148
1262
|
}
|
|
1149
1263
|
if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
|
|
1150
1264
|
return;
|
|
1151
1265
|
}
|
|
1152
|
-
|
|
1266
|
+
const announced = this.withoutDelivered(data.events);
|
|
1267
|
+
this.rememberLiveTabEvents(announced);
|
|
1268
|
+
this.queue = mergeQueues(this.queue, announced);
|
|
1153
1269
|
this.queue = this.trimQueue();
|
|
1154
1270
|
};
|
|
1155
1271
|
}
|
|
1156
1272
|
if (this.persistQueue && typeof window !== "undefined") {
|
|
1157
|
-
this.
|
|
1273
|
+
this.offStorageQueue = listen(window, "storage", (e) => {
|
|
1158
1274
|
if (e.key !== QUEUE_KEY) return;
|
|
1159
1275
|
this.loadAndMergeQueue();
|
|
1160
|
-
};
|
|
1161
|
-
window.addEventListener("storage", this.onStorageQueue);
|
|
1276
|
+
});
|
|
1162
1277
|
}
|
|
1163
1278
|
}
|
|
1164
1279
|
startTimer() {
|
|
@@ -1177,29 +1292,99 @@ var Eventra = class {
|
|
|
1177
1292
|
const pageHide = () => {
|
|
1178
1293
|
this.leaving = true;
|
|
1179
1294
|
this.persistNow();
|
|
1180
|
-
|
|
1295
|
+
if (this.inFlight) {
|
|
1296
|
+
this.sendOnLeave();
|
|
1297
|
+
} else {
|
|
1298
|
+
void this.flush();
|
|
1299
|
+
}
|
|
1181
1300
|
};
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1301
|
+
const pageShow = () => {
|
|
1302
|
+
this.leaving = false;
|
|
1303
|
+
};
|
|
1304
|
+
const offs = [
|
|
1305
|
+
listen(document, "visibilitychange", handler),
|
|
1306
|
+
listen(window, "pagehide", pageHide),
|
|
1307
|
+
listen(window, "pageshow", pageShow)
|
|
1308
|
+
];
|
|
1309
|
+
this.exitHandlers.push(() => offs.forEach((off) => off()));
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* The page is being left while a request is in flight: send what is queued at once with keepalive, without
|
|
1313
|
+
* waiting for that request. The events of the batch in flight go along too (after the others, as far as the
|
|
1314
|
+
* keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
|
|
1315
|
+
* drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
|
|
1316
|
+
*/
|
|
1317
|
+
sendOnLeave() {
|
|
1318
|
+
if (this.leader && !this.leader.canSend()) return;
|
|
1319
|
+
const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));
|
|
1320
|
+
const candidates = [
|
|
1321
|
+
...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),
|
|
1322
|
+
...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey))
|
|
1323
|
+
];
|
|
1324
|
+
const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
1325
|
+
const sentAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1326
|
+
let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));
|
|
1327
|
+
const events = [];
|
|
1328
|
+
const json = [];
|
|
1329
|
+
for (const event of candidates) {
|
|
1330
|
+
if (events.length >= MAX_BATCH_SIZE) break;
|
|
1331
|
+
let eventJson;
|
|
1332
|
+
try {
|
|
1333
|
+
eventJson = JSON.stringify(event);
|
|
1334
|
+
} catch {
|
|
1335
|
+
continue;
|
|
1336
|
+
}
|
|
1337
|
+
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
1338
|
+
if (total2 > limit) continue;
|
|
1339
|
+
events.push(event);
|
|
1340
|
+
json.push(eventJson);
|
|
1341
|
+
bytes = total2;
|
|
1342
|
+
}
|
|
1343
|
+
if (!events.length) return;
|
|
1344
|
+
const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });
|
|
1345
|
+
const body = `${head.slice(0, -1)},"events":[${json.join(",")}]}`;
|
|
1346
|
+
try {
|
|
1347
|
+
const request = this.fetch(this.endpoint, {
|
|
1348
|
+
method: "POST",
|
|
1349
|
+
headers: {
|
|
1350
|
+
"Content-Type": "application/json",
|
|
1351
|
+
"x-api-key": this.apiKey
|
|
1352
|
+
},
|
|
1353
|
+
body,
|
|
1354
|
+
keepalive: true,
|
|
1355
|
+
redirect: "error"
|
|
1356
|
+
});
|
|
1357
|
+
Promise.resolve(request).then(
|
|
1358
|
+
(res) => {
|
|
1359
|
+
discardBody(res);
|
|
1360
|
+
if (res.ok && !this.destroyed) this.removeDelivered(events);
|
|
1361
|
+
},
|
|
1362
|
+
() => void 0
|
|
1363
|
+
);
|
|
1364
|
+
} catch {
|
|
1365
|
+
}
|
|
1188
1366
|
}
|
|
1189
1367
|
setupProcessExit() {
|
|
1190
1368
|
const proc = globalThis.process;
|
|
1191
1369
|
if (!proc?.on) return;
|
|
1192
|
-
const exitOnSignal = this.options.exitOnSignal
|
|
1370
|
+
const exitOnSignal = this.options.exitOnSignal !== false;
|
|
1193
1371
|
const onSignal = (signal) => () => {
|
|
1372
|
+
proc.off?.(signal, handlers[signal]);
|
|
1373
|
+
const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1194
1374
|
void this.shutdown().finally(() => {
|
|
1195
|
-
if (!exitOnSignal) return;
|
|
1196
|
-
proc.off?.(signal, handlers[signal]);
|
|
1375
|
+
if (!exitOnSignal || othersAtSignal) return;
|
|
1197
1376
|
const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1198
|
-
if (
|
|
1377
|
+
if (othersListening) return;
|
|
1378
|
+
if (proc.pid === 1 && proc.exit) {
|
|
1379
|
+
proc.exit(128 + (signal === "SIGINT" ? 2 : 15));
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
if (proc.kill && proc.pid !== void 0) {
|
|
1199
1383
|
proc.kill(proc.pid, signal);
|
|
1200
1384
|
}
|
|
1201
1385
|
});
|
|
1202
1386
|
};
|
|
1387
|
+
const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
|
|
1203
1388
|
const handlers = {
|
|
1204
1389
|
SIGINT: onSignal("SIGINT"),
|
|
1205
1390
|
SIGTERM: onSignal("SIGTERM")
|
|
@@ -1219,8 +1404,8 @@ var Eventra = class {
|
|
|
1219
1404
|
if (!this.queue.length) listenAgain();
|
|
1220
1405
|
});
|
|
1221
1406
|
};
|
|
1222
|
-
|
|
1223
|
-
|
|
1407
|
+
listenFirst("SIGINT", handlers.SIGINT);
|
|
1408
|
+
listenFirst("SIGTERM", handlers.SIGTERM);
|
|
1224
1409
|
proc.once("beforeExit", onBeforeExit);
|
|
1225
1410
|
this.exitHandlers.push(() => {
|
|
1226
1411
|
proc.off?.("SIGINT", handlers.SIGINT);
|