@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/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-
|
|
12
|
-
<img alt="test suites" src="https://img.shields.io/badge/suites-
|
|
11
|
+
<img alt="tests passing" src="https://img.shields.io/badge/tests-280%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
|
|
@@ -210,7 +212,7 @@ tracker.track("page.viewed");
|
|
|
210
212
|
- persistence (localStorage)
|
|
211
213
|
- flush on tab close (`fetch` with `keepalive`)
|
|
212
214
|
|
|
213
|
-
By default (`multiTabMode: "independent"`) every open tab shares its pending events with the others and
|
|
215
|
+
By default (`multiTabMode: "independent"`) every open tab shares its pending events with the others, so the events of a tab that closes are not lost. An event another open tab just announced is left to that tab for 15 seconds (it sends within its flush interval and tells the others); only after that does another tab send it, for example when the first tab was closed. Events read back from storage (an earlier page, a closed tab) are sent at once. An event keeps the same idempotency key in every tab, so it is counted once even if two tabs send it. Use `"leader"` to have one tab send for all of them.
|
|
214
216
|
|
|
215
217
|
Optional - single sender across tabs:
|
|
216
218
|
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
|
@@ -368,7 +391,7 @@ await tracker.flush();
|
|
|
368
391
|
await tracker.shutdown();
|
|
369
392
|
```
|
|
370
393
|
|
|
371
|
-
`destroy()` stops timers and listeners immediately without flushing.
|
|
394
|
+
`destroy()` stops timers and listeners immediately without flushing, and a retry that is waiting does not run. In a browser the queue stays in `localStorage` for the next page; where it cannot be kept (Node, `persistQueue: false`, blocked storage) the events still queued are reported to `onEventsDropped` (a batch already in flight is not counted).
|
|
372
395
|
|
|
373
396
|
---
|
|
374
397
|
|
|
@@ -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
|
-
|
|
468
|
+
280 vitest tests across 24 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 (
|
|
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
|
|
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.
|
|
196
|
+
var SDK_VERSION = "2.0.14";
|
|
197
197
|
var LEADER_KEY = "__eventra_leader__";
|
|
198
198
|
var LEADER_TTL_MS = 4e3;
|
|
199
199
|
var QUEUE_KEY = "__eventra_q__";
|
|
@@ -213,17 +213,42 @@ 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;
|
|
219
|
+
var LIVE_TAB_GRACE_MS = 15e3;
|
|
220
|
+
var LIVE_TAB_KEYS_MAX = 1e4;
|
|
218
221
|
var activeInstances = 0;
|
|
219
222
|
function detectRuntime() {
|
|
220
223
|
const g = globalThis;
|
|
221
|
-
if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
|
|
222
224
|
if (g.EdgeRuntime) return "edge";
|
|
225
|
+
if (hasBrowserEvents()) return "browser";
|
|
223
226
|
if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
|
|
224
227
|
if (g.process?.versions?.node) return "node";
|
|
225
228
|
return "unknown";
|
|
226
229
|
}
|
|
230
|
+
function hasBrowserEvents() {
|
|
231
|
+
try {
|
|
232
|
+
return typeof window !== "undefined" && window !== null && typeof window.addEventListener === "function" && typeof document !== "undefined" && document !== null && typeof document.addEventListener === "function";
|
|
233
|
+
} catch {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function listen(target, type, listener) {
|
|
238
|
+
const t = target;
|
|
239
|
+
try {
|
|
240
|
+
if (!t || typeof t.addEventListener !== "function") return () => void 0;
|
|
241
|
+
t.addEventListener(type, listener);
|
|
242
|
+
} catch {
|
|
243
|
+
return () => void 0;
|
|
244
|
+
}
|
|
245
|
+
return () => {
|
|
246
|
+
try {
|
|
247
|
+
t.removeEventListener?.(type, listener);
|
|
248
|
+
} catch {
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
227
252
|
function uuidV4() {
|
|
228
253
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
229
254
|
return crypto.randomUUID();
|
|
@@ -250,6 +275,7 @@ function uuidV4() {
|
|
|
250
275
|
}
|
|
251
276
|
var MAX_TIMER_MS = 2147483647;
|
|
252
277
|
var MAX_RETRIES = 20;
|
|
278
|
+
var MAX_BATCH_SIZE = 500;
|
|
253
279
|
function isUrl(value) {
|
|
254
280
|
try {
|
|
255
281
|
new URL(value);
|
|
@@ -315,9 +341,27 @@ function normalizeUserId(value, max) {
|
|
|
315
341
|
if (typeof value !== "string") return void 0;
|
|
316
342
|
return cut(value, max);
|
|
317
343
|
}
|
|
344
|
+
function stripUnsafeForName(value) {
|
|
345
|
+
let out = "";
|
|
346
|
+
for (let i = 0; i < value.length; i++) {
|
|
347
|
+
const code = value.charCodeAt(i);
|
|
348
|
+
if (code === 0 || code === 10 || code === 13) continue;
|
|
349
|
+
if (code >= 55296 && code <= 56319) {
|
|
350
|
+
const next = value.charCodeAt(i + 1);
|
|
351
|
+
if (next >= 56320 && next <= 57343) {
|
|
352
|
+
out += value[i] + value[i + 1];
|
|
353
|
+
i++;
|
|
354
|
+
}
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (code >= 56320 && code <= 57343) continue;
|
|
358
|
+
out += value[i];
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
318
362
|
function normalizeEventName(name) {
|
|
319
363
|
if (typeof name !== "string") return null;
|
|
320
|
-
const trimmed = name.trim();
|
|
364
|
+
const trimmed = stripUnsafeForName(name).trim();
|
|
321
365
|
if (!trimmed) return null;
|
|
322
366
|
return cut(trimmed, MAX_EVENT_NAME).trimEnd();
|
|
323
367
|
}
|
|
@@ -356,20 +400,33 @@ function mergeQueues(...queues) {
|
|
|
356
400
|
}
|
|
357
401
|
return out;
|
|
358
402
|
}
|
|
403
|
+
function persistedQueueJson(queue) {
|
|
404
|
+
const parts = [];
|
|
405
|
+
let chars = 2;
|
|
406
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
407
|
+
let json;
|
|
408
|
+
try {
|
|
409
|
+
json = JSON.stringify(queue[i]);
|
|
410
|
+
} catch {
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const next = chars + json.length + (parts.length ? 1 : 0);
|
|
414
|
+
if (next > PERSISTED_QUEUE_MAX_CHARS) break;
|
|
415
|
+
parts.push(json);
|
|
416
|
+
chars = next;
|
|
417
|
+
}
|
|
418
|
+
return `[${parts.reverse().join(",")}]`;
|
|
419
|
+
}
|
|
359
420
|
var MAX_PROPERTIES_NODES = 5e4;
|
|
360
421
|
function validateProperties(properties) {
|
|
361
422
|
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
423
|
Object.prototype.toString.call(properties) !== "[object Object]") {
|
|
363
424
|
throw new Error("Eventra: properties must be an object");
|
|
364
425
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
hasKeys = true;
|
|
368
|
-
break;
|
|
369
|
-
}
|
|
370
|
-
if (!hasKeys) return {};
|
|
426
|
+
const topKeys = Object.keys(properties);
|
|
427
|
+
if (topKeys.length === 0) return {};
|
|
371
428
|
let visited = 0;
|
|
372
|
-
const depth = (obj, level) => {
|
|
429
|
+
const depth = (obj, level, keys) => {
|
|
373
430
|
if (level > MAX_PROPERTIES_DEPTH) {
|
|
374
431
|
throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
|
|
375
432
|
}
|
|
@@ -378,14 +435,19 @@ function validateProperties(properties) {
|
|
|
378
435
|
}
|
|
379
436
|
if (obj === null || typeof obj !== "object") return;
|
|
380
437
|
if (Array.isArray(obj)) {
|
|
438
|
+
if (visited + obj.length > MAX_PROPERTIES_NODES) {
|
|
439
|
+
throw new Error("Eventra: properties are too large to check");
|
|
440
|
+
}
|
|
381
441
|
for (const item of obj) depth(item, level + 1);
|
|
382
442
|
return;
|
|
383
443
|
}
|
|
384
|
-
|
|
385
|
-
|
|
444
|
+
const own = keys ?? Object.keys(obj);
|
|
445
|
+
if (visited + own.length > MAX_PROPERTIES_NODES) {
|
|
446
|
+
throw new Error("Eventra: properties are too large to check");
|
|
386
447
|
}
|
|
448
|
+
for (const key of own) depth(obj[key], level + 1);
|
|
387
449
|
};
|
|
388
|
-
depth(properties, 0);
|
|
450
|
+
depth(properties, 0, topKeys);
|
|
389
451
|
const json = JSON.stringify(properties);
|
|
390
452
|
if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
|
|
391
453
|
throw new Error(
|
|
@@ -420,6 +482,12 @@ var RetryableDeliveryError = class extends Error {
|
|
|
420
482
|
this.name = "RetryableDeliveryError";
|
|
421
483
|
}
|
|
422
484
|
};
|
|
485
|
+
var DeliveryStopped = class extends Error {
|
|
486
|
+
constructor() {
|
|
487
|
+
super("delivery stopped by destroy()");
|
|
488
|
+
this.name = "DeliveryStopped";
|
|
489
|
+
}
|
|
490
|
+
};
|
|
423
491
|
var Storage = class {
|
|
424
492
|
constructor() {
|
|
425
493
|
this.enabled = false;
|
|
@@ -432,6 +500,10 @@ var Storage = class {
|
|
|
432
500
|
} catch {
|
|
433
501
|
}
|
|
434
502
|
}
|
|
503
|
+
// localStorage works here (not in Node, a blocked or private-mode browser)
|
|
504
|
+
get isEnabled() {
|
|
505
|
+
return this.enabled;
|
|
506
|
+
}
|
|
435
507
|
get(key) {
|
|
436
508
|
if (!this.enabled) return null;
|
|
437
509
|
try {
|
|
@@ -441,9 +513,18 @@ var Storage = class {
|
|
|
441
513
|
}
|
|
442
514
|
}
|
|
443
515
|
set(key, value) {
|
|
516
|
+
let json;
|
|
517
|
+
try {
|
|
518
|
+
json = JSON.stringify(value);
|
|
519
|
+
} catch {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
this.setRaw(key, json);
|
|
523
|
+
}
|
|
524
|
+
setRaw(key, json) {
|
|
444
525
|
if (!this.enabled) return;
|
|
445
526
|
try {
|
|
446
|
-
localStorage.setItem(key,
|
|
527
|
+
localStorage.setItem(key, json);
|
|
447
528
|
} catch {
|
|
448
529
|
}
|
|
449
530
|
}
|
|
@@ -479,12 +560,9 @@ var Leader = class {
|
|
|
479
560
|
}
|
|
480
561
|
this.tick();
|
|
481
562
|
this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
};
|
|
486
|
-
window.addEventListener("storage", this.onStorage);
|
|
487
|
-
}
|
|
563
|
+
this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
|
|
564
|
+
if (e.key === LEADER_KEY) this.tick();
|
|
565
|
+
});
|
|
488
566
|
}
|
|
489
567
|
tick() {
|
|
490
568
|
const was = this.isLeader;
|
|
@@ -557,9 +635,7 @@ var Leader = class {
|
|
|
557
635
|
destroy() {
|
|
558
636
|
if (this.election) clearInterval(this.election);
|
|
559
637
|
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
560
|
-
|
|
561
|
-
window.removeEventListener("storage", this.onStorage);
|
|
562
|
-
}
|
|
638
|
+
this.offStorage?.();
|
|
563
639
|
if (this.isLeader && storageAvailable()) {
|
|
564
640
|
try {
|
|
565
641
|
const raw = localStorage.getItem(LEADER_KEY);
|
|
@@ -599,6 +675,8 @@ var Eventra = class {
|
|
|
599
675
|
constructor(options) {
|
|
600
676
|
this.queue = [];
|
|
601
677
|
this.sending = null;
|
|
678
|
+
// events other open tabs announced on the channel, by key, and until when they are theirs to send
|
|
679
|
+
this.liveTabEvents = /* @__PURE__ */ new Map();
|
|
602
680
|
this.inFlight = false;
|
|
603
681
|
this.destroyed = false;
|
|
604
682
|
this.shuttingDown = false;
|
|
@@ -667,7 +745,10 @@ var Eventra = class {
|
|
|
667
745
|
if (!this.fetch) {
|
|
668
746
|
throw new Error("Eventra: fetch not available - provide fetchImpl");
|
|
669
747
|
}
|
|
670
|
-
|
|
748
|
+
if (typeof options.maxBatchSize === "number" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {
|
|
749
|
+
warnOption("maxBatchSize", options.maxBatchSize, MAX_BATCH_SIZE);
|
|
750
|
+
}
|
|
751
|
+
this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1)));
|
|
671
752
|
this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
|
|
672
753
|
this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
|
|
673
754
|
this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
|
|
@@ -884,6 +965,12 @@ var Eventra = class {
|
|
|
884
965
|
activeInstances = Math.max(0, activeInstances - 1);
|
|
885
966
|
if (this.timer) clearInterval(this.timer);
|
|
886
967
|
this.persistNow();
|
|
968
|
+
const kept = this.runtime === "browser" && this.persistQueue && this.storage.isEnabled;
|
|
969
|
+
if (!kept) {
|
|
970
|
+
const inFlight = new Set(this.sending ?? []);
|
|
971
|
+
const lost = this.queue.filter((event) => !inFlight.has(event)).length;
|
|
972
|
+
if (lost > 0) callSafely(this.options.onEventsDropped, lost);
|
|
973
|
+
}
|
|
887
974
|
this.leader?.destroy();
|
|
888
975
|
if (this.channel) {
|
|
889
976
|
try {
|
|
@@ -892,9 +979,7 @@ var Eventra = class {
|
|
|
892
979
|
}
|
|
893
980
|
this.channel = void 0;
|
|
894
981
|
}
|
|
895
|
-
|
|
896
|
-
window.removeEventListener("storage", this.onStorageQueue);
|
|
897
|
-
}
|
|
982
|
+
this.offStorageQueue?.();
|
|
898
983
|
for (const off of this.exitHandlers) {
|
|
899
984
|
off();
|
|
900
985
|
}
|
|
@@ -916,6 +1001,10 @@ var Eventra = class {
|
|
|
916
1001
|
let index = 0;
|
|
917
1002
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
918
1003
|
const event = this.queue[index];
|
|
1004
|
+
if (this.leftToItsTab(event)) {
|
|
1005
|
+
index++;
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
919
1008
|
let eventJson;
|
|
920
1009
|
try {
|
|
921
1010
|
eventJson = JSON.stringify(event);
|
|
@@ -1055,6 +1144,7 @@ var Eventra = class {
|
|
|
1055
1144
|
throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
|
|
1056
1145
|
}
|
|
1057
1146
|
await sleep(wait);
|
|
1147
|
+
if (this.destroyed) throw new DeliveryStopped();
|
|
1058
1148
|
} finally {
|
|
1059
1149
|
clearTimeout(timeout);
|
|
1060
1150
|
}
|
|
@@ -1138,15 +1228,38 @@ var Eventra = class {
|
|
|
1138
1228
|
this.queue
|
|
1139
1229
|
);
|
|
1140
1230
|
this.queue = this.trimQueue(merged);
|
|
1141
|
-
this.storage.
|
|
1231
|
+
this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
|
|
1142
1232
|
}
|
|
1143
1233
|
trimQueue(queue = this.queue) {
|
|
1144
1234
|
if (queue.length <= this.maxQueue) return queue;
|
|
1145
|
-
const
|
|
1146
|
-
this.
|
|
1147
|
-
|
|
1235
|
+
const removed = queue.slice(0, queue.length - this.maxQueue);
|
|
1236
|
+
const dropped = removed.filter((e) => !this.liveTabEvents.has(e?.idempotencyKey)).length;
|
|
1237
|
+
if (dropped > 0) {
|
|
1238
|
+
this.recordDiagnostic("queue_full", dropped);
|
|
1239
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
1240
|
+
}
|
|
1148
1241
|
return queue.slice(-this.maxQueue);
|
|
1149
1242
|
}
|
|
1243
|
+
// events another open tab just announced on the channel, with the time until which that tab sends them
|
|
1244
|
+
rememberLiveTabEvents(events) {
|
|
1245
|
+
const until = Date.now() + LIVE_TAB_GRACE_MS;
|
|
1246
|
+
for (const event of events) {
|
|
1247
|
+
const key = event?.idempotencyKey;
|
|
1248
|
+
if (typeof key === "string" && !this.liveTabEvents.has(key)) this.liveTabEvents.set(key, until);
|
|
1249
|
+
}
|
|
1250
|
+
for (const key of this.liveTabEvents.keys()) {
|
|
1251
|
+
if (this.liveTabEvents.size <= LIVE_TAB_KEYS_MAX) break;
|
|
1252
|
+
this.liveTabEvents.delete(key);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
// In `independent` mode, an event another open tab announced less than LIVE_TAB_GRACE_MS ago is that
|
|
1256
|
+
// tab's to send. After that (the tab was closed, or it cannot reach the server either) anyone sends it.
|
|
1257
|
+
// The leader in `leader` mode sends everything, so it never waits.
|
|
1258
|
+
leftToItsTab(event) {
|
|
1259
|
+
if (this.leader) return false;
|
|
1260
|
+
const until = this.liveTabEvents.get(event?.idempotencyKey);
|
|
1261
|
+
return until !== void 0 && Date.now() < until;
|
|
1262
|
+
}
|
|
1150
1263
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
1151
1264
|
// of structured-cloning the whole queue on every call.
|
|
1152
1265
|
broadcast(message) {
|
|
@@ -1169,22 +1282,24 @@ var Eventra = class {
|
|
|
1169
1282
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
1170
1283
|
const keys = new Set(data.keys);
|
|
1171
1284
|
this.rememberDelivered(keys);
|
|
1285
|
+
for (const key of keys) this.liveTabEvents.delete(key);
|
|
1172
1286
|
this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
|
|
1173
1287
|
return;
|
|
1174
1288
|
}
|
|
1175
1289
|
if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
|
|
1176
1290
|
return;
|
|
1177
1291
|
}
|
|
1178
|
-
|
|
1292
|
+
const announced = this.withoutDelivered(data.events);
|
|
1293
|
+
this.rememberLiveTabEvents(announced);
|
|
1294
|
+
this.queue = mergeQueues(this.queue, announced);
|
|
1179
1295
|
this.queue = this.trimQueue();
|
|
1180
1296
|
};
|
|
1181
1297
|
}
|
|
1182
1298
|
if (this.persistQueue && typeof window !== "undefined") {
|
|
1183
|
-
this.
|
|
1299
|
+
this.offStorageQueue = listen(window, "storage", (e) => {
|
|
1184
1300
|
if (e.key !== QUEUE_KEY) return;
|
|
1185
1301
|
this.loadAndMergeQueue();
|
|
1186
|
-
};
|
|
1187
|
-
window.addEventListener("storage", this.onStorageQueue);
|
|
1302
|
+
});
|
|
1188
1303
|
}
|
|
1189
1304
|
}
|
|
1190
1305
|
startTimer() {
|
|
@@ -1203,29 +1318,99 @@ var Eventra = class {
|
|
|
1203
1318
|
const pageHide = () => {
|
|
1204
1319
|
this.leaving = true;
|
|
1205
1320
|
this.persistNow();
|
|
1206
|
-
|
|
1321
|
+
if (this.inFlight) {
|
|
1322
|
+
this.sendOnLeave();
|
|
1323
|
+
} else {
|
|
1324
|
+
void this.flush();
|
|
1325
|
+
}
|
|
1207
1326
|
};
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1327
|
+
const pageShow = () => {
|
|
1328
|
+
this.leaving = false;
|
|
1329
|
+
};
|
|
1330
|
+
const offs = [
|
|
1331
|
+
listen(document, "visibilitychange", handler),
|
|
1332
|
+
listen(window, "pagehide", pageHide),
|
|
1333
|
+
listen(window, "pageshow", pageShow)
|
|
1334
|
+
];
|
|
1335
|
+
this.exitHandlers.push(() => offs.forEach((off) => off()));
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* The page is being left while a request is in flight: send what is queued at once with keepalive, without
|
|
1339
|
+
* waiting for that request. The events of the batch in flight go along too (after the others, as far as the
|
|
1340
|
+
* keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
|
|
1341
|
+
* drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
|
|
1342
|
+
*/
|
|
1343
|
+
sendOnLeave() {
|
|
1344
|
+
if (this.leader && !this.leader.canSend()) return;
|
|
1345
|
+
const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));
|
|
1346
|
+
const candidates = [
|
|
1347
|
+
...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),
|
|
1348
|
+
...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey))
|
|
1349
|
+
];
|
|
1350
|
+
const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
|
|
1351
|
+
const sentAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1352
|
+
let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));
|
|
1353
|
+
const events = [];
|
|
1354
|
+
const json = [];
|
|
1355
|
+
for (const event of candidates) {
|
|
1356
|
+
if (events.length >= MAX_BATCH_SIZE) break;
|
|
1357
|
+
let eventJson;
|
|
1358
|
+
try {
|
|
1359
|
+
eventJson = JSON.stringify(event);
|
|
1360
|
+
} catch {
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
|
|
1364
|
+
if (total2 > limit) continue;
|
|
1365
|
+
events.push(event);
|
|
1366
|
+
json.push(eventJson);
|
|
1367
|
+
bytes = total2;
|
|
1368
|
+
}
|
|
1369
|
+
if (!events.length) return;
|
|
1370
|
+
const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });
|
|
1371
|
+
const body = `${head.slice(0, -1)},"events":[${json.join(",")}]}`;
|
|
1372
|
+
try {
|
|
1373
|
+
const request = this.fetch(this.endpoint, {
|
|
1374
|
+
method: "POST",
|
|
1375
|
+
headers: {
|
|
1376
|
+
"Content-Type": "application/json",
|
|
1377
|
+
"x-api-key": this.apiKey
|
|
1378
|
+
},
|
|
1379
|
+
body,
|
|
1380
|
+
keepalive: true,
|
|
1381
|
+
redirect: "error"
|
|
1382
|
+
});
|
|
1383
|
+
Promise.resolve(request).then(
|
|
1384
|
+
(res) => {
|
|
1385
|
+
discardBody(res);
|
|
1386
|
+
if (res.ok && !this.destroyed) this.removeDelivered(events);
|
|
1387
|
+
},
|
|
1388
|
+
() => void 0
|
|
1389
|
+
);
|
|
1390
|
+
} catch {
|
|
1391
|
+
}
|
|
1214
1392
|
}
|
|
1215
1393
|
setupProcessExit() {
|
|
1216
1394
|
const proc = globalThis.process;
|
|
1217
1395
|
if (!proc?.on) return;
|
|
1218
|
-
const exitOnSignal = this.options.exitOnSignal
|
|
1396
|
+
const exitOnSignal = this.options.exitOnSignal !== false;
|
|
1219
1397
|
const onSignal = (signal) => () => {
|
|
1398
|
+
proc.off?.(signal, handlers[signal]);
|
|
1399
|
+
const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1220
1400
|
void this.shutdown().finally(() => {
|
|
1221
|
-
if (!exitOnSignal) return;
|
|
1222
|
-
proc.off?.(signal, handlers[signal]);
|
|
1401
|
+
if (!exitOnSignal || othersAtSignal) return;
|
|
1223
1402
|
const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
|
|
1224
|
-
if (
|
|
1403
|
+
if (othersListening) return;
|
|
1404
|
+
if (proc.pid === 1 && proc.exit) {
|
|
1405
|
+
proc.exit(128 + (signal === "SIGINT" ? 2 : 15));
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
if (proc.kill && proc.pid !== void 0) {
|
|
1225
1409
|
proc.kill(proc.pid, signal);
|
|
1226
1410
|
}
|
|
1227
1411
|
});
|
|
1228
1412
|
};
|
|
1413
|
+
const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
|
|
1229
1414
|
const handlers = {
|
|
1230
1415
|
SIGINT: onSignal("SIGINT"),
|
|
1231
1416
|
SIGTERM: onSignal("SIGTERM")
|
|
@@ -1245,8 +1430,8 @@ var Eventra = class {
|
|
|
1245
1430
|
if (!this.queue.length) listenAgain();
|
|
1246
1431
|
});
|
|
1247
1432
|
};
|
|
1248
|
-
|
|
1249
|
-
|
|
1433
|
+
listenFirst("SIGINT", handlers.SIGINT);
|
|
1434
|
+
listenFirst("SIGTERM", handlers.SIGTERM);
|
|
1250
1435
|
proc.once("beforeExit", onBeforeExit);
|
|
1251
1436
|
this.exitHandlers.push(() => {
|
|
1252
1437
|
proc.off?.("SIGINT", handlers.SIGINT);
|