@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/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-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 to 64 characters, `userId` to 120 (API limits). `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,9 @@ tracker.track("page.viewed");
|
|
|
210
212
|
- persistence (localStorage)
|
|
211
213
|
- flush on tab close (`fetch` with `keepalive`)
|
|
212
214
|
|
|
213
|
-
|
|
215
|
+
By default (`multiTabMode: "independent"`) every open tab shares its pending events with the others and each tab may deliver them. An event keeps the same idempotency key in every tab, so it is counted once, but the number of requests grows with the number of open tabs. Use `"leader"` to have one tab send for all of them.
|
|
216
|
+
|
|
217
|
+
Optional - single sender across tabs:
|
|
214
218
|
|
|
215
219
|
```ts
|
|
216
220
|
const tracker = new Eventra({
|
|
@@ -228,11 +232,15 @@ const tracker = new Eventra({
|
|
|
228
232
|
});
|
|
229
233
|
```
|
|
230
234
|
|
|
231
|
-
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.
|
|
232
240
|
|
|
233
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.
|
|
234
242
|
|
|
235
|
-
With `persistQueue: false`, nothing is written to `localStorage`; the queue lives in memory only and is lost if the page closes before delivery (
|
|
243
|
+
With `persistQueue: false`, nothing is written to `localStorage`; the queue lives in memory only and is lost if the page closes before delivery (sharing events between tabs via `BroadcastChannel` still works, since that's never written to disk).
|
|
236
244
|
|
|
237
245
|
---
|
|
238
246
|
|
|
@@ -256,11 +264,13 @@ tracker.track("invoice.created");
|
|
|
256
264
|
### Serverless (IMPORTANT)
|
|
257
265
|
|
|
258
266
|
```ts
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
267
|
+
// created once, outside the handler: the platform reuses it between invocations.
|
|
268
|
+
// A new Eventra per call keeps adding exit listeners and is never cleaned up.
|
|
269
|
+
const tracker = new Eventra({
|
|
270
|
+
apiKey: "...",
|
|
271
|
+
});
|
|
263
272
|
|
|
273
|
+
export default async function handler(req, res) {
|
|
264
274
|
tracker.track("function.called");
|
|
265
275
|
|
|
266
276
|
await tracker.flush();
|
|
@@ -315,22 +325,24 @@ const tracker = new Eventra({
|
|
|
315
325
|
| apiKey | Project API key (required). Create it with `SDK` access in the dashboard (a key made for the CLI is refused with 403) |
|
|
316
326
|
| endpoint | Ingest batch URL |
|
|
317
327
|
| flushInterval | Flush interval (ms) |
|
|
318
|
-
| maxBatchSize | Events per batch |
|
|
328
|
+
| maxBatchSize | Events per batch (default: 50, at most 500 - the most the ingest API accepts in one request) |
|
|
319
329
|
| maxQueueSize | Max buffer size |
|
|
320
330
|
| maxRetries | Total delivery attempts per batch (default: 3) |
|
|
321
331
|
| retryBaseDelayMs | Base delay for exponential backoff (ms) |
|
|
322
332
|
| maxPayloadBytes | Max serialized batch size (default: 60000) |
|
|
323
333
|
| fetchImpl | Custom `fetch` (Node without native fetch, tests) |
|
|
324
|
-
| autoFlushOnExit |
|
|
334
|
+
| autoFlushOnExit | Node / serverless, default `true`: flush what is queued when the script ends by itself (`beforeExit`, bounded by `shutdownTimeoutMs`) and on `SIGINT`/`SIGTERM`. `process.exit()` and a crash do not run it, so call `await tracker.shutdown()` first |
|
|
325
335
|
| disableTimer | Disable periodic flush timer |
|
|
326
|
-
| onEventsDropped | Called
|
|
327
|
-
| onDeliveryFailed | Callback on permanent ingest errors (4xx except 429) |
|
|
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 |
|
|
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` |
|
|
328
338
|
| multiTabMode | `"independent"` (default) or `"leader"` (browser only) |
|
|
329
|
-
| 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) |
|
|
330
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 |
|
|
331
341
|
| diagnostics | Report delivery problems (counts only) with the next successful batch, default `true`; `false` sends nothing extra. See [Delivery diagnostics](#delivery-diagnostics) |
|
|
332
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 |
|
|
333
343
|
|
|
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.
|
|
345
|
+
|
|
334
346
|
---
|
|
335
347
|
|
|
336
348
|
## Manual Flush
|
|
@@ -339,6 +351,8 @@ const tracker = new Eventra({
|
|
|
339
351
|
await tracker.flush();
|
|
340
352
|
```
|
|
341
353
|
|
|
354
|
+
`flush()` also waits for a send that is already running (the timer, a full batch, or the per-call flush on serverless), so awaiting it in a serverless handler is enough. While the circuit breaker is open or a `Retry-After` wait is active it resolves without sending, and the events stay queued.
|
|
355
|
+
|
|
342
356
|
---
|
|
343
357
|
|
|
344
358
|
## Shutdown
|
|
@@ -349,9 +363,26 @@ Graceful shutdown — flush first, then cleanup:
|
|
|
349
363
|
await tracker.shutdown();
|
|
350
364
|
```
|
|
351
365
|
|
|
352
|
-
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).
|
|
353
384
|
|
|
354
|
-
`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
|
|
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.
|
|
355
386
|
|
|
356
387
|
For Node / serverless, prefer explicit shutdown over relying on process signals:
|
|
357
388
|
|
|
@@ -434,19 +465,20 @@ Eventra SDK includes:
|
|
|
434
465
|
|
|
435
466
|
**100% statement/branch/function/line coverage** (v8 provider, `pnpm test:coverage`).
|
|
436
467
|
|
|
437
|
-
|
|
468
|
+
266 vitest tests across 22 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
|
|
438
469
|
|
|
439
470
|
- `track()` validation — name length, userId truncation, properties depth/size, idempotency keys
|
|
440
471
|
- Batching — auto-flush at `maxBatchSize`, periodic flush via timer, queue overflow drop
|
|
441
472
|
- Retry & backoff — 429, 5xx, network errors, no-retry on 4xx, fetch timeout/abort
|
|
442
473
|
- Circuit breaker - opens after 5 consecutive failed batches (each one after its retries), cools down, resets on success
|
|
443
474
|
- Payload guards — multi-batch splitting, oversize event dropped via `onDeliveryFailed(413)`
|
|
444
|
-
- 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`)
|
|
445
476
|
- Persisted queue - coalesced writes, 14-day maximum age, delivered-key filtering, cross-tab merge
|
|
446
477
|
- Runtime detection — Node, Edge (`EdgeRuntime`), Serverless (AWS Lambda), unknown fallback, Node process exit handling
|
|
447
|
-
- 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
|
|
448
479
|
- Storage edge cases — corrupted/blocked localStorage, quota exceeded, queue trimming
|
|
449
|
-
- Internal fallbacks
|
|
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
|
|
481
|
+
- Regressions: `flush()` waiting for a flush already in flight, properties copied at `track()`, a corrupt stored queue
|
|
450
482
|
|
|
451
483
|
Run locally:
|
|
452
484
|
|