@eventra_dev/eventra-sdk 2.0.13 → 2.1.0

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,7 +8,7 @@
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-266%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
11
+ <img alt="tests passing" src="https://img.shields.io/badge/tests-358%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
12
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">
@@ -85,6 +85,48 @@ The SDK automatically handles:
85
85
 
86
86
  ---
87
87
 
88
+ ## Identify users
89
+
90
+ Unique users, the Users page and per-user numbers in the dashboard (Top users, users on Declining) need to know whose event it is. Without a `userId` the events still count as uses (dead, new and declining features work as before), but nothing can be counted per user.
91
+
92
+ Already pass `userId` to every `track()`? Nothing to change: it still works and can be mixed with the methods below.
93
+
94
+ **Browser and React Native:** call `identify()` once after sign-in (and when the page loads with a signed-in user), and `reset()` in your sign-out handler. Every following `track()` gets that user:
95
+
96
+ ```ts
97
+ tracker.identify(user.id);
98
+ tracker.track("export.clicked"); // sent with userId = user.id
99
+
100
+ // in your sign-out handler (not while auth is still loading)
101
+ tracker.reset();
102
+ ```
103
+
104
+ - The user is kept in `localStorage` (with `persistQueue: false` in memory only, and a user stored earlier is removed), so the first events after a reload are not sent without it.
105
+ - `identify()` and `reset()` reach every open tab of the site. `reset()` also removes a user stored by an earlier visit.
106
+ - The stored user belongs to your API key: another Eventra project on the same site (a third-party widget, say) never sees it or resets it.
107
+ - `getUserId()` returns the current user.
108
+ - In React Native `identify()` works in memory. In Next.js and other SSR apps, call it in client code (an effect), not while rendering on the server.
109
+
110
+ **Everywhere else** (Node, serverless, edge, Deno, Cloudflare Workers) one instance may serve many users at once, so `identify()` is ignored there with one warning. Use `withUser()` for each request instead:
111
+
112
+ ```ts
113
+ // in a request handler (Express, Nest, a serverless function); req.user is set by your auth middleware
114
+ app.post("/invoices", (req: Request & { user?: { id: string } }, res) => {
115
+ tracker.withUser(req.user?.id).track("invoice.created", { properties: { plan: "pro" } }); // undefined: no user
116
+ res.sendStatus(201);
117
+ });
118
+ ```
119
+
120
+ `withUser()` returns a light object over the same queue, so making one per request is cheap. It works in every runtime. `withUser(undefined)`, `withUser(null)` or an invalid id give events without a user, never the user of `identify()`. Call it where you track (or keep it in a typed variable): the Eventra CLI finds `tracker.withUser(id).track("x")` and `const t = tracker.withUser(id); t.track("x")`, but not a scope stored on an untyped object such as `req.tracker`.
121
+
122
+ **Which user an event gets:** the `userId` passed to `track()` first (`null` sends the event without a user; an empty or blank one counts as not given), then the user of `withUser()`, then the one of `identify()`. The user is fixed when `track()` is called, so an event tracked just before `reset()` keeps its user.
123
+
124
+ Pass your own internal id (or a hash of it), never an email or a phone number. `identify()` and `withUser()` refuse text that names nobody (`"undefined"`, `"null"`, blanks), which is what `String(user?.id)` gives for a missing user.
125
+
126
+ The SDK warns once when none of the first 50 events has a user id: in a browser bundle that is not built for production, and on a server only when `NODE_ENV` is `development` (Lambda and many containers set none in production). Test runs (`NODE_ENV=test`) never warn. `identifyHint: false` turns it off for an app without signed-in users.
127
+
128
+ ---
129
+
88
130
  ## Runtime Behavior
89
131
 
90
132
  Eventra SDK adapts automatically:
@@ -95,7 +137,7 @@ Eventra SDK adapts automatically:
95
137
  | Node.js | batching + retry |
96
138
  | Serverless (AWS Lambda only) | immediate flush + retry |
97
139
  | Edge | batching + retry |
98
- | Anything else (e.g. Cloudflare Workers) | not distinctly detected — falls back to the same batching + retry path as Node.js |
140
+ | Anything else (e.g. Cloudflare Workers) | not distinctly detected - falls back to the same batching + retry path as Node.js |
99
141
 
100
142
  No config needed.
101
143
 
@@ -122,7 +164,7 @@ Minimal:
122
164
  tracker.track("app.loaded");
