@eventra_dev/eventra-sdk 2.0.12 → 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 CHANGED
@@ -8,8 +8,8 @@
8
8
  <a href="https://www.npmjs.com/package/@eventra_dev/eventra-sdk"><img alt="npm version" src="https://img.shields.io/npm/v/@eventra_dev/eventra-sdk.svg?style=flat-square&color=blue"></a>
9
9
  <a href="https://www.npmjs.com/package/@eventra_dev/eventra-sdk"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@eventra_dev/eventra-sdk.svg?style=flat-square&color=blue"></a>
10
10
  <a href="https://github.com/and-1991/eventra-sdk/actions/workflows/test.yml"><img alt="tests" src="https://img.shields.io/github/actions/workflow/status/and-1991/eventra-sdk/test.yml?branch=main&label=tests&style=flat-square&logo=vitest&logoColor=white"></a>
11
- <img alt="tests passing" src="https://img.shields.io/badge/tests-245%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
12
- <img alt="test suites" src="https://img.shields.io/badge/suites-17-brightgreen?style=flat-square">
11
+ <img alt="tests passing" src="https://img.shields.io/badge/tests-266%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
12
+ <img alt="test suites" src="https://img.shields.io/badge/suites-22-brightgreen?style=flat-square">
13
13
  <img alt="coverage" src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&logo=vitest&logoColor=white">
14
14
  <img alt="node" src="https://img.shields.io/node/v/@eventra_dev/eventra-sdk?style=flat-square&color=darkgreen&logo=node.js&logoColor=white">
15
15
  <a href="https://www.typescriptlang.org/"><img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-blue?style=flat-square&logo=typescript&logoColor=white"></a>
@@ -122,7 +122,7 @@ Minimal:
122
122
  tracker.track("app.loaded");
123
123
  ```
124
124
 
125
- Event names are trimmed, cut to 64 characters and trimmed again, `userId` is cut to 120 (API limits); a cut never leaves half of an emoji, so the name is the one the CLI catalog holds. A numeric `userId` is written out as text, and `null` or an object means no user id. `properties` are copied when you call `track()`, so changing the object afterwards does not change the event. `track()` never throws: an empty name, or properties that exceed the depth/size limits, are dropped silently and reported via `onEventsDropped` instead.
125
+ Event names lose NUL, line breaks and half-surrogates (the server removes them too), are trimmed, cut to 64 characters and trimmed again, `userId` is cut to 120 (API limits); a cut never leaves half of an emoji, so the name is the one the CLI catalog holds. A numeric `userId` is written out as text, and `null` or an object means no user id. `properties` are copied when you call `track()`, so changing the object afterwards does not change the event. `track()` never throws: an empty name, or properties that exceed the depth/size limits, are dropped silently and reported via `onEventsDropped` instead. A properties object with more than 50,000 values in all is refused as soon as its keys are listed, without walking it (listing the keys of a huge object is the only cost left: about 0.35 s for a million).
126
126
 
127
127
  ---
128
128
 
@@ -191,6 +191,8 @@ tracker.track("error.occurred", {
191
191
  - Serverless (AWS Lambda is auto-detected and flushes immediately; on Vercel and other platforms call `await tracker.flush()` yourself, as in the example below)
192
192
  - Bun / Deno (not tested)
193
193
 
194
+ The browser mode (persistence, tab-close flush) is used only when `window` and `document` both have `addEventListener`. A global `window` without them (React Native, Deno 1.x) does not count as a browser, so the constructor does not throw there; the queue then lives in memory.
195
+
194
196
  ---
195
197
 
196
198
  ## Usage by Environment
@@ -230,7 +232,11 @@ const tracker = new Eventra({
230
232
  });
231
233
  ```
232
234
 
