@eventra_dev/eventra-sdk 2.0.12 → 2.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -167,7 +167,7 @@ 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.12";
170
+ var SDK_VERSION = "2.0.13";
171
171
  var LEADER_KEY = "__eventra_leader__";
172
172
  var LEADER_TTL_MS = 4e3;
173
173
  var QUEUE_KEY = "__eventra_q__";
@@ -187,17 +187,40 @@ var RETRY_AFTER_MAX_MS = 3e4;
187
187
  var PERSIST_DEBOUNCE_MS = 50;
188
188
  var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
189
189
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
190
+ var PERSISTED_QUEUE_MAX_CHARS = 1e6;
190
191
  var KEEPALIVE_MAX_BYTES = 6e4;
191
192
  var DELIVERED_KEYS_MAX = 1e4;
192
193
  var activeInstances = 0;
193
194
  function detectRuntime() {
194
195
  const g = globalThis;
195
- if (typeof window !== "undefined" && !g.EdgeRuntime) return "browser";
196
196
  if (g.EdgeRuntime) return "edge";
197
+ if (hasBrowserEvents()) return "browser";
197
198
  if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return "serverless";
198
199
  if (g.process?.versions?.node) return "node";
199
200
  return "unknown";
200
201
  }
202
+ function hasBrowserEvents() {
203
+ try {
204
+ return typeof window !== "undefined" && window !== null && typeof window.addEventListener === "function" && typeof document !== "undefined" && document !== null && typeof document.addEventListener === "function";
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+ function listen(target, type, listener) {
210
+ const t = target;
211
+ try {
212
+ if (!t || typeof t.addEventListener !== "function") return () => void 0;
213
+ t.addEventListener(type, listener);
214
+ } catch {
215
+ return () => void 0;
216
+ }
217
+ return () => {
218
+ try {
219
+ t.removeEventListener?.(type, listener);
220
+ } catch {
221
+ }
222
+ };
223
+ }
201
224
  function uuidV4() {
202
225
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
203
226
  return crypto.randomUUID();
@@ -224,6 +247,7 @@ function uuidV4() {
224
247
  }
225
248
  var MAX_TIMER_MS = 2147483647;
226
249
  var MAX_RETRIES = 20;
250
+ var MAX_BATCH_SIZE = 500;
227
251
  function isUrl(value) {
228
252
  try {
229
253
  new URL(value);
@@ -289,9 +313,27 @@ function normalizeUserId(value, max) {
289
313
  if (typeof value !== "string") return void 0;
290
314
  return cut(value, max);
291
315
  }
316
+ function stripUnsafeForName(value) {
317
+ let out = "";
318
+ for (let i = 0; i < value.length; i++) {
319
+ const code = value.charCodeAt(i);
320
+ if (code === 0 || code === 10 || code === 13) continue;
321
+ if (code >= 55296 && code <= 56319) {
322
+ const next = value.charCodeAt(i + 1);
323
+ if (next >= 56320 && next <= 57343) {
324
+ out += value[i] + value[i + 1];
325
+ i++;
326
+ }
327
+ continue;
328
+ }
329
+ if (code >= 56320 && code <= 57343) continue;
330
+ out += value[i];
331
+ }
332
+ return out;
333
+ }
292
334
  function normalizeEventName(name) {
293
335
  if (typeof name !== "string") return null;
294
- const trimmed = name.trim();
336
+ const trimmed = stripUnsafeForName(name).trim();
295
337
  if (!trimmed) return null;
296
338
  return cut(trimmed, MAX_EVENT_NAME).trimEnd();
297
339
  }
@@ -330,20 +372,33 @@ function mergeQueues(...queues) {
330
372
  }
331
373
  return out;
332
374
  }
375
+ function persistedQueueJson(queue) {
376
+ const parts = [];
377
+ let chars = 2;
378
+ for (let i = queue.length - 1; i >= 0; i--) {
379
+ let json;
380
+ try {
381
+ json = JSON.stringify(queue[i]);
382
+ } catch {
383
+ continue;
384
+ }
385
+ const next = chars + json.length + (parts.length ? 1 : 0);
386
+ if (next > PERSISTED_QUEUE_MAX_CHARS) break;
387
+ parts.push(json);
388
+ chars = next;
389
+ }
390
+ return `[${parts.reverse().join(",")}]`;
391
+ }
333
392
  var MAX_PROPERTIES_NODES = 5e4;
334
393
  function validateProperties(properties) {
335
394
  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
336
395
  Object.prototype.toString.call(properties) !== "[object Object]") {
337
396
  throw new Error("Eventra: properties must be an object");
338
397
  }
339
- let hasKeys = false;
340
- for (const _ in properties) {
341
- hasKeys = true;
342
- break;
343
- }
344
- if (!hasKeys) return {};
398
+ const topKeys = Object.keys(properties);
399
+ if (topKeys.length === 0) return {};
345
400
  let visited = 0;
346
- const depth = (obj, level) => {
401
+ const depth = (obj, level, keys) => {
347
402
  if (level > MAX_PROPERTIES_DEPTH) {
348
403
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
349
404
  }
@@ -352,14 +407,19 @@ function validateProperties(properties) {
352
407
  }
353
408
  if (obj === null || typeof obj !== "object") return;
354
409
  if (Array.isArray(obj)) {
410
+ if (visited + obj.length > MAX_PROPERTIES_NODES) {
411
+ throw new Error("Eventra: properties are too large to check");
412
+ }
355
413
  for (const item of obj) depth(item, level + 1);
356
414
  return;
357
415
  }
358
- for (const key in obj) {
359
- if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
416
+ const own = keys ?? Object.keys(obj);
417
+ if (visited + own.length > MAX_PROPERTIES_NODES) {
418
+ throw new Error("Eventra: properties are too large to check");
360
419
  }
420
+ for (const key of own) depth(obj[key], level + 1);
361
421
  };
362
- depth(properties, 0);
422
+ depth(properties, 0, topKeys);
363
423
  const json = JSON.stringify(properties);
364
424
  if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
365
425
  throw new Error(
@@ -415,9 +475,18 @@ var Storage = class {
415
475
  }
416
476
  }
417
477
  set(key, value) {
478
+ let json;
479
+ try {
480
+ json = JSON.stringify(value);
481
+ } catch {
482
+ return;
483
+ }
484
+ this.setRaw(key, json);
485
+ }
486
+ setRaw(key, json) {
418
487
  if (!this.enabled) return;
419
488
  try {
420
- localStorage.setItem(key, JSON.stringify(value));
489
+ localStorage.setItem(key, json);
421
490
  } catch {
422
491
  }
423
492
  }
@@ -453,12 +522,9 @@ var Leader = class {
453
522
  }
454
523
  this.tick();
455
524
  this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);
456
- if (typeof window !== "undefined") {
457
- this.onStorage = (e) => {
458
- if (e.key === LEADER_KEY) this.tick();
459
- };
460
- window.addEventListener("storage", this.onStorage);
461
- }
525
+ this.offStorage = listen(typeof window !== "undefined" ? window : void 0, "storage", (e) => {
526
+ if (e.key === LEADER_KEY) this.tick();
527
+ });
462
528
  }
463
529
  tick() {
464
530
  const was = this.isLeader;
@@ -531,9 +597,7 @@ var Leader = class {
531
597
  destroy() {
532
598
  if (this.election) clearInterval(this.election);
533
599
  if (this.heartbeat) clearInterval(this.heartbeat);
534
- if (this.onStorage && typeof window !== "undefined") {
535
- window.removeEventListener("storage", this.onStorage);
536
- }
600
+ this.offStorage?.();
537
601
  if (this.isLeader && storageAvailable()) {
538
602
  try {
539
603
  const raw = localStorage.getItem(LEADER_KEY);
@@ -641,7 +705,10 @@ var Eventra = class {
641
705
  if (!this.fetch) {
642
706
  throw new Error("Eventra: fetch not available - provide fetchImpl");
643
707
  }
644
- this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
708
+ if (typeof options.maxBatchSize === "number" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {
709
+ warnOption("maxBatchSize", options.maxBatchSize, MAX_BATCH_SIZE);
710
+ }
711
+ this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1)));
645
712
  this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
646
713
  this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
647
714
  this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
@@ -866,9 +933,7 @@ var Eventra = class {
866
933
  }
867
934
  this.channel = void 0;
868
935
  }
869
- if (this.onStorageQueue && typeof window !== "undefined") {
870
- window.removeEventListener("storage", this.onStorageQueue);
871
- }
936
+ this.offStorageQueue?.();
872
937
  for (const off of this.exitHandlers) {
873
938
  off();
874
939
  }
@@ -1112,7 +1177,7 @@ var Eventra = class {
1112
1177
  this.queue
1113
1178
  );
1114
1179
  this.queue = this.trimQueue(merged);
1115
- this.storage.set(QUEUE_KEY, this.queue);
1180
+ this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));
1116
1181
  }
1117
1182
  trimQueue(queue = this.queue) {
1118
1183
  if (queue.length <= this.maxQueue) return queue;
@@ -1154,11 +1219,10 @@ var Eventra = class {
1154
1219
  };
1155
1220
  }
1156
1221
  if (this.persistQueue && typeof window !== "undefined") {
1157
- this.onStorageQueue = (e) => {
1222
+ this.offStorageQueue = listen(window, "storage", (e) => {
1158
1223
  if (e.key !== QUEUE_KEY) return;
1159
1224
  this.loadAndMergeQueue();
1160
- };
1161
- window.addEventListener("storage", this.onStorageQueue);
1225
+ });
1162
1226
  }
1163
1227
  }
1164
1228
  startTimer() {
@@ -1177,29 +1241,99 @@ var Eventra = class {
1177
1241
  const pageHide = () => {
1178
1242
  this.leaving = true;
1179
1243
  this.persistNow();
1180
- void this.flush();
1244
+ if (this.inFlight) {
1245
+ this.sendOnLeave();
1246
+ } else {
1247
+ void this.flush();
1248
+ }
1181
1249
  };
1182
- document.addEventListener("visibilitychange", handler);
1183
- window.addEventListener("pagehide", pageHide);
1184
- this.exitHandlers.push(() => {
1185
- document.removeEventListener("visibilitychange", handler);
1186
- window.removeEventListener("pagehide", pageHide);
1187
- });
1250
+ const pageShow = () => {
1251
+ this.leaving = false;
1252
+ };
1253
+ const offs = [
1254
+ listen(document, "visibilitychange", handler),
1255
+ listen(window, "pagehide", pageHide),
1256
+ listen(window, "pageshow", pageShow)
1257
+ ];
1258
+ this.exitHandlers.push(() => offs.forEach((off) => off()));
1259
+ }
1260
+ /**
1261
+ * The page is being left while a request is in flight: send what is queued at once with keepalive, without
1262
+ * waiting for that request. The events of the batch in flight go along too (after the others, as far as the
1263
+ * keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server
1264
+ * drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.
1265
+ */
1266
+ sendOnLeave() {
1267
+ if (this.leader && !this.leader.canSend()) return;
1268
+ const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));
1269
+ const candidates = [
1270
+ ...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),
1271
+ ...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey))
1272
+ ];
1273
+ const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
1274
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
1275
+ let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));
1276
+ const events = [];
1277
+ const json = [];
1278
+ for (const event of candidates) {
1279
+ if (events.length >= MAX_BATCH_SIZE) break;
1280
+ let eventJson;
1281
+ try {
1282
+ eventJson = JSON.stringify(event);
1283
+ } catch {
1284
+ continue;
1285
+ }
1286
+ const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
1287
+ if (total2 > limit) continue;
1288
+ events.push(event);
1289
+ json.push(eventJson);
1290
+ bytes = total2;
1291
+ }
1292
+ if (!events.length) return;
1293
+ const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });
1294
+ const body = `${head.slice(0, -1)},"events":[${json.join(",")}]}`;
1295
+ try {
1296
+ const request = this.fetch(this.endpoint, {
1297
+ method: "POST",
1298
+ headers: {
1299
+ "Content-Type": "application/json",
1300
+ "x-api-key": this.apiKey
1301
+ },
1302
+ body,
1303
+ keepalive: true,
1304
+ redirect: "error"
1305
+ });
1306
+ Promise.resolve(request).then(
1307
+ (res) => {
1308
+ discardBody(res);
1309
+ if (res.ok && !this.destroyed) this.removeDelivered(events);
1310
+ },
1311
+ () => void 0
1312
+ );
1313
+ } catch {
1314
+ }
1188
1315
  }