123
165
  ```
124
166
 
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).
167
+ 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 (`null` also overrides a user set by `identify()` or `withUser()`). `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
168
 
127
169
  ---
128
170
 
@@ -212,7 +254,7 @@ tracker.track("page.viewed");
212
254
  - persistence (localStorage)
213
255
  - flush on tab close (`fetch` with `keepalive`)
214
256
 
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.
257
+ 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.
216
258
 
217
259
  Optional - single sender across tabs:
218
260
 
@@ -223,7 +265,7 @@ const tracker = new Eventra({
223
265
  });
224
266
  ```
225
267
 
226
- **Privacy note:** persistence stores the pending queue — including any `userId`/`properties` you pass to `track()` — as plaintext JSON in `localStorage` so it survives reloads. If that's a concern (e.g. properties may carry PII on a shared/public device), disable it:
268
+ **Privacy note:** persistence stores the pending queue - including any `userId`/`properties` you pass to `track()` - as plaintext JSON in `localStorage` so it survives reloads. If that's a concern (e.g. properties may carry PII on a shared/public device), disable it:
227
269
 
228
270
  ```ts
229
271
  const tracker = new Eventra({
@@ -252,12 +294,18 @@ const tracker = new Eventra({
252
294
  });
253
295
 
254
296
  tracker.track("invoice.created");
297
+
298
+ // one process serves many users: bind the user per call or request
299
+ export function onInvoiceCreated(userId: string) {
300
+ tracker.withUser(userId).track("invoice.created");
301
+ }
255
302
  ```
256
303
 
257
304
  - batching
258
305
  - retry
259
306
  - auto flush (interval)
260
307
  - graceful shutdown support
308
+ - `identify()` is ignored here, use `withUser()` (see [Identify users](#identify-users))
261
309
 
262
310
  ---
263
311
 
@@ -339,9 +387,10 @@ const tracker = new Eventra({
339
387
  | 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) |
340
388
  | 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 |
341
389
  | diagnostics | Report delivery problems (counts only) with the next successful batch, default `true`; `false` sends nothing extra. See [Delivery diagnostics](#delivery-diagnostics) |
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 |
390
+ | 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 (the user of `identify()` is then kept in memory too) |
391
+ | identifyHint | Warn once when none of the first 50 events has a user id (default: `true`): in a browser bundle not built for production, on a server only with `NODE_ENV=development`, never in test runs. `false` for an app without signed-in users. See [Identify users](#identify-users) |
343
392
 
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.
393
+ 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` or `identifyHint` 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
394
 
346
395
  ---
347
396
 
@@ -357,7 +406,7 @@ await tracker.flush();
357
406
 
358
407
  ## Shutdown
359
408
 
360
- Graceful shutdown — flush first, then cleanup:
409
+ Graceful shutdown - flush first, then cleanup:
361
410
 
362
411
  ```ts
363
412
  await tracker.shutdown();
@@ -391,7 +440,7 @@ await tracker.flush();
391
440
  await tracker.shutdown();
392
441
  ```
393
442
 
394
- `destroy()` stops timers and listeners immediately without flushing.
443
+ `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).
395
444
 
396
445
  ---
397
446
 
@@ -449,11 +498,11 @@ Eventra SDK includes:
449
498
  - Circuit breaker with half-open recovery: one probe request, cooldown doubles after each failed probe (5 s up to 60 s)
450
499
  - Queue-based delivery (all runtimes)
451
500
  - Safe dequeue (events removed only after successful ingest)
452
- - Queue persistence (browser) with merge + cross-tab sync — opt out via `persistQueue: false` if `localStorage` isn't acceptable for your data
501
+ - Queue persistence (browser) with merge + cross-tab sync - opt out via `persistQueue: false` if `localStorage` isn't acceptable for your data
453
502
  - Multi-tab leader election with re-election
454
503
  - `fetch` + `keepalive` on tab close (with `x-api-key`, size-checked)
455
504
  - `pagehide` + `visibilitychange` flush hooks
456
- - Property validation at `track()` (depth + size) — fails soft via `onEventsDropped`, `track()` never throws
505
+ - Property validation at `track()` (depth + size) - fails soft via `onEventsDropped`, `track()` never throws
457
506
  - Payload byte limits per batch
458
507
  - Permanent error handling via `onDeliveryFailed` (401, 422, etc.)
459
508
  - Automatic requeue on network errors and 429 / 5xx
@@ -465,18 +514,21 @@ Eventra SDK includes:
465
514
 
466
515
  **100% statement/branch/function/line coverage** (v8 provider, `pnpm test:coverage`).
467
516
 
468
- 266 vitest tests across 22 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
517
+ **Mutation testing** (`pnpm test:mutation`, Stryker over all of `src/client.ts` and `src/diagnostics.ts`, about 30 minutes): 84.6% of mutants killed (2026-11-16), the build breaks below 80%. `tests/accuracy.test.ts` pins what decides whether an event reaches the server once and under its catalog name: name and user id cleaning and cutting, idempotency keys in every runtime, UTF-8 payload size, which saved events are read back, Retry-After, the size and depth limits of properties, what each server answer does to a batch, keepalive, and events shared between tabs. Mutants that cannot change behaviour are marked in the code with `// Stryker disable` and the reason.
518
+
519
+ 358 vitest tests across 26 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
469
520
 
470
- - `track()` validation — name length, userId truncation, properties depth/size, idempotency keys
471
- - Batching — auto-flush at `maxBatchSize`, periodic flush via timer, queue overflow drop
472
- - Retry & backoff — 429, 5xx, network errors, no-retry on 4xx, fetch timeout/abort
521
+ - `track()` validation - name length, userId truncation, properties depth/size, idempotency keys
522
+ - Users - `identify()`, `reset()` and `withUser()`, which user wins, keeping the user across reloads and tabs and per API key, ignoring `identify()` outside a browser and React Native, ids that name nobody, the development hint
523
+ - Batching - auto-flush at `maxBatchSize`, periodic flush via timer, queue overflow drop
524
+ - Retry & backoff - 429, 5xx, network errors, no-retry on 4xx, fetch timeout/abort
473
525
  - Circuit breaker - opens after 5 consecutive failed batches (each one after its retries), cools down, resets on success
474
- - Payload guards — multi-batch splitting, oversize event dropped via `onDeliveryFailed(413)`
526
+ - Payload guards - multi-batch splitting, oversize event dropped via `onDeliveryFailed(413)`
475
527
  - Shutdown & destroy - flush ordering, timer teardown, idempotent shutdown, the `shutdownTimeoutMs` budget, signal handling (re-raise only when nobody else listens, PID 1, `exitOnSignal: false`)
476
528
  - Persisted queue - coalesced writes, 14-day maximum age, delivered-key filtering, cross-tab merge
477
- - Runtime detection — Node, Edge (`EdgeRuntime`), Serverless (AWS Lambda), unknown fallback, Node process exit handling
529
+ - Runtime detection - Node, Edge (`EdgeRuntime`), Serverless (AWS Lambda), unknown fallback, Node process exit handling
478
530
  - 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
479
- - Storage edge cases — corrupted/blocked localStorage, quota exceeded, queue trimming
531
+ - Storage edge cases - corrupted/blocked localStorage, quota exceeded, queue trimming
480
532
  - 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
533
  - Regressions: `flush()` waiting for a flush already in flight, properties copied at `track()`, a corrupt stored queue
482
534
 
@@ -513,7 +565,7 @@ pnpm --filter @eventra_dev/eventra-sdk test:coverage
513
565
  }
514
566
  ```
515
567
 
516
- `idempotencyKey` is generated once per event and stays identical across every retry attempt of that event — delivery is **at-least-once, not exactly-once**. A retried batch resends the same events with the same keys, and under a slow network a request can be fully received and processed by the ingestion endpoint even after the SDK's own fetch timed out client-side and moved on to a retry — the backend seeing the same `idempotencyKey` more than once is expected, not a sign of a bug, and should be deduplicated on that key rather than on request count.
568
+ `idempotencyKey` is generated once per event and stays identical across every retry attempt of that event - delivery is **at-least-once, not exactly-once**. A retried batch resends the same events with the same keys, and under a slow network a request can be fully received and processed by the ingestion endpoint even after the SDK's own fetch timed out client-side and moved on to a retry - the backend seeing the same `idempotencyKey` more than once is expected, not a sign of a bug, and should be deduplicated on that key rather than on request count.
517
569
 
518
570
  Limits enforced by the SDK at `track()` time:
519
571
 
package/dist/index.cjs CHANGED
@@ -193,11 +193,12 @@ 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.13";
196
+ var SDK_VERSION = "2.1.0";
197
197
  var LEADER_KEY = "__eventra_leader__";
198
198
  var LEADER_TTL_MS = 4e3;
199
199
  var QUEUE_KEY = "__eventra_q__";
200
200
  var DIAGNOSTICS_KEY = "__eventra_d__";
201
+ var USER_KEY_PREFIX = "__eventra_u__";
201
202
  var CHANNEL_NAME = "eventra-sdk";
202
203
  var MAX_EVENT_NAME = 64;
203
204
  var MAX_USER_ID = 120;
@@ -216,6 +217,9 @@ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
216
217
  var PERSISTED_QUEUE_MAX_CHARS = 1e6;
217
218
  var KEEPALIVE_MAX_BYTES = 6e4;
218
219
  var DELIVERED_KEYS_MAX = 1e4;
220
+ var LIVE_TAB_GRACE_MS = 15e3;
221
+ var LIVE_TAB_KEYS_MAX = 1e4;
222
+ var IDENTIFY_HINT_AFTER = 50;
219
223
  var activeInstances = 0;
220
224
  function detectRuntime() {
221
225
  const g = globalThis;
@@ -282,10 +286,11 @@ function isUrl(value) {
282
286
  return false;
283
287
  }
284
288
  }
289
+ function warn(message) {
290
+ if (typeof console !== "undefined") console.warn(message);
291
+ }
285
292
  function warnOption(name, value, fallback) {
286
- if (typeof console !== "undefined") {
287
- console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
288
- }
293
+ warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
289
294
  }
290
295
  function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
291
296
  if (value === void 0) return fallback;
@@ -339,6 +344,39 @@ function normalizeUserId(value, max) {
339
344
  if (typeof value !== "string") return void 0;
340
345
  return cut(value, max);
341
346
  }
347
+ function identifiedUserId(value) {
348
+ const id = normalizeUserId(value, MAX_USER_ID);
349
+ if (id === void 0) return void 0;
350
+ const trimmed = id.trim();
351
+ return trimmed && trimmed !== "undefined" && trimmed !== "null" ? id : void 0;
352
+ }
353
+ function keyHash(value) {
354
+ let hash = 2166136261;
355
+ for (let i = 0; i < value.length; i++) {
356
+ hash ^= value.charCodeAt(i);
357
+ hash = Math.imul(hash, 16777619);
358
+ }
359
+ return (hash >>> 0).toString(16);
360
+ }
361
+ function isReactNative() {
362
+ try {
363
+ return globalThis.navigator?.product === "ReactNative";
364
+ } catch {
365
+ return false;
366
+ }
367
+ }
368
+ function nodeEnv() {
369
+ try {
370
+ return process.env.NODE_ENV;
371
+ } catch {
372
+ return null;
373
+ }
374
+ }
375
+ function isDevelopment(server) {
376
+ const env = nodeEnv();
377
+ if (env === null || env === "test") return false;
378
+ return server ? env === "development" : env !== "production";
379
+ }
342
380
  function stripUnsafeForName(value) {
343
381
  let out = "";
344
382
  for (let i = 0; i < value.length; i++) {
@@ -383,7 +421,9 @@ function utf8ByteLength(value) {
383
421
  function isStoredEvent(e) {
384
422
  if (e === null || typeof e !== "object") return false;
385
423
  const ev = e;
386
- return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 && typeof ev.name === "string" && ev.name.length > 0 && ev.name.length <= MAX_EVENT_NAME && typeof ev.timestamp === "string" && (ev.userId === void 0 || typeof ev.userId === "string" && ev.userId.length <= MAX_USER_ID) && (ev.properties === void 0 || ev.properties !== null && typeof ev.properties === "object" && !Array.isArray(ev.properties));
424
+ return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 && // Stryker disable next-line ConditionalExpression: equivalent, a name that is not a string has no length and fails the next check
425
+ typeof ev.name === "string" && ev.name.length > 0 && ev.name.length <= MAX_EVENT_NAME && typeof ev.timestamp === "string" && // Stryker disable next-line ConditionalExpression: equivalent, a user id that is not a string has no length to pass the check
426
+ (ev.userId === void 0 || typeof ev.userId === "string" && ev.userId.length <= MAX_USER_ID) && (ev.properties === void 0 || ev.properties !== null && typeof ev.properties === "object" && !Array.isArray(ev.properties));
387
427
  }
388
428
  function mergeQueues(...queues) {
389
429
  const seen = /* @__PURE__ */ new Set();
@@ -417,8 +457,12 @@ function persistedQueueJson(queue) {
417
457
  }
418
458
  var MAX_PROPERTIES_NODES = 5e4;
419
459
  function validateProperties(properties) {
420
- if (properties === null || typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
421
- Object.prototype.toString.call(properties) !== "[object Object]") {
460
+ if (
461
+ // Stryker disable next-line all: equivalent, track() passes `properties ?? {}`, and any other non-object fails the toString check below
462
+ properties === null || // Stryker disable next-line all: equivalent, see the line above
463
+ typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
464
+ Object.prototype.toString.call(properties) !== "[object Object]"
465
+ ) {
422
466
  throw new Error("Eventra: properties must be an object");
423
467
  }
424
468
  const topKeys = Object.keys(properties);
@@ -480,6 +524,12 @@ var RetryableDeliveryError = class extends Error {
480
524
  this.name = "RetryableDeliveryError";
481
525
  }
482
526
  };
527
+ var DeliveryStopped = class extends Error {
528
+ constructor() {
529
+ super("delivery stopped by destroy()");
530
+ this.name = "DeliveryStopped";
531
+ }
532
+ };
483
533
  var Storage = class {
484
534
  constructor() {
485
535
  this.enabled = false;
@@ -492,6 +542,10 @@ var Storage = class {
492
542
  } catch {
493
543
  }
494
544
  }
545
+ // localStorage works here (not in Node, a blocked or private-mode browser)
546
+ get isEnabled() {
547
+ return this.enabled;
548
+ }
495
549
  get(key) {
496
550
  if (!this.enabled) return null;
497
551
  try {
@@ -516,11 +570,6 @@ var Storage = class {
516
570
  } catch {
517
571
  }
518
572
  }
519
- // Not currently called anywhere in the client — kept for API symmetry with
520
- // get()/set() on this internal class. No real call site exists to exercise
521
- // it, and Storage isn't part of the public surface, so a direct call here
522
- // would only be a reflection-hack test, not real usage.
523
- /* v8 ignore start */
524
573
  remove(key) {
525
574
  if (!this.enabled) return;
526
575
  try {
@@ -528,7 +577,6 @@ var Storage = class {
528
577
  } catch {
529
578
  }
530
579
  }
531
- /* v8 ignore stop */
532
580
  };
533
581
  function storageAvailable() {
534
582
  try {
@@ -663,6 +711,8 @@ var Eventra = class {
663
711
  constructor(options) {
664
712
  this.queue = [];
665
713
  this.sending = null;
714
+ // events other open tabs announced on the channel, by key, and until when they are theirs to send
715
+ this.liveTabEvents = /* @__PURE__ */ new Map();
666
716
  this.inFlight = false;
667
717
  this.destroyed = false;
668
718
  this.shuttingDown = false;
@@ -687,6 +737,16 @@ var Eventra = class {
687
737
  // the page is being left (`pagehide`)
688
738
  this.leaving = false;
689
739
  this.exitHandlers = [];
740
+ this.warnedServerIdentify = false;
741
+ this.warnedInvalidIdentify = false;
742
+ this.warnedInvalidUser = false;
743
+ // one user for the whole instance is safe only where the instance serves one person: a browser tab, a React
744
+ // Native app. Everything else (Node, edge, Lambda, Deno, Cloudflare Workers) may serve many requests at once.
745
+ this.singleUser = false;
746
+ this.userKey = USER_KEY_PREFIX;
747
+ // identifyHint: events without a user id so far, and whether the check is over
748
+ this.eventsWithoutUser = 0;
749
+ this.identifyHintDone = false;
690
750
  if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
691
751
  throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
692
752
  }
@@ -719,6 +779,10 @@ var Eventra = class {
719
779
  if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
720
780
  warnOption("diagnostics", options.diagnostics, "true");
721
781
  }
782
+ if (options.identifyHint !== void 0 && typeof options.identifyHint !== "boolean") {
783
+ warnOption("identifyHint", options.identifyHint, "true");
784
+ }
785
+ this.identifyHintDone = options.identifyHint === false;
722
786
  for (const name of ["maxBatchSize", "maxQueueSize"]) {
723
787
  const value = options[name];
724
788
  if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
@@ -726,6 +790,8 @@ var Eventra = class {
726
790
  }
727
791
  }
728
792
  this.runtime = detectRuntime();
793
+ this.singleUser = this.runtime === "browser" || isReactNative();
794
+ this.userKey = `${USER_KEY_PREFIX}${keyHash(options.apiKey)}`;
729
795
  warnIfInsecureEndpoint(this.endpoint);
730
796
  this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
731
797
  if (!this.fetch) {
@@ -757,7 +823,10 @@ var Eventra = class {
757
823
  };
758
824
  if (this.runtime === "browser") {
759
825
  if (this.persistQueue) {
826
+ this.userId = this.loadStoredUser();
760
827
  this.loadAndMergeQueue();
828
+ } else {
829
+ this.storage.remove(this.userKey);
761
830
  }
762
831
  this.setupQueueSync();
763
832
  }
@@ -795,14 +864,86 @@ var Eventra = class {
795
864
  }
796
865
  }
797
866
  track(name, options) {
867
+ this.trackSafely(name, options, void 0);
868
+ }
869
+ /**
870
+ * Sets the user of every following event that does not name its own, in a browser or a React Native app. In
871
+ * the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open
872
+ * tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may
873
+ * serve many users at once, so it is ignored with one warning: use `withUser()` there.
874
+ */
875
+ identify(userId) {
876
+ if (this.destroyed) return;
877
+ if (!this.singleUser) {
878
+ if (!this.warnedServerIdentify) {
879
+ this.warnedServerIdentify = true;
880
+ warn(
881
+ "Eventra: identify() is ignored outside a browser, where one instance may serve many users - use withUser(userId).track(...) for each request (in Next.js and other SSR apps, call identify() in client code, e.g. useEffect)"
882
+ );
883
+ }
884
+ return;
885
+ }
886
+ const id = identifiedUserId(userId);
887
+ if (id === void 0) {
888
+ if (!this.warnedInvalidIdentify) {
889
+ this.warnedInvalidIdentify = true;
890
+ warn("Eventra: identify() needs a user id (a non-empty string or a number) - to sign a user out, call reset()");
891
+ }
892
+ return;
893
+ }
894
+ this.identifyHintDone = true;
895
+ if (id !== this.userId) this.setUser(id);
896
+ }
897
+ /** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */
898
+ reset() {
899
+ if (this.destroyed || !this.singleUser) return;
900
+ this.setUser(void 0);
901
+ }
902
+ /** The user set by `identify()`, if any. */
903
+ getUserId() {
904
+ return this.userId;
905
+ }
906
+ /**
907
+ * A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares
908
+ * this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events
909
+ * without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.
910
+ */
911
+ withUser(userId) {
912
+ let id;
913
+ if (userId !== void 0 && userId !== null) {
914
+ id = identifiedUserId(userId);
915
+ if (id === void 0 && !this.warnedInvalidUser) {
916
+ this.warnedInvalidUser = true;
917
+ warn("Eventra: withUser() got an invalid user id (it needs a non-empty string or a number), its events are sent without one");
918
+ }
919
+ }
920
+ if (id !== void 0) this.identifyHintDone = true;
921
+ const scopeUser = id ?? null;
922
+ return {
923
+ track: (name, options) => this.trackSafely(name, options, scopeUser)
924
+ };
925
+ }
926
+ setUser(id) {
927
+ this.userId = id;
928
+ if (this.runtime !== "browser") return;
929
+ if (id === void 0) this.storage.remove(this.userKey);
930
+ else if (this.persistQueue) this.storage.set(this.userKey, id);
931
+ this.broadcast({ type: "user", key: this.userKey, userId: id ?? null });
932
+ }
933
+ loadStoredUser() {
934
+ const saved = this.storage.get(this.userKey);
935
+ return typeof saved === "string" ? identifiedUserId(saved) : void 0;
936
+ }
937
+ // scopeUserId: undefined outside a scope, null for a scope without a user
938
+ trackSafely(name, options, scopeUserId) {
798
939
  try {
799
- this.trackEvent(name, options);
940
+ this.trackEvent(name, options, scopeUserId);
800
941
  } catch {
801
942
  this.recordDiagnostic("invalid_event");
802
943
  callSafely(this.options.onEventsDropped, 1);
803
944
  }
804
945
  }
805
- trackEvent(name, options) {
946
+ trackEvent(name, options, scopeUserId) {
806
947
  if (this.destroyed || this.shuttingDown) return;
807
948
  const eventName = normalizeEventName(name);
808
949
  if (eventName === null) {
@@ -823,14 +964,17 @@ var Eventra = class {
823
964
  callSafely(this.options.onEventsDropped, 1);
824
965
  return;
825
966
  }
967
+ const given = options?.userId;
968
+ const ownUserId = typeof given === "string" && !given.trim() ? void 0 : given;
826
969
  const event = {
827
970
  idempotencyKey: uuidV4(),
828
971
  name: eventName,
829
- userId: normalizeUserId(options?.userId, MAX_USER_ID),
972
+ userId: ownUserId !== void 0 ? normalizeUserId(ownUserId, MAX_USER_ID) : scopeUserId !== void 0 ? scopeUserId ?? void 0 : this.userId,
830
973
  properties,
831
974
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
832
975
  };
833
976
  this.queue.push(event);
977
+ if (!this.identifyHintDone) this.checkIdentifyHint(identifiedUserId(event.userId) !== void 0);
834
978
  if (this.runtime === "browser") {
835
979
  this.schedulePersist();
836
980
  this.broadcast({ type: "queue-add", events: [event] });
@@ -951,6 +1095,12 @@ var Eventra = class {
951
1095
  activeInstances = Math.max(0, activeInstances - 1);
952
1096
  if (this.timer) clearInterval(this.timer);
953
1097
  this.persistNow();
1098
+ const kept = this.runtime === "browser" && this.persistQueue && this.storage.isEnabled;
1099
+ if (!kept) {
1100
+ const inFlight = new Set(this.sending ?? []);
1101
+ const lost = this.queue.filter((event) => !inFlight.has(event)).length;
1102
+ if (lost > 0) callSafely(this.options.onEventsDropped, lost);
1103
+ }
954
1104
  this.leader?.destroy();
955
1105
  if (this.channel) {
956
1106
  try {
@@ -981,6 +1131,10 @@ var Eventra = class {
981
1131
  let index = 0;
982
1132
  while (index < this.queue.length && events.length < this.maxBatch) {
983
1133
  const event = this.queue[index];
1134
+ if (this.leftToItsTab(event)) {
1135
+ index++;
1136
+ continue;
1137
+ }
984
1138
  let eventJson;
985
1139
  try {
986
1140
  eventJson = JSON.stringify(event);
@@ -1015,6 +1169,20 @@ var Eventra = class {
1015
1169
  diagnostics: withReport && report ? report : void 0
1016
1170
  };
1017
1171
  }
1172
+ // one warning during development when an app sends events without ever saying whose they are
1173
+ checkIdentifyHint(hasUser) {
1174
+ if (hasUser) {
1175
+ this.identifyHintDone = true;
1176
+ return;
1177
+ }
1178
+ if (++this.eventsWithoutUser < IDENTIFY_HINT_AFTER) return;
1179
+ this.identifyHintDone = true;
1180
+ if (!isDevelopment(!this.singleUser)) return;
1181
+ const how = this.singleUser ? "call tracker.identify(userId) after sign-in" : "track through tracker.withUser(userId) in each request";
1182
+ warn(
1183
+ `Eventra: none of the first ${IDENTIFY_HINT_AFTER} events has a userId, so unique users cannot be counted - ${how} (identifyHint: false turns this off)`
1184
+ );
1185
+ }
1018
1186
  dropPoisonEvent(event) {
1019
1187
  this.recordDiagnostic("too_large");
1020
1188
  this.removeDelivered([event]);
@@ -1050,8 +1218,13 @@ var Eventra = class {
1050
1218
  this.dropPoisonEvents(events);
1051
1219
  return false;
1052
1220
  }
1053
- const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
1054
- payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
1221
+ const useKeepalive = (
1222
+ // Stryker disable next-line all: equivalent, document exists exactly in the browser runtime
1223
+ this.runtime === "browser" && // Stryker disable next-line all: equivalent, see the line above
1224
+ typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
1225
+ // Stryker disable next-line EqualityOperator: a body of exactly the keepalive limit; not worth a 60,000-byte fixture
1226
+ payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES)
1227
+ );
1055
1228
  const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
1056
1229
  let strippedDiagnostics = false;
1057
1230
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -1079,7 +1252,9 @@ var Eventra = class {
1079
1252
  discardBody(res);
1080
1253
  if (res.status === 429 || res.status >= 500) {
1081
1254
  throw new RetryableDeliveryError(
1255
+ // Stryker disable next-line StringLiteral: the message is never read
1082
1256
  "retryable delivery error",
1257
+ // Stryker disable next-line OptionalChaining: equivalent with a real Response, which always has headers.get
1083
1258
  parseRetryAfterMs(res.headers?.get?.("retry-after")),
1084
1259
  res.status === 429 ? "rate_limited" : "server_error"
1085
1260
  );
@@ -1120,6 +1295,7 @@ var Eventra = class {
1120
1295
  throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
1121
1296
  }
1122
1297
  await sleep(wait);
1298
+ if (this.destroyed) throw new DeliveryStopped();
1123
1299
  } finally {
1124
1300
  clearTimeout(timeout);
1125
1301
  }
@@ -1207,11 +1383,34 @@ var Eventra = class {
1207
1383
  }
1208
1384
  trimQueue(queue = this.queue) {
1209
1385
  if (queue.length <= this.maxQueue) return queue;
1210
- const dropped = queue.length - this.maxQueue;
1211
- this.recordDiagnostic("queue_full", dropped);
1212
- callSafely(this.options.onEventsDropped, dropped);
1386
+ const removed = queue.slice(0, queue.length - this.maxQueue);
1387
+ const dropped = removed.filter((e) => !this.liveTabEvents.has(e?.idempotencyKey)).length;
1388
+ if (dropped > 0) {
1389
+ this.recordDiagnostic("queue_full", dropped);
1390
+ callSafely(this.options.onEventsDropped, dropped);
1391
+ }
1213
1392
  return queue.slice(-this.maxQueue);
1214
1393
  }
1394
+ // events another open tab just announced on the channel, with the time until which that tab sends them
1395
+ rememberLiveTabEvents(events) {
1396
+ const until = Date.now() + LIVE_TAB_GRACE_MS;
1397
+ for (const event of events) {
1398
+ const key = event?.idempotencyKey;
1399
+ if (typeof key === "string" && !this.liveTabEvents.has(key)) this.liveTabEvents.set(key, until);
1400
+ }
1401
+ for (const key of this.liveTabEvents.keys()) {
1402
+ if (this.liveTabEvents.size <= LIVE_TAB_KEYS_MAX) break;
1403
+ this.liveTabEvents.delete(key);
1404
+ }
1405
+ }
1406
+ // In `independent` mode, an event another open tab announced less than LIVE_TAB_GRACE_MS ago is that
1407
+ // tab's to send. After that (the tab was closed, or it cannot reach the server either) anyone sends it.
1408
+ // The leader in `leader` mode sends everything, so it never waits.
1409
+ leftToItsTab(event) {
1410
+ if (this.leader) return false;
1411
+ const until = this.liveTabEvents.get(event?.idempotencyKey);
1412
+ return until !== void 0 && Date.now() < until;
1413
+ }
1215
1414
  // Sends only what changed (a new event, or the keys just delivered) instead
1216
1415
  // of structured-cloning the whole queue on every call.
1217
1416
  broadcast(message) {
@@ -1231,21 +1430,31 @@ var Eventra = class {
1231
1430
  if (this.channel) {
1232
1431
  this.channel.onmessage = (e) => {
1233
1432
  const data = e.data;
1433
+ if (data?.type === "user") {
1434
+ if (data.key !== this.userKey) return;
1435
+ if (data.userId === null) this.userId = void 0;
1436
+ else if (typeof data.userId === "string") this.userId = identifiedUserId(data.userId) ?? this.userId;
1437
+ return;
1438
+ }
1234
1439
  if (data?.type === "delivered" && Array.isArray(data.keys)) {
1235
1440
  const keys = new Set(data.keys);
1236
1441
  this.rememberDelivered(keys);
1442
+ for (const key of keys) this.liveTabEvents.delete(key);
1237
1443
  this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
1238
1444
  return;
1239
1445
  }
1240
1446
  if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
1241
1447
  return;
1242
1448
  }
1243
- this.queue = mergeQueues(this.queue, this.withoutDelivered(data.events));
1449
+ const announced = this.withoutDelivered(data.events);
1450
+ this.rememberLiveTabEvents(announced);
1451
+ this.queue = mergeQueues(this.queue, announced);
1244
1452
  this.queue = this.trimQueue();
1245
1453
  };
1246
1454
  }
1247
1455
  if (this.persistQueue && typeof window !== "undefined") {
1248
1456
  this.offStorageQueue = listen(window, "storage", (e) => {
1457
+ if (e.key === this.userKey || e.key === null) this.userId = this.loadStoredUser();
1249
1458
  if (e.key !== QUEUE_KEY) return;
1250
1459
  this.loadAndMergeQueue();
1251
1460
  });