233
- Writes to `localStorage` are coalesced: a burst of `track()` calls costs one write about 50 ms later, not one write per call, and the queue is written immediately on `pagehide`, when the tab becomes hidden, and on `shutdown()`/`destroy()`. Closing or navigating away never loses events; only a hard crash of the tab in that ~50 ms window can.
235
+ Writes to `localStorage` are coalesced: a burst of `track()` calls costs one write about 50 ms later, not one write per call, and the queue is written immediately on `pagehide`, when the tab becomes hidden, and on `shutdown()`/`destroy()`. Closing or navigating away does not lose events that fit in storage; only a hard crash of the tab in that ~50 ms window can.
236
+
237
+ On `pagehide` what is queued is sent at once with `fetch` `keepalive`, even while another request is still running (the browser cancels that one when the page goes away, so its events are sent again in the keepalive request; the server counts an event once by its idempotency key). One keepalive request carries at most 60,000 bytes (or `maxPayloadBytes` when that is smaller) and 500 events, so a very large queue is not all sent then; the rest stays in `localStorage` for the next visit. After a back/forward cache restore (`pageshow`) requests are normal again.
238
+
239
+ `localStorage` is shared with your own app, so the SDK keeps its queue there to about 1 MB (1,000,000 characters of JSON) and your own writes keep working. When the queue is larger, only the newest events are written; the older ones stay in the in-memory queue and are still delivered while the page is open, but would not survive the page closing before that.
234
240
 
235
241
  Events kept in `localStorage` have a maximum age of 14 days: when the queue is loaded again (page load, another tab writing it), events older than that are dropped. The server only remembers idempotency keys for 30 days, so an event that was already delivered while the page was closing (whose response is never seen) must not be re-sent by a visitor who comes back months later and be counted twice.
236
242
 