1189
1316
  setupProcessExit() {
1190
1317
  const proc = globalThis.process;
1191
1318
  if (!proc?.on) return;
1192
- const exitOnSignal = this.options.exitOnSignal === true;
1319
+ const exitOnSignal = this.options.exitOnSignal !== false;
1193
1320
  const onSignal = (signal) => () => {
1321
+ proc.off?.(signal, handlers[signal]);
1322
+ const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;
1194
1323
  void this.shutdown().finally(() => {
1195
- if (!exitOnSignal) return;
1196
- proc.off?.(signal, handlers[signal]);
1324
+ if (!exitOnSignal || othersAtSignal) return;
1197
1325
  const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
1198
- if (!othersListening && proc.kill && proc.pid !== void 0) {
1326
+ if (othersListening) return;
1327
+ if (proc.pid === 1 && proc.exit) {
1328
+ proc.exit(128 + (signal === "SIGINT" ? 2 : 15));
1329
+ return;
1330
+ }
1331
+ if (proc.kill && proc.pid !== void 0) {
1199
1332
  proc.kill(proc.pid, signal);
1200
1333
  }
1201
1334
  });
1202
1335
  };
1336
+ const listenFirst = (event, listener) => typeof proc.prependOnceListener === "function" ? proc.prependOnceListener(event, listener) : proc.once(event, listener);
1203
1337
  const handlers = {
1204
1338
  SIGINT: onSignal("SIGINT"),
1205
1339
  SIGTERM: onSignal("SIGTERM")
@@ -1219,8 +1353,8 @@ var Eventra = class {
1219
1353
  if (!this.queue.length) listenAgain();
1220
1354
  });
1221
1355
  };
1222
- proc.once("SIGINT", handlers.SIGINT);
1223
- proc.once("SIGTERM", handlers.SIGTERM);
1356
+ listenFirst("SIGINT", handlers.SIGINT);
1357
+ listenFirst("SIGTERM", handlers.SIGTERM);
1224
1358
  proc.once("beforeExit", onBeforeExit);
1225
1359
  this.exitHandlers.push(() => {
1226
1360
  proc.off?.("SIGINT", handlers.SIGINT);