@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 +71 -19
- package/dist/index.cjs +231 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -3
- package/dist/index.d.ts +49 -3
- package/dist/index.mjs +231 -22
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -3
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
interface TrackOptions {
|
|
2
|
-
/**
|
|
3
|
-
|
|
2
|
+
/**
|
|
3
|
+
* A string; a number is written out as text. Cut to 120 characters. Takes priority over the user of
|
|
4
|
+
* `withUser()` and `identify()`; `null` sends the event without a user even when one is identified, and an
|
|
5
|
+
* empty or blank string counts as not given.
|
|
6
|
+
*/
|
|
7
|
+
userId?: string | number | null;
|
|
4
8
|
properties?: Record<string, unknown>;
|
|
5
9
|
}
|
|
10
|
+
/** A tracker bound to one user, returned by `withUser()`. Shares the queue and delivery of its `Eventra`. */
|
|
11
|
+
interface EventraScope {
|
|
12
|
+
track(name: string, options?: TrackOptions): void;
|
|
13
|
+
}
|
|
6
14
|
interface TrackerOptions {
|
|
7
15
|
apiKey: string;
|
|
8
16
|
/** Defaults to production ingest URL when omitted */
|
|
@@ -57,6 +65,12 @@ interface TrackerOptions {
|
|
|
57
65
|
status: number;
|
|
58
66
|
events: TrackEvent[];
|
|
59
67
|
}) => void;
|
|
68
|
+
/**
|
|
69
|
+
* Warn once when none of the first 50 events carries a user id (default `true`): in a browser bundle not
|
|
70
|
+
* built for production, on a server only with `NODE_ENV=development`, never in test runs. Set `false` for an
|
|
71
|
+
* app that has no signed-in users.
|
|
72
|
+
*/
|
|
73
|
+
identifyHint?: boolean;
|
|
60
74
|
/** Multi-tab mode (browser only) */
|
|
61
75
|
multiTabMode?: "independent" | "leader";
|
|
62
76
|
}
|
|
@@ -80,6 +94,7 @@ declare class Eventra {
|
|
|
80
94
|
private fetch;
|
|
81
95
|
private queue;
|
|
82
96
|
private sending;
|
|
97
|
+
private liveTabEvents;
|
|
83
98
|
private inFlight;
|
|
84
99
|
private destroyed;
|
|
85
100
|
private shuttingDown;
|
|
@@ -114,8 +129,36 @@ declare class Eventra {
|
|
|
114
129
|
private sdkInfo;
|
|
115
130
|
private options;
|
|
116
131
|
private exitHandlers;
|
|
132
|
+
private userId?;
|
|
133
|
+
private warnedServerIdentify;
|
|
134
|
+
private warnedInvalidIdentify;
|
|
135
|
+
private warnedInvalidUser;
|
|
136
|
+
private singleUser;
|
|
137
|
+
private userKey;
|
|
138
|
+
private eventsWithoutUser;
|
|
139
|
+
private identifyHintDone;
|
|
117
140
|
constructor(options: TrackerOptions);
|
|
118
141
|
track(name: string, options?: TrackOptions): void;
|
|
142
|
+
/**
|
|
143
|
+
* Sets the user of every following event that does not name its own, in a browser or a React Native app. In
|
|
144
|
+
* the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open
|
|
145
|
+
* tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may
|
|
146
|
+
* serve many users at once, so it is ignored with one warning: use `withUser()` there.
|
|
147
|
+
*/
|
|
148
|
+
identify(userId: string | number): void;
|
|
149
|
+
/** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */
|
|
150
|
+
reset(): void;
|
|
151
|
+
/** The user set by `identify()`, if any. */
|
|
152
|
+
getUserId(): string | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares
|
|
155
|
+
* this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events
|
|
156
|
+
* without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.
|
|
157
|
+
*/
|
|
158
|
+
withUser(userId: string | number | null | undefined): EventraScope;
|
|
159
|
+
private setUser;
|
|
160
|
+
private loadStoredUser;
|
|
161
|
+
private trackSafely;
|
|
119
162
|
private trackEvent;
|
|
120
163
|
flush(): Promise<void>;
|
|
121
164
|
private flushNow;
|
|
@@ -130,6 +173,7 @@ declare class Eventra {
|
|
|
130
173
|
private flushEverything;
|
|
131
174
|
destroy(): void;
|
|
132
175
|
private buildBatch;
|
|
176
|
+
private checkIdentifyHint;
|
|
133
177
|
private dropPoisonEvent;
|
|
134
178
|
private removeDelivered;
|
|
135
179
|
private send;
|
|
@@ -143,6 +187,8 @@ declare class Eventra {
|
|
|
143
187
|
private schedulePersist;
|
|
144
188
|
private persistNow;
|
|
145
189
|
private trimQueue;
|
|
190
|
+
private rememberLiveTabEvents;
|
|
191
|
+
private leftToItsTab;
|
|
146
192
|
private broadcast;
|
|
147
193
|
private setupQueueSync;
|
|
148
194
|
private startTimer;
|
|
@@ -157,4 +203,4 @@ declare class Eventra {
|
|
|
157
203
|
private setupProcessExit;
|
|
158
204
|
}
|
|
159
205
|
|
|
160
|
-
export { Eventra, type SdkInfo, type TrackEvent, type TrackOptions, type TrackerOptions };
|
|
206
|
+
export { Eventra, type EventraScope, type SdkInfo, type TrackEvent, type TrackOptions, type TrackerOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
interface TrackOptions {
|
|
2
|
-
/**
|
|
3
|
-
|
|
2
|
+
/**
|
|
3
|
+
* A string; a number is written out as text. Cut to 120 characters. Takes priority over the user of
|
|
4
|
+
* `withUser()` and `identify()`; `null` sends the event without a user even when one is identified, and an
|
|
5
|
+
* empty or blank string counts as not given.
|
|
6
|
+
*/
|
|
7
|
+
userId?: string | number | null;
|
|
4
8
|
properties?: Record<string, unknown>;
|
|
5
9
|
}
|
|
10
|
+
/** A tracker bound to one user, returned by `withUser()`. Shares the queue and delivery of its `Eventra`. */
|
|
11
|
+
interface EventraScope {
|
|
12
|
+
track(name: string, options?: TrackOptions): void;
|
|
13
|
+
}
|
|
6
14
|
interface TrackerOptions {
|
|
7
15
|
apiKey: string;
|
|
8
16
|
/** Defaults to production ingest URL when omitted */
|
|
@@ -57,6 +65,12 @@ interface TrackerOptions {
|
|
|
57
65
|
status: number;
|
|
58
66
|
events: TrackEvent[];
|
|
59
67
|
}) => void;
|
|
68
|
+
/**
|
|
69
|
+
* Warn once when none of the first 50 events carries a user id (default `true`): in a browser bundle not
|
|
70
|
+
* built for production, on a server only with `NODE_ENV=development`, never in test runs. Set `false` for an
|
|
71
|
+
* app that has no signed-in users.
|
|
72
|
+
*/
|
|
73
|
+
identifyHint?: boolean;
|
|
60
74
|
/** Multi-tab mode (browser only) */
|
|
61
75
|
multiTabMode?: "independent" | "leader";
|
|
62
76
|
}
|
|
@@ -80,6 +94,7 @@ declare class Eventra {
|
|
|
80
94
|
private fetch;
|
|
81
95
|
private queue;
|
|
82
96
|
private sending;
|
|
97
|
+
private liveTabEvents;
|
|
83
98
|
private inFlight;
|
|
84
99
|
private destroyed;
|
|
85
100
|
private shuttingDown;
|
|
@@ -114,8 +129,36 @@ declare class Eventra {
|
|
|
114
129
|
private sdkInfo;
|
|
115
130
|
private options;
|
|
116
131
|
private exitHandlers;
|
|
132
|
+
private userId?;
|
|
133
|
+
private warnedServerIdentify;
|
|
134
|
+
private warnedInvalidIdentify;
|
|
135
|
+
private warnedInvalidUser;
|
|
136
|
+
private singleUser;
|
|
137
|
+
private userKey;
|
|
138
|
+
private eventsWithoutUser;
|
|
139
|
+
private identifyHintDone;
|
|
117
140
|
constructor(options: TrackerOptions);
|
|
118
141
|
track(name: string, options?: TrackOptions): void;
|
|
142
|
+
/**
|
|
143
|
+
* Sets the user of every following event that does not name its own, in a browser or a React Native app. In
|
|
144
|
+
* the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open
|
|
145
|
+
* tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may
|
|
146
|
+
* serve many users at once, so it is ignored with one warning: use `withUser()` there.
|
|
147
|
+
*/
|
|
148
|
+
identify(userId: string | number): void;
|
|
149
|
+
/** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */
|
|
150
|
+
reset(): void;
|
|
151
|
+
/** The user set by `identify()`, if any. */
|
|
152
|
+
getUserId(): string | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares
|
|
155
|
+
* this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events
|
|
156
|
+
* without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.
|
|
157
|
+
*/
|
|
158
|
+
withUser(userId: string | number | null | undefined): EventraScope;
|
|
159
|
+
private setUser;
|
|
160
|
+
private loadStoredUser;
|
|
161
|
+
private trackSafely;
|
|
119
162
|
private trackEvent;
|
|
120
163
|
flush(): Promise<void>;
|
|
121
164
|
private flushNow;
|
|
@@ -130,6 +173,7 @@ declare class Eventra {
|
|
|
130
173
|
private flushEverything;
|
|
131
174
|
destroy(): void;
|
|
132
175
|
private buildBatch;
|
|
176
|
+
private checkIdentifyHint;
|
|
133
177
|
private dropPoisonEvent;
|
|
134
178
|
private removeDelivered;
|
|
135
179
|
private send;
|
|
@@ -143,6 +187,8 @@ declare class Eventra {
|
|
|
143
187
|
private schedulePersist;
|
|
144
188
|
private persistNow;
|
|
145
189
|
private trimQueue;
|
|
190
|
+
private rememberLiveTabEvents;
|
|
191
|
+
private leftToItsTab;
|
|
146
192
|
private broadcast;
|
|
147
193
|
private setupQueueSync;
|
|
148
194
|
private startTimer;
|
|
@@ -157,4 +203,4 @@ declare class Eventra {
|
|
|
157
203
|
private setupProcessExit;
|
|
158
204
|
}
|
|
159
205
|
|
|
160
|
-
export { Eventra, type SdkInfo, type TrackEvent, type TrackOptions, type TrackerOptions };
|
|
206
|
+
export { Eventra, type EventraScope, type SdkInfo, type TrackEvent, type TrackOptions, type TrackerOptions };
|
package/dist/index.mjs
CHANGED
|
@@ -167,11 +167,12 @@ var Diagnostics = class {
|
|
|
167
167
|
// src/client.ts
|
|
168
168
|
var SDK_NAME = "@eventra_dev/eventra-sdk";
|
|
169
169
|
var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
|
|
170
|
-
var SDK_VERSION = "2.0
|
|
170
|
+
var SDK_VERSION = "2.1.0";
|
|
171
171
|
var LEADER_KEY = "__eventra_leader__";
|
|
172
172
|
var LEADER_TTL_MS = 4e3;
|
|
173
173
|
var QUEUE_KEY = "__eventra_q__";
|
|
174
174
|
var DIAGNOSTICS_KEY = "__eventra_d__";
|
|
175
|
+
var USER_KEY_PREFIX = "__eventra_u__";
|
|
175
176
|
var CHANNEL_NAME = "eventra-sdk";
|
|
176
177
|
var MAX_EVENT_NAME = 64;
|
|
177
178
|
var MAX_USER_ID = 120;
|
|
@@ -190,6 +191,9 @@ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
|
190
191
|
var PERSISTED_QUEUE_MAX_CHARS = 1e6;
|
|
191
192
|
var KEEPALIVE_MAX_BYTES = 6e4;
|
|
192
193
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
194
|
+
var LIVE_TAB_GRACE_MS = 15e3;
|
|
195
|
+
var LIVE_TAB_KEYS_MAX = 1e4;
|
|
196
|
+
var IDENTIFY_HINT_AFTER = 50;
|
|
193
197
|
var activeInstances = 0;
|
|
194
198
|
function detectRuntime() {
|
|
195
199
|
const g = globalThis;
|
|
@@ -256,10 +260,11 @@ function isUrl(value) {
|
|
|
256
260
|
return false;
|
|
257
261
|
}
|
|
258
262
|
}
|
|
263
|
+
function warn(message) {
|
|
264
|
+
if (typeof console !== "undefined") console.warn(message);
|
|
265
|
+
}
|
|
259
266
|
function warnOption(name, value, fallback) {
|
|
260
|
-
|
|
261
|
-
console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
262
|
-
}
|
|
267
|
+
warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
263
268
|
}
|
|
264
269
|
function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
|
|
265
270
|
if (value === void 0) return fallback;
|
|
@@ -313,6 +318,39 @@ function normalizeUserId(value, max) {
|
|
|
313
318
|
if (typeof value !== "string") return void 0;
|
|
314
319
|
return cut(value, max);
|
|
315
320
|
}
|
|
321
|
+
function identifiedUserId(value) {
|
|
322
|
+
const id = normalizeUserId(value, MAX_USER_ID);
|
|
323
|
+
if (id === void 0) return void 0;
|
|
324
|
+
const trimmed = id.trim();
|
|
325
|
+
return trimmed && trimmed !== "undefined" && trimmed !== "null" ? id : void 0;
|
|
326
|
+
}
|
|
327
|
+
function keyHash(value) {
|
|
328
|
+
let hash = 2166136261;
|
|
329
|
+
for (let i = 0; i < value.length; i++) {
|
|
330
|
+
hash ^= value.charCodeAt(i);
|
|
331
|
+
hash = Math.imul(hash, 16777619);
|
|
332
|
+
}
|
|
333
|
+
return (hash >>> 0).toString(16);
|
|
334
|
+
}
|
|
335
|
+
function isReactNative() {
|
|
336
|
+
try {
|
|
337
|
+
return globalThis.navigator?.product === "ReactNative";
|
|
338
|
+
} catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function nodeEnv() {
|
|
343
|
+
try {
|
|
344
|
+
return process.env.NODE_ENV;
|
|
345
|
+
} catch {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function isDevelopment(server) {
|
|
350
|
+
const env = nodeEnv();
|
|
351
|
+
if (env === null || env === "test") return false;
|
|
352
|
+
return server ? env === "development" : env !== "production";
|
|
353
|
+
}
|
|
316
354
|
function stripUnsafeForName(value) {
|
|
317
355
|
let out = "";
|
|
318
356
|
for (let i = 0; i < value.length; i++) {
|
|
@@ -357,7 +395,9 @@ function utf8ByteLength(value) {
|
|
|
357
395
|
function isStoredEvent(e) {
|
|
358
396
|
if (e === null || typeof e !== "object") return false;
|
|
359
397
|
const ev = e;
|
|
360
|
-
return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 &&
|
|
398
|
+
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
|
|
399
|
+
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
|
|
400
|
+
(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));
|
|
361
401
|
}
|
|
362
402
|
function mergeQueues(...queues) {
|
|
363
403
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -391,8 +431,12 @@ function persistedQueueJson(queue) {
|
|
|
391
431
|
}
|
|
392
432
|
var MAX_PROPERTIES_NODES = 5e4;
|
|
393
433
|
function validateProperties(properties) {
|
|
394
|
-
if (
|
|
395
|
-
|
|
434
|
+
if (
|
|
435
|
+
// Stryker disable next-line all: equivalent, track() passes `properties ?? {}`, and any other non-object fails the toString check below
|
|
436
|
+
properties === null || // Stryker disable next-line all: equivalent, see the line above
|
|
437
|
+
typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
|
|
438
|
+
Object.prototype.toString.call(properties) !== "[object Object]"
|
|
439
|
+
) {
|
|
396
440
|
throw new Error("Eventra: properties must be an object");
|
|
397
441
|
}
|
|
398
442
|
const topKeys = Object.keys(properties);
|
|
@@ -454,6 +498,12 @@ var RetryableDeliveryError = class extends Error {
|
|
|
454
498
|
this.name = "RetryableDeliveryError";
|
|
455
499
|
}
|
|
456
500
|
};
|
|
501
|
+
var DeliveryStopped = class extends Error {
|
|
502
|
+
constructor() {
|
|
503
|
+
super("delivery stopped by destroy()");
|
|
504
|
+
this.name = "DeliveryStopped";
|
|
505
|
+
}
|
|
506
|
+
};
|
|
457
507
|
var Storage = class {
|
|
458
508
|
constructor() {
|
|
459
509
|
this.enabled = false;
|
|
@@ -466,6 +516,10 @@ var Storage = class {
|
|
|
466
516
|
} catch {
|
|
467
517
|
}
|
|
468
518
|
}
|
|
519
|
+
// localStorage works here (not in Node, a blocked or private-mode browser)
|
|
520
|
+
get isEnabled() {
|
|
521
|
+
return this.enabled;
|
|
522
|
+
}
|
|
469
523
|
get(key) {
|
|
470
524
|
if (!this.enabled) return null;
|
|
471
525
|
try {
|
|
@@ -490,11 +544,6 @@ var Storage = class {
|
|
|
490
544
|
} catch {
|
|
491
545
|
}
|
|
492
546
|
}
|
|
493
|
-
// Not currently called anywhere in the client — kept for API symmetry with
|
|
494
|
-
// get()/set() on this internal class. No real call site exists to exercise
|
|
495
|
-
// it, and Storage isn't part of the public surface, so a direct call here
|
|
496
|
-
// would only be a reflection-hack test, not real usage.
|
|
497
|
-
/* v8 ignore start */
|
|
498
547
|
remove(key) {
|
|
499
548
|
if (!this.enabled) return;
|
|
500
549
|
try {
|
|
@@ -502,7 +551,6 @@ var Storage = class {
|
|
|
502
551
|
} catch {
|
|
503
552
|
}
|
|
504
553
|
}
|
|
505
|
-
/* v8 ignore stop */
|
|
506
554
|
};
|
|
507
555
|
function storageAvailable() {
|
|
508
556
|
try {
|
|
@@ -637,6 +685,8 @@ var Eventra = class {
|
|
|
637
685
|
constructor(options) {
|
|
638
686
|
this.queue = [];
|
|
639
687
|
this.sending = null;
|
|
688
|
+
// events other open tabs announced on the channel, by key, and until when they are theirs to send
|
|
689
|
+
this.liveTabEvents = /* @__PURE__ */ new Map();
|
|
640
690
|
this.inFlight = false;
|
|
641
691
|
this.destroyed = false;
|
|
642
692
|
this.shuttingDown = false;
|
|
@@ -661,6 +711,16 @@ var Eventra = class {
|
|
|
661
711
|
// the page is being left (`pagehide`)
|
|
662
712
|
this.leaving = false;
|
|
663
713
|
this.exitHandlers = [];
|
|
714
|
+
this.warnedServerIdentify = false;
|
|
715
|
+
this.warnedInvalidIdentify = false;
|
|
716
|
+
this.warnedInvalidUser = false;
|
|
717
|
+
// one user for the whole instance is safe only where the instance serves one person: a browser tab, a React
|
|
718
|
+
// Native app. Everything else (Node, edge, Lambda, Deno, Cloudflare Workers) may serve many requests at once.
|
|
719
|
+
this.singleUser = false;
|
|
720
|
+
this.userKey = USER_KEY_PREFIX;
|
|
721
|
+
// identifyHint: events without a user id so far, and whether the check is over
|
|
722
|
+
this.eventsWithoutUser = 0;
|
|
723
|
+
this.identifyHintDone = false;
|
|
664
724
|
if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
|
|
665
725
|
throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
|
|
666
726
|
}
|
|
@@ -693,6 +753,10 @@ var Eventra = class {
|
|
|
693
753
|
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
|
|
694
754
|
warnOption("diagnostics", options.diagnostics, "true");
|
|
695
755
|
}
|
|
756
|
+
if (options.identifyHint !== void 0 && typeof options.identifyHint !== "boolean") {
|
|
757
|
+
warnOption("identifyHint", options.identifyHint, "true");
|
|
758
|
+
}
|
|
759
|
+
this.identifyHintDone = options.identifyHint === false;
|
|
696
760
|
for (const name of ["maxBatchSize", "maxQueueSize"]) {
|
|
697
761
|
const value = options[name];
|
|
698
762
|
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
|
|
@@ -700,6 +764,8 @@ var Eventra = class {
|
|
|
700
764
|
}
|
|
701
765
|
}
|
|
702
766
|
this.runtime = detectRuntime();
|
|
767
|
+
this.singleUser = this.runtime === "browser" || isReactNative();
|
|
768
|
+
this.userKey = `${USER_KEY_PREFIX}${keyHash(options.apiKey)}`;
|
|
703
769
|
warnIfInsecureEndpoint(this.endpoint);
|
|
704
770
|
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
705
771
|
if (!this.fetch) {
|
|
@@ -731,7 +797,10 @@ var Eventra = class {
|
|
|
731
797
|
};
|
|
732
798
|
if (this.runtime === "browser") {
|
|
733
799
|
if (this.persistQueue) {
|
|
800
|
+
this.userId = this.loadStoredUser();
|
|
734
801
|
this.loadAndMergeQueue();
|
|
802
|
+
} else {
|
|
803
|
+
this.storage.remove(this.userKey);
|
|
735
804
|
}
|
|
736
805
|
this.setupQueueSync();
|
|
737
806
|
}
|
|
@@ -769,14 +838,86 @@ var Eventra = class {
|
|
|
769
838
|
}
|
|
770
839
|
}
|
|
771
840
|
track(name, options) {
|
|
841
|
+
this.trackSafely(name, options, void 0);
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Sets the user of every following event that does not name its own, in a browser or a React Native app. In
|
|
845
|
+
* the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open
|
|
846
|
+
* tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may
|
|
847
|
+
* serve many users at once, so it is ignored with one warning: use `withUser()` there.
|
|
848
|
+
*/
|
|
849
|
+
identify(userId) {
|
|
850
|
+
if (this.destroyed) return;
|
|
851
|
+
if (!this.singleUser) {
|
|
852
|
+
if (!this.warnedServerIdentify) {
|
|
853
|
+
this.warnedServerIdentify = true;
|
|
854
|
+
warn(
|
|
855
|
+
"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)"
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
const id = identifiedUserId(userId);
|
|
861
|
+
if (id === void 0) {
|
|
862
|
+
if (!this.warnedInvalidIdentify) {
|
|
863
|
+
this.warnedInvalidIdentify = true;
|
|
864
|
+
warn("Eventra: identify() needs a user id (a non-empty string or a number) - to sign a user out, call reset()");
|
|
865
|
+
}
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
this.identifyHintDone = true;
|
|
869
|
+
if (id !== this.userId) this.setUser(id);
|
|
870
|
+
}
|
|
871
|
+
/** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */
|
|
872
|
+
reset() {
|
|
873
|
+
if (this.destroyed || !this.singleUser) return;
|
|
874
|
+
this.setUser(void 0);
|
|
875
|
+
}
|
|
876
|
+
/** The user set by `identify()`, if any. */
|
|
877
|
+
getUserId() {
|
|
878
|
+
return this.userId;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares
|
|
882
|
+
* this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events
|
|
883
|
+
* without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.
|
|
884
|
+
*/
|
|
885
|
+
withUser(userId) {
|
|
886
|
+
let id;
|
|
887
|
+
if (userId !== void 0 && userId !== null) {
|
|
888
|
+
id = identifiedUserId(userId);
|
|
889
|
+
if (id === void 0 && !this.warnedInvalidUser) {
|
|
890
|
+
this.warnedInvalidUser = true;
|
|
891
|
+
warn("Eventra: withUser() got an invalid user id (it needs a non-empty string or a number), its events are sent without one");
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (id !== void 0) this.identifyHintDone = true;
|
|
895
|
+
const scopeUser = id ?? null;
|
|
896
|
+
return {
|
|
897
|
+
track: (name, options) => this.trackSafely(name, options, scopeUser)
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
setUser(id) {
|
|
901
|
+
this.userId = id;
|
|
902
|
+
if (this.runtime !== "browser") return;
|
|
903
|
+
if (id === void 0) this.storage.remove(this.userKey);
|
|
904
|
+
else if (this.persistQueue) this.storage.set(this.userKey, id);
|
|
905
|
+
this.broadcast({ type: "user", key: this.userKey, userId: id ?? null });
|
|
906
|
+
}
|
|
907
|
+
loadStoredUser() {
|
|
908
|
+
const saved = this.storage.get(this.userKey);
|
|
909
|
+
return typeof saved === "string" ? identifiedUserId(saved) : void 0;
|
|
910
|
+
}
|
|
911
|
+
// scopeUserId: undefined outside a scope, null for a scope without a user
|
|
912
|
+
trackSafely(name, options, scopeUserId) {
|
|
772
913
|
try {
|
|
773
|
-
this.trackEvent(name, options);
|
|
914
|
+
this.trackEvent(name, options, scopeUserId);
|
|
774
915
|
} catch {
|
|
775
916
|
this.recordDiagnostic("invalid_event");
|
|
776
917
|
callSafely(this.options.onEventsDropped, 1);
|
|
777
918
|
}
|
|
778
919
|
}
|
|
779
|
-
trackEvent(name, options) {
|
|
920
|
+
trackEvent(name, options, scopeUserId) {
|
|
780
921
|
if (this.destroyed || this.shuttingDown) return;
|
|
781
922
|
const eventName = normalizeEventName(name);
|
|
782
923
|
if (eventName === null) {
|
|
@@ -797,14 +938,17 @@ var Eventra = class {
|
|
|
797
938
|
callSafely(this.options.onEventsDropped, 1);
|
|
798
939
|
return;
|
|
799
940
|
}
|
|
941
|
+
const given = options?.userId;
|
|
942
|
+
const ownUserId = typeof given === "string" && !given.trim() ? void 0 : given;
|
|
800
943
|
const event = {
|
|
801
944
|
idempotencyKey: uuidV4(),
|
|
802
945
|
name: eventName,
|
|
803
|
-
userId: normalizeUserId(
|
|
946
|
+
userId: ownUserId !== void 0 ? normalizeUserId(ownUserId, MAX_USER_ID) : scopeUserId !== void 0 ? scopeUserId ?? void 0 : this.userId,
|
|
804
947
|
properties,
|
|
805
948
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
806
949
|
};
|
|
807
950
|
this.queue.push(event);
|
|
951
|
+
if (!this.identifyHintDone) this.checkIdentifyHint(identifiedUserId(event.userId) !== void 0);
|
|
808
952
|
if (this.runtime === "browser") {
|
|
809
953
|
this.schedulePersist();
|
|
810
954
|
this.broadcast({ type: "queue-add", events: [event] });
|
|
@@ -925,6 +1069,12 @@ var Eventra = class {
|
|
|
925
1069
|
activeInstances = Math.max(0, activeInstances - 1);
|
|
926
1070
|
if (this.timer) clearInterval(this.timer);
|
|
927
1071
|
this.persistNow();
|
|
1072
|
+
const kept = this.runtime === "browser" && this.persistQueue && this.storage.isEnabled;
|
|
1073
|
+
if (!kept) {
|
|
1074
|
+
const inFlight = new Set(this.sending ?? []);
|
|
1075
|
+
const lost = this.queue.filter((event) => !inFlight.has(event)).length;
|
|
1076
|
+
if (lost > 0) callSafely(this.options.onEventsDropped, lost);
|
|
1077
|
+
}
|
|
928
1078
|
this.leader?.destroy();
|
|
929
1079
|
if (this.channel) {
|
|
930
1080
|
try {
|
|
@@ -955,6 +1105,10 @@ var Eventra = class {
|
|
|
955
1105
|
let index = 0;
|
|
956
1106
|
while (index < this.queue.length && events.length < this.maxBatch) {
|
|
957
1107
|
const event = this.queue[index];
|
|
1108
|
+
if (this.leftToItsTab(event)) {
|
|
1109
|
+
index++;
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
958
1112
|
let eventJson;
|
|
959
1113
|
try {
|
|
960
1114
|
eventJson = JSON.stringify(event);
|
|
@@ -989,6 +1143,20 @@ var Eventra = class {
|
|
|
989
1143
|
diagnostics: withReport && report ? report : void 0
|
|
990
1144
|
};
|
|
991
1145
|
}
|
|
1146
|
+
// one warning during development when an app sends events without ever saying whose they are
|
|
1147
|
+
checkIdentifyHint(hasUser) {
|
|
1148
|
+
if (hasUser) {
|
|
1149
|
+
this.identifyHintDone = true;
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
if (++this.eventsWithoutUser < IDENTIFY_HINT_AFTER) return;
|
|
1153
|
+
this.identifyHintDone = true;
|
|
1154
|
+
if (!isDevelopment(!this.singleUser)) return;
|
|
1155
|
+
const how = this.singleUser ? "call tracker.identify(userId) after sign-in" : "track through tracker.withUser(userId) in each request";
|
|
1156
|
+
warn(
|
|
1157
|
+
`Eventra: none of the first ${IDENTIFY_HINT_AFTER} events has a userId, so unique users cannot be counted - ${how} (identifyHint: false turns this off)`
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
992
1160
|
dropPoisonEvent(event) {
|
|
993
1161
|
this.recordDiagnostic("too_large");
|
|
994
1162
|
this.removeDelivered([event]);
|
|
@@ -1024,8 +1192,13 @@ var Eventra = class {
|
|
|
1024
1192
|
this.dropPoisonEvents(events);
|
|
1025
1193
|
return false;
|
|
1026
1194
|
}
|
|
1027
|
-
const useKeepalive =
|
|
1028
|
-
|
|
1195
|
+
const useKeepalive = (
|
|
1196
|
+
// Stryker disable next-line all: equivalent, document exists exactly in the browser runtime
|
|
1197
|
+
this.runtime === "browser" && // Stryker disable next-line all: equivalent, see the line above
|
|
1198
|
+
typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
|
|
1199
|
+
// Stryker disable next-line EqualityOperator: a body of exactly the keepalive limit; not worth a 60,000-byte fixture
|
|
1200
|
+
payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES)
|
|
1201
|
+
);
|
|
1029
1202
|
const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
|
|
1030
1203
|
let strippedDiagnostics = false;
|
|
1031
1204
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
@@ -1053,7 +1226,9 @@ var Eventra = class {
|
|
|
1053
1226
|
discardBody(res);
|
|
1054
1227
|
if (res.status === 429 || res.status >= 500) {
|
|
1055
1228
|
throw new RetryableDeliveryError(
|
|
1229
|
+
// Stryker disable next-line StringLiteral: the message is never read
|
|
1056
1230
|
"retryable delivery error",
|
|
1231
|
+
// Stryker disable next-line OptionalChaining: equivalent with a real Response, which always has headers.get
|
|
1057
1232
|
parseRetryAfterMs(res.headers?.get?.("retry-after")),
|
|
1058
1233
|
res.status === 429 ? "rate_limited" : "server_error"
|
|
1059
1234
|
);
|
|
@@ -1094,6 +1269,7 @@ var Eventra = class {
|
|
|
1094
1269
|
throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
|
|
1095
1270
|
}
|
|
1096
1271
|
await sleep(wait);
|
|
1272
|
+
if (this.destroyed) throw new DeliveryStopped();
|
|
1097
1273
|
} finally {
|
|
1098
1274
|
clearTimeout(timeout);
|
|
1099
1275
|
}
|
|
@@ -1181,11 +1357,34 @@ var Eventra = class {
|
|
|
1181
1357
|
}
|
|
1182
1358
|
trimQueue(queue = this.queue) {
|
|
1183
1359
|
if (queue.length <= this.maxQueue) return queue;
|
|
1184
|
-
const
|
|
1185
|
-
this.
|
|
1186
|
-
|
|
1360
|
+
const removed = queue.slice(0, queue.length - this.maxQueue);
|
|
1361
|
+
const dropped = removed.filter((e) => !this.liveTabEvents.has(e?.idempotencyKey)).length;
|
|
1362
|
+
if (dropped > 0) {
|
|
1363
|
+
this.recordDiagnostic("queue_full", dropped);
|
|
1364
|
+
callSafely(this.options.onEventsDropped, dropped);
|
|
1365
|
+
}
|
|
1187
1366
|
return queue.slice(-this.maxQueue);
|
|
1188
1367
|
}
|
|
1368
|
+
// events another open tab just announced on the channel, with the time until which that tab sends them
|
|
1369
|
+
rememberLiveTabEvents(events) {
|
|
1370
|
+
const until = Date.now() + LIVE_TAB_GRACE_MS;
|
|
1371
|
+
for (const event of events) {
|
|
1372
|
+
const key = event?.idempotencyKey;
|
|
1373
|
+
if (typeof key === "string" && !this.liveTabEvents.has(key)) this.liveTabEvents.set(key, until);
|
|
1374
|
+
}
|
|
1375
|
+
for (const key of this.liveTabEvents.keys()) {
|
|
1376
|
+
if (this.liveTabEvents.size <= LIVE_TAB_KEYS_MAX) break;
|
|
1377
|
+
this.liveTabEvents.delete(key);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
// In `independent` mode, an event another open tab announced less than LIVE_TAB_GRACE_MS ago is that
|
|
1381
|
+
// tab's to send. After that (the tab was closed, or it cannot reach the server either) anyone sends it.
|
|
1382
|
+
// The leader in `leader` mode sends everything, so it never waits.
|
|
1383
|
+
leftToItsTab(event) {
|
|
1384
|
+
if (this.leader) return false;
|
|
1385
|
+
const until = this.liveTabEvents.get(event?.idempotencyKey);
|
|
1386
|
+
return until !== void 0 && Date.now() < until;
|
|
1387
|
+
}
|
|
1189
1388
|
// Sends only what changed (a new event, or the keys just delivered) instead
|
|
1190
1389
|
// of structured-cloning the whole queue on every call.
|
|
1191
1390
|
broadcast(message) {
|
|
@@ -1205,21 +1404,31 @@ var Eventra = class {
|
|
|
1205
1404
|
if (this.channel) {
|
|
1206
1405
|
this.channel.onmessage = (e) => {
|
|
1207
1406
|
const data = e.data;
|
|
1407
|
+
if (data?.type === "user") {
|
|
1408
|
+
if (data.key !== this.userKey) return;
|
|
1409
|
+
if (data.userId === null) this.userId = void 0;
|
|
1410
|
+
else if (typeof data.userId === "string") this.userId = identifiedUserId(data.userId) ?? this.userId;
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1208
1413
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
1209
1414
|
const keys = new Set(data.keys);
|
|
1210
1415
|
this.rememberDelivered(keys);
|
|
1416
|
+
for (const key of keys) this.liveTabEvents.delete(key);
|
|
1211
1417
|
this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
|
|
1212
1418
|
return;
|
|
1213
1419
|
}
|
|
1214
1420
|
if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
|
|
1215
1421
|
return;
|
|
1216
1422
|
}
|
|
1217
|
-
|
|
1423
|
+
const announced = this.withoutDelivered(data.events);
|
|
1424
|
+
this.rememberLiveTabEvents(announced);
|
|
1425
|
+
this.queue = mergeQueues(this.queue, announced);
|
|
1218
1426
|
this.queue = this.trimQueue();
|
|
1219
1427
|
};
|
|
1220
1428
|
}
|
|
1221
1429
|
if (this.persistQueue && typeof window !== "undefined") {
|
|
1222
1430
|
this.offStorageQueue = listen(window, "storage", (e) => {
|
|
1431
|
+
if (e.key === this.userKey || e.key === null) this.userId = this.loadStoredUser();
|
|
1223
1432
|
if (e.key !== QUEUE_KEY) return;
|
|
1224
1433
|
this.loadAndMergeQueue();
|
|
1225
1434
|
});
|