@@ -319,7 +325,7 @@ const tracker = new Eventra({
319
325
  | apiKey | Project API key (required). Create it with `SDK` access in the dashboard (a key made for the CLI is refused with 403) |
320
326
  | endpoint | Ingest batch URL |
321
327
  | flushInterval | Flush interval (ms) |
322
- | maxBatchSize | Events per batch |
328
+ | maxBatchSize | Events per batch (default: 50, at most 500 - the most the ingest API accepts in one request) |
323
329
  | maxQueueSize | Max buffer size |
324
330
  | maxRetries | Total delivery attempts per batch (default: 3) |
325
331
  | retryBaseDelayMs | Base delay for exponential backoff (ms) |
@@ -330,12 +336,12 @@ const tracker = new Eventra({
330
336
  | onEventsDropped | Called when events are dropped (queue full, an invalid event, or a single event above `maxPayloadBytes`), normally once per dropped event, so the count is 1; when a saved queue is trimmed at load, the number removed |
331
337
  | onDeliveryFailed | Callback on permanent ingest errors (4xx except 429). The whole rejected batch is dropped, including events that were valid, because the server does not say which one it refused. A single event above `maxPayloadBytes` is reported here too, with status `413`, besides `onEventsDropped` |
332
338
  | multiTabMode | `"independent"` (default) or `"leader"` (browser only) |
333
- | exitOnSignal | Node only. On `SIGINT`/`SIGTERM` the SDK flushes and does nothing else (default `false`); `true` re-raises the signal after the flush when no other listener exists. See [Shutdown](#shutdown) |
339
+ | exitOnSignal | Node only, default `true`: on `SIGINT`/`SIGTERM` the SDK flushes (bounded by `shutdownTimeoutMs`) and then, when no other listener for the signal exists, re-raises it so the process ends as it would without the SDK; when your app has its own listener the SDK only flushes. `false` only flushes and never re-raises. See [Shutdown](#shutdown) |
334
340
  | shutdownTimeoutMs | Total time `shutdown()` may spend flushing (default: 10000). It gives up after this, so a dead or rate-limited server cannot hold a `SIGTERM` shutdown past your grace period |
335
341
  | diagnostics | Report delivery problems (counts only) with the next successful batch, default `true`; `false` sends nothing extra. See [Delivery diagnostics](#delivery-diagnostics) |
336
342
  | persistQueue | Persist the queue to `localStorage` in the browser (browser only, default: `true`) — `false` keeps it in-memory only, avoiding writing `userId`/`properties` to disk |
337
343
 
338
- An option with an invalid value (for example `maxBatchSize: 0` or `NaN`, an empty `endpoint`) is ignored with one console warning and the default is used. Callbacks such as `onEventsDropped` and `onDeliveryFailed` can throw or reject without affecting the SDK. Draining a large queue (hundreds of thousands of events) takes time in proportion to its size. Some values are refused at once instead: an `apiKey` with characters a header cannot carry, a `fetchImpl` that is not a function. `endpoint` that is not a URL, an unknown `multiTabMode`, a `diagnostics` that is not `true` or `false`, a fractional `maxBatchSize` or `maxQueueSize`, and a `maxRetries` above 20 are reported with a warning and replaced. A `userId` that is `NaN` or infinite is no user id.
344
+ An option with an invalid value (for example `maxBatchSize: 0` or `NaN`, an empty `endpoint`) is ignored with one console warning and the default is used. Callbacks such as `onEventsDropped` and `onDeliveryFailed` can throw or reject without affecting the SDK. Draining a large queue (hundreds of thousands of events) takes time in proportion to its size. Some values are refused at once instead: an `apiKey` with characters a header cannot carry, a `fetchImpl` that is not a function. `endpoint` that is not a URL, an unknown `multiTabMode`, a `diagnostics` that is not `true` or `false`, a fractional `maxBatchSize` or `maxQueueSize`, a `maxBatchSize` above 500 (500 is used), and a `maxRetries` above 20 are reported with a warning and replaced. A `userId` that is `NaN` or infinite is no user id.
339
345
 
340
346
  ---
341
347
 
@@ -357,7 +363,24 @@ Graceful shutdown — flush first, then cleanup:
357
363
  await tracker.shutdown();
358
364
  ```
359
365
 
360
- On `SIGINT`/`SIGTERM` the SDK flushes its queue and does nothing else, so it never interrupts your own graceful shutdown (an app that uses `process.once` or framework shutdown hooks has already removed its listener by the time the SDK finishes, and killing the process then would cut that shutdown off). Be aware that registering any signal handler cancels Node's default "exit on SIGINT/SIGTERM": **if the SDK is the only signal handler in your process, your app must exit itself** (for example `process.exit()` after your cleanup), or you can set `exitOnSignal: true`, which makes the SDK re-raise the signal after the flush when no other listener exists.
366
+ On `SIGINT`/`SIGTERM` the SDK flushes its queue (within `shutdownTimeoutMs`). Registering any signal handler cancels Node's default "exit on SIGINT/SIGTERM", so the SDK keeps that default for you:
367
+
368
+ - **Nobody else listens to the signal** (a plain Express server, for example): after the flush the SDK re-raises the signal and the process ends as it would have without the SDK, so `docker stop` or a Kubernetes rollout does not wait for `SIGKILL`. When the process is PID 1 in a container (no init such as `tini`), where a re-raised signal would be ignored, it exits with code 130 (`SIGINT`) or 143 (`SIGTERM`) instead.
369
+ - **Your app has its own listener** (your own `process.on("SIGTERM")`, `process.once`, NestJS `enableShutdownHooks()`): the SDK only flushes and your app owns its shutdown. This is decided when the signal arrives (the SDK's listener runs first), so a listener that removes itself while it shuts down is never cut off by a re-raise.
370
+
371
+ A `process.on`/`process.once` listener of your own replaces Node's default exit, and the SDK does not re-raise next to it, so that listener has to end the process itself. Awaiting `shutdown()` alone leaves the process running:
372
+
373
+ ```ts
374
+ process.on("SIGTERM", async () => {
375
+ await tracker.shutdown();
376
+ // your own cleanup here
377
+ process.exit(0);
378
+ });
379
+ ```
380
+
381
+ If you have nothing else to do on the signal, leave the listener out: the default (`exitOnSignal: true`) already flushes and then ends the process.
382
+
383
+ Set `exitOnSignal: false` to only flush and never re-raise. Then, if the SDK is the only signal handler in your process, **your app must exit itself** (for example `process.exit()` after your cleanup).
361
384
 
362
385
  `shutdown()` has a total time budget (`shutdownTimeoutMs`, default 10 s). While it runs, retries and `Retry-After` waits that do not fit in what is left are skipped and requests are cut at the deadline, so a server that is down or rate limiting cannot hold the process past a typical termination grace period; events that could not be sent stay in the persisted queue (browser) or are lost with the process (Node). The flush timer never keeps a Node process alive on its own, and events still queued when a script ends are sent on `beforeExit` (each time the loop drains, so later ones too, within the same budget); `process.exit()` or a crash skips that. `track()` after `shutdown()` is ignored without a callback. `shutdown()` waits for a flush that is already running before sending what is left.
363
386
 
@@ -442,17 +465,17 @@ Eventra SDK includes:
442
465
 
443
466
  **100% statement/branch/function/line coverage** (v8 provider, `pnpm test:coverage`).
444
467
 
445
- 245 vitest tests across 21 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
468
+ 266 vitest tests across 22 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
446
469
 
447
470
  - `track()` validation — name length, userId truncation, properties depth/size, idempotency keys
448
471
  - Batching — auto-flush at `maxBatchSize`, periodic flush via timer, queue overflow drop
449
472
  - Retry & backoff — 429, 5xx, network errors, no-retry on 4xx, fetch timeout/abort
450
473
  - Circuit breaker - opens after 5 consecutive failed batches (each one after its retries), cools down, resets on success
451
474
  - Payload guards — multi-batch splitting, oversize event dropped via `onDeliveryFailed(413)`
452
- - Shutdown & destroy - flush ordering, timer teardown, idempotent shutdown, the `shutdownTimeoutMs` budget, signal handling (flush only by default, `exitOnSignal`)
475
+ - Shutdown & destroy - flush ordering, timer teardown, idempotent shutdown, the `shutdownTimeoutMs` budget, signal handling (re-raise only when nobody else listens, PID 1, `exitOnSignal: false`)
453
476
  - Persisted queue - coalesced writes, 14-day maximum age, delivered-key filtering, cross-tab merge
454
477
  - Runtime detection — Node, Edge (`EdgeRuntime`), Serverless (AWS Lambda), unknown fallback, Node process exit handling
455
- - Browser mode — persistence, leader election (including multi-tab lease races), BroadcastChannel sync, `fetch` keepalive, `pagehide`
478
+ - Browser mode - persistence (with its size cap), leader election (including multi-tab lease races), BroadcastChannel sync, `fetch` keepalive, `pagehide` while a request is in flight, `pageshow` after a back/forward cache restore, a `window` that is not a browser
456
479
  - Storage edge cases — corrupted/blocked localStorage, quota exceeded, queue trimming
457
480
  - Internal fallbacks - `crypto.getRandomValues` (and a random id when there is no Web Crypto at all, as on Node 18), `Buffer`/string-length byte counting
458
481
  - Regressions: `flush()` waiting for a flush already in flight, properties copied at `track()`, a corrupt stored queue
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.12";
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,17 +213,40 @@ 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;
216
217
  var KEEPALIVE_MAX_BYTES = 6e4;
217
218
  var DELIVERED_KEYS_MAX = 1e4;
218
219
  var activeInstances = 0;
219
220
  function detectRuntime() {
220
221
  const g = globalThis;
221
- if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
222
222
  if (g.EdgeRuntime) return "edge";
223
+ if (hasBrowserEvents()) return "browser";
223
224
  if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
224
225
  if (g.process?.versions?.node) return "node";
225
226
  return "unknown";
226
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
+ }
227
250
  function uuidV4() {
228
251
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
229
252
  return crypto.randomUUID();
@@ -250,6 +273,7 @@ function uuidV4() {
250
273
  }
251
274
  var MAX_TIMER_MS = 2147483647;
252
275
  var MAX_RETRIES = 20;
276
+ var MAX_BATCH_SIZE = 500;
253
277
  function isUrl(value) {
254
278
  try {
255
279
  new URL(value);
@@ -315,9 +339,27 @@ function normalizeUserId(value, max) {
315
339
  if (typeof value !== "string") return void 0;
316
340
  return cut(value, max);
317
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;
359
+ }
318
360
  function normalizeEventName(name) {
319
361
  if (typeof name !== "string") return null;
320
- const trimmed = name.trim();
362
+ const trimmed = stripUnsafeForName(name).trim();
321
363
  if (!trimmed) return null;
322
364
  return cut(trimmed, MAX_EVENT_NAME).trimEnd();
323
365
  }
@@ -356,20 +398,33 @@ function mergeQueues(...queues) {
356
398
  }
357
399
  return out;
358
400
  }
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;
415
+ }
416
+ return `[${parts.reverse().join(",")}]`;
417
+ }
359
418
  var MAX_PROPERTIES_NODES = 5e4;
360
419
  function validateProperties(properties) {
361
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
362
421
  Object.prototype.toString.call(properties) !== "[object Object]") {
363
422
  throw new Error("Eventra: properties must be an object");
364
423
  }
365
- let hasKeys = false;
366
- for (const _ in properties) {
367
- hasKeys = true;
368
- break;
369
- }
370
- if (!hasKeys) return {};
424
+ const topKeys = Object.keys(properties);
425
+ if (topKeys.length === 0) return {};
371
426
  let visited = 0;
372
- const depth = (obj, level) => {
427
+ const depth = (obj, level, keys) => {
373
428
  if (level > MAX_PROPERTIES_DEPTH) {
374
429
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
375
430
  }
@@ -378,14 +433,19 @@ function validateProperties(properties) {
378
433
  }
379
434
  if (obj === null || typeof obj !== "object") return;
380
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
+ }
381
439
  for (const item of obj) depth(item, level + 1);
382
440
  return;
383
441
  }
384
- for (const key in obj) {
385
- if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
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");
386
445
  }
446
+ for (const key of own) depth(obj[key], level + 1);
387
447
  };
388
- depth(properties, 0);
448
+ depth(properties, 0, topKeys);
389
449
  const json = JSON.stringify(properties);
390
450
  if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
391
451
  throw new Error(
@@ -441,9 +501,18 @@ var Storage = class {
441
501
  }
442
502
  }
443
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) {
444
513
  if (!this.enabled) return;
445
514
  try {
446
- localStorage.setItem(key, JSON.stringify(value));
515
+ localStorage.setItem(key, json);
447
516
  } catch {
448
517
  }
449
518
  }
@@ -479,12 +548,9 @@ var Leader = class {
479
548
  }
480
549
  this.tick();
481
550
  this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
482
- if (typeof window !== "undefined") {
483
- this.onStorage = (e) => {
484
- if (e.key === LEADER_KEY) this.tick();
485
- };
486
- window.addEventListener("storage", this.onStorage);
487
- }
551
+ this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
552
+ if (e.key === LEADER_KEY) this.tick();
553
+ });
488
554
  }
489
555
  tick() {
490
556
  const was = this.isLeader;
@@ -557,9 +623,7 @@ var Leader = class {
557
623
  destroy() {
558
624
  if (this.election) clearInterval(this.election);
559
625
  if (this.heartbeat) clearInterval(this.heartbeat);
560
- if (this.onStorage && typeof window !== "undefined") {
561
- window.removeEventListener("storage", this.onStorage);
562
- }
626
+ this.offStorage?.();
563
627
  if (this.isLeader && storageAvailable()) {
564
628
  try {
565
629
  const raw = localStorage.getItem(LEADER_KEY);
@@ -667,7 +731,10 @@ var Eventra = class {
667
731
  if (!this.fetch) {
668
732
  throw new Error("Eventra: fetch not available - provide fetchImpl");
669
733
  }
670
- this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
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)));
671
738
  this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
672
739
  this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
673
740
  this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
@@ -892,9 +959,7 @@ var Eventra = class {
892
959
  }
893
960
  this.channel = void 0;
894
961
  }
895
- if (this.onStorageQueue && typeof window !== "undefined") {
896
- window.removeEventListener("storage", this.onStorageQueue);
897
- }
962
+ this.offStorageQueue?.();
898
963
  for (const off of this.exitHandlers) {
899
964
  off();
900
965
  }
@@ -1138,7 +1203,7 @@ var Eventra = class {
1138
1203
  this.queue
1139
1204
  );
1140
1205
  this.queue = this.trimQueue(merged);
1141
- this.storage.set(QUEUE_KEY, this.queue);
1206
+ this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
1142
1207
  }
1143
1208
  trimQueue(queue = this.queue) {
1144
1209
  if (queue.length <= this.maxQueue) return queue;
@@ -1180,11 +1245,10 @@ var Eventra = class {
1180
1245
  };
1181
1246
  }
1182
1247
  if (this.persistQueue && typeof window !== "undefined") {
1183
- this.onStorageQueue = (e) => {
1248
+ this.offStorageQueue = listen(window, "storage", (e) => {
1184
1249
  if (e.key !== QUEUE_KEY) return;
1185
1250
  this.loadAndMergeQueue();
1186
- };
1187
- window.addEventListener("storage", this.onStorageQueue);
1251
+ });
1188
1252
  }
1189
1253
  }
1190
1254
  startTimer() {
@@ -1203,29 +1267,99 @@ var Eventra = class {
1203
1267
  const pageHide = () => {
1204
1268
  this.leaving = true;
1205
1269
  this.persistNow();
1206
- void this.flush();
1270
+ if (this.inFlight) {
1271
+ this.sendOnLeave();
1272
+ } else {
1273
+ void this.flush();
1274
+ }
1207
1275
  };
1208
- document.addEventListener("visibilitychange", handler);
1209
- window.addEventListener("pagehide", pageHide);
1210
- this.exitHandlers.push(() => {
1211
- document.removeEventListener("visibilitychange", handler);
1212
- window.removeEventListener("pagehide", pageHide);
1213
- });
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
+ }
1214
1341
  }
1215
1342
  setupProcessExit() {
1216
1343
  const proc = globalThis.process;
1217
1344
  if (!proc?.on) return;
1218
- const exitOnSignal = this.options.exitOnSignal === true;
1345
+ const exitOnSignal = this.options.exitOnSignal !== false;
1219
1346
  const onSignal = (signal) => () => {
1347
+ proc.off?.(signal, handlers[signal]);
1348
+ const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
1220
1349
  void this.shutdown().finally(() => {
1221
- if (!exitOnSignal) return;
1222
- proc.off?.(signal, handlers[signal]);
1350
+ if (!exitOnSignal || othersAtSignal) return;
1223
1351
  const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
1224
- if (!othersListening && proc.kill && proc.pid !== void 0) {
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) {
1225
1358
  proc.kill(proc.pid, signal);
1226
1359
  }
1227
1360
  });
1228
1361
  };
1362
+ const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
1229
1363
  const handlers = {
1230
1364
  SIGINT: onSignal("SIGINT"),
1231
1365
  SIGTERM: onSignal("SIGTERM")
@@ -1245,8 +1379,8 @@ var Eventra = class {
1245
1379
  if (!this.queue.length) listenAgain();
1246
1380
  });
1247
1381
  };
1248
- proc.once("SIGINT", handlers.SIGINT);
1249
- proc.once("SIGTERM", handlers.SIGTERM);
1382
+ listenFirst("SIGINT", handlers.SIGINT);
1383
+ listenFirst("SIGTERM", handlers.SIGTERM);
1250
1384
  proc.once("beforeExit", onBeforeExit);
1251
1385
  this.exitHandlers.push(() => {
1252
1386
  proc.off?.("SIGINT", handlers.SIGINT);