@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.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diagnostics.ts","../src/client.ts"],"sourcesContent":["// Delivery diagnostics: counters of what the SDK itself could not deliver, so\n// the dashboard can say how many events never arrived. Numbers only - never\n// event names, user ids or properties.\n//\n// Counters accumulate locally, are moved into a \"pending\" report right before\n// they are attached to a batch, and are removed only after the server answered\n// 2xx for that very batch. A failed send keeps the pending report, which is\n// re-sent with the same `reportId` (the server counts a reportId once), so a\n// retry or a lost response never double reports and a failure never loses it.\n\n// events the SDK gave up on\nexport type DroppedReason =\n | \"queue_full\" // queue overflow\n | \"invalid_event\" // empty name or unusable properties\n | \"too_large\" // a single event above the payload limit\n | \"rejected\"; // the server answered 4xx (not 429)\n\n// failed send attempts: one per batch that could not be delivered after all\n// retries (the events stay queued). `failedTotal` counts these; `circuit_open`\n// is listed by reason only and is not added to the total.\nexport type FailedReason =\n | \"network\" // blocked, offline, DNS, timeout\n | \"server_error\" // 5xx\n | \"rate_limited\" // 429\n | \"circuit_open\"; // the circuit breaker opened\n\nexport type DiagnosticsReason = DroppedReason | FailedReason;\n\nconst DROPPED_REASONS: ReadonlySet<string> = new Set([\n \"queue_full\",\n \"invalid_event\",\n \"too_large\",\n \"rejected\",\n]);\nconst FAILED_REASONS: ReadonlySet<string> = new Set([\n \"network\",\n \"server_error\",\n \"rate_limited\",\n \"circuit_open\",\n]);\n\n// a counter can never exceed this, so the payload stays tiny and numeric\nconst COUNT_MAX = 1_000_000_000;\n\nexport interface DiagnosticsReport {\n /** one id per report, the server counts it once */\n reportId: string;\n /** when the oldest counted problem happened (ISO) */\n since: string;\n droppedTotal: number;\n /** failed send attempts (batches that failed after retries), not events */\n failedTotal: number;\n byReason: Record<string, number>;\n /** events waiting in the queue when the report was built */\n queued: number;\n sdkVersion: string;\n}\n\ninterface Counts {\n dropped: number;\n failed: number;\n byReason: Record<string, number>;\n since?: string;\n}\n\ninterface PendingReport {\n reportId: string;\n counts: Counts;\n}\n\ninterface StoredRecord {\n counts: Counts;\n pending?: PendingReport;\n}\n\nexport interface DiagnosticsStore {\n get(key: string): unknown;\n set(key: string, value: unknown): void;\n}\n\n// used in Node, and in the browser when the queue must not touch localStorage\nexport class MemoryStore implements DiagnosticsStore {\n private data = new Map<string, unknown>();\n\n get(key: string): unknown {\n return this.data.get(key) ?? null;\n }\n\n set(key: string, value: unknown) {\n this.data.set(key, value);\n }\n}\n\n// localStorage first (shared by tabs and surviving a reload), memory as the\n// fallback when storage is blocked (private mode) and so reads nothing back\nexport class SharedStore implements DiagnosticsStore {\n private memory = new MemoryStore();\n\n constructor(private readonly storage: DiagnosticsStore) {}\n\n get(key: string): unknown {\n return this.storage.get(key) ?? this.memory.get(key);\n }\n\n set(key: string, value: unknown) {\n this.memory.set(key, value);\n this.storage.set(key, value);\n }\n}\n\nfunction emptyCounts(): Counts {\n return { dropped: 0, failed: 0, byReason: {} };\n}\n\nfunction isCount(value: unknown): value is number {\n return (\n typeof value === \"number\" &&\n Number.isInteger(value) &&\n value >= 0 &&\n value <= COUNT_MAX\n );\n}\n\nfunction parseCounts(value: unknown): Counts | null {\n if (typeof value !== \"object\" || value === null) return null;\n const v = value as Record<string, unknown>;\n if (!isCount(v.dropped) || !isCount(v.failed)) return null;\n\n const byReason: Record<string, number> = {};\n const raw = v.byReason;\n if (typeof raw === \"object\" && raw !== null) {\n for (const [reason, count] of Object.entries(raw)) {\n if (\n (DROPPED_REASONS.has(reason) || FAILED_REASONS.has(reason)) &&\n isCount(count)\n ) {\n byReason[reason] = count;\n }\n }\n }\n\n const since =\n typeof v.since === \"string\" && !Number.isNaN(Date.parse(v.since))\n ? v.since\n : undefined;\n\n return { dropped: v.dropped, failed: v.failed, byReason, since };\n}\n\n// what is in storage may be stale, hand-edited or from another version: only\n// a well-formed record is used, anything else starts over\nfunction parseRecord(value: unknown): StoredRecord {\n if (typeof value !== \"object\" || value === null) {\n return { counts: emptyCounts() };\n }\n const v = value as Record<string, unknown>;\n const counts = parseCounts(v.counts) ?? emptyCounts();\n\n let pending: PendingReport | undefined;\n const p = v.pending as Record<string, unknown> | undefined;\n if (typeof p === \"object\" && p !== null && typeof p.reportId === \"string\") {\n const pendingCounts = parseCounts(p.counts);\n if (pendingCounts) pending = { reportId: p.reportId, counts: pendingCounts };\n }\n\n return { counts, pending };\n}\n\nfunction total(counts: Counts): number {\n return counts.dropped + counts.failed;\n}\n\nfunction add(into: Counts, from: Counts) {\n into.dropped = Math.min(COUNT_MAX, into.dropped + from.dropped);\n into.failed = Math.min(COUNT_MAX, into.failed + from.failed);\n for (const [reason, count] of Object.entries(from.byReason)) {\n into.byReason[reason] = Math.min(\n COUNT_MAX,\n (into.byReason[reason] ?? 0) + count,\n );\n }\n if (from.since && (!into.since || from.since < into.since)) {\n into.since = from.since;\n }\n}\n\nexport class Diagnostics {\n // not yet merged into the (possibly shared) record\n private local: Counts = emptyCounts();\n private dirty = false;\n\n constructor(\n private readonly store: DiagnosticsStore,\n private readonly key: string,\n private readonly newId: () => string,\n private readonly onChange: () => void = () => {},\n ) {}\n\n record(reason: DiagnosticsReason, n = 1) {\n if (!(n > 0)) return;\n const isDropped = DROPPED_REASONS.has(reason);\n\n if (isDropped) {\n this.local.dropped = Math.min(COUNT_MAX, this.local.dropped + n);\n } else if (reason !== \"circuit_open\") {\n // `circuit_open` is an extra detail of a failure that was already\n // counted, so it appears in byReason only and never in failedTotal\n this.local.failed = Math.min(COUNT_MAX, this.local.failed + n);\n }\n this.local.byReason[reason] = Math.min(\n COUNT_MAX,\n (this.local.byReason[reason] ?? 0) + n,\n );\n this.local.since ??= new Date().toISOString();\n\n this.dirty = true;\n this.onChange();\n }\n\n // writes the local counters into the shared record (debounced by the client,\n // immediate on pagehide/destroy); a no-op when nothing changed\n sync() {\n if (!this.dirty) return;\n const record = this.read();\n add(record.counts, this.local);\n this.local = emptyCounts();\n this.dirty = false;\n this.store.set(this.key, record);\n }\n\n // Moves the counters into a pending report and returns it; an unacknowledged\n // pending report is returned again as it is. null when there is nothing to\n // report or another tab claimed the same counters first.\n claim(queued: number, sdkVersion: string): DiagnosticsReport | null {\n this.dirty = this.dirty || total(this.local) > 0;\n this.sync();\n\n const record = this.read();\n\n if (!record.pending) {\n if (total(record.counts) === 0) return null;\n\n const reportId = this.newId();\n record.pending = { reportId, counts: record.counts };\n record.counts = emptyCounts();\n this.store.set(this.key, record);\n\n // two tabs claiming at the same moment: only the one whose claim is what\n // is stored sends it, the other sends nothing this round\n const stored = this.read();\n if (stored.pending?.reportId !== reportId) return null;\n }\n\n const { reportId, counts } = record.pending;\n return {\n reportId,\n since: counts.since ?? new Date().toISOString(),\n droppedTotal: counts.dropped,\n failedTotal: counts.failed,\n byReason: { ...counts.byReason },\n queued,\n sdkVersion,\n };\n }\n\n // the server accepted the batch the report travelled with\n ack(reportId: string) {\n const record = this.read();\n if (record.pending?.reportId !== reportId) return;\n record.pending = undefined;\n this.store.set(this.key, record);\n }\n\n private read(): StoredRecord {\n return parseRecord(this.store.get(this.key));\n }\n}\n","import { TrackerOptions, TrackEvent, SdkInfo, TrackOptions } from \"./types\";\nimport {\n Diagnostics,\n DiagnosticsReport,\n FailedReason,\n MemoryStore,\n SharedStore,\n} from \"./diagnostics\";\n\ndeclare const __SDK_VERSION__: string | undefined;\ndeclare const __EVENTRA_ENDPOINT__: string | undefined;\n\nconst SDK_NAME = \"@eventra_dev/eventra-sdk\";\n// `__EVENTRA_ENDPOINT__`/`__SDK_VERSION__` are build-time constants substituted\n// by the bundler (see tsup/vitest `define`). Under this package's test config\n// (vitest.config.ts) they're always statically defined to a truthy string, so\n// the `|| default` fallback below can't be exercised by any test — it only\n// matters for a build that omits the define entirely.\n/* v8 ignore next 3 */\nconst DEFAULT_ENDPOINT =\n (typeof __EVENTRA_ENDPOINT__ !== \"undefined\" && __EVENTRA_ENDPOINT__) ||\n \"https://api.eventra.dev/api/v1/ingest/batch\";\n/* v8 ignore next 2 */\nconst SDK_VERSION =\n (typeof __SDK_VERSION__ !== \"undefined\" && __SDK_VERSION__) || \"0.0.0-dev\";\n\nconst LEADER_KEY = \"__eventra_leader__\";\nconst LEADER_TTL_MS = 4000;\nconst QUEUE_KEY = \"__eventra_q__\";\nconst DIAGNOSTICS_KEY = \"__eventra_d__\";\nconst CHANNEL_NAME = \"eventra-sdk\";\n\nconst MAX_EVENT_NAME = 64;\nconst MAX_USER_ID = 120;\nconst MAX_PROPERTIES_JSON_BYTES = 32_000;\nconst MAX_PROPERTIES_DEPTH = 8;\nconst DEFAULT_MAX_PAYLOAD_BYTES = 60_000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 30_000;\nconst FETCH_TIMEOUT_MS = 5000;\nconst CIRCUIT_FAILURE_THRESHOLD = 5;\nconst CIRCUIT_COOLDOWN_MS = 5000;\nconst CIRCUIT_COOLDOWN_MAX_MS = 60_000;\nconst RETRY_AFTER_MAX_MS = 30_000;\n// How long a burst of track() calls is coalesced into one localStorage write.\n// A crash inside this window (not a normal tab close: pagehide, hidden and\n// shutdown() write immediately) can lose the events tracked in it.\nconst PERSIST_DEBOUNCE_MS = 50;\n// A queued event kept in localStorage longer than this is dropped when it is\n// loaded again. The server only remembers idempotency keys for 30 days, so an\n// event that was delivered during pagehide (whose response is never seen) and\n// is re-sent by a visitor who returns after a long time could otherwise be\n// accepted a second time.\nconst PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000;\n// The most the queue may take in localStorage, in characters of JSON (browsers count the quota of about\n// 5M per site in characters). The storage is shared with the host app, whose own writes must keep working:\n// past this, only the newest events are written, the rest stay in the in-memory queue.\nconst PERSISTED_QUEUE_MAX_CHARS = 1_000_000;\n// the most a keepalive request may carry: Chrome and Firefox refuse more than 64 KiB\nconst KEEPALIVE_MAX_BYTES = 60_000;\n// Keys of events already delivered, remembered so a stale copy in\n// localStorage or from another tab cannot put them back in the queue.\nconst DELIVERED_KEYS_MAX = 10_000;\n\nlet activeInstances = 0;\n\n// ================= RUNTIME =================\ntype Runtime = \"browser\" | \"node\" | \"edge\" | \"serverless\" | \"unknown\";\n\nfunction detectRuntime(): Runtime {\n const g = globalThis as typeof globalThis & {\n EdgeRuntime?: unknown;\n process?: { env?: Record<string, string>; versions?: { node?: string } };\n };\n\n if (g.EdgeRuntime) return \"edge\";\n if (hasBrowserEvents()) return \"browser\";\n if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return \"serverless\";\n if (g.process?.versions?.node) return \"node\";\n\n return \"unknown\";\n}\n\n/**\n * A global `window` alone does not make a browser: React Native defines `window` without `addEventListener`,\n * and Deno 1.x has `window` without `document`. The browser mode needs both event targets.\n */\nfunction hasBrowserEvents(): boolean {\n try {\n return (\n typeof window !== \"undefined\" &&\n window !== null &&\n typeof window.addEventListener === \"function\" &&\n typeof document !== \"undefined\" &&\n document !== null &&\n typeof document.addEventListener === \"function\"\n );\n } catch {\n return false;\n }\n}\n\n/** Adds a listener and returns how to remove it; a target without the API is skipped instead of throwing. */\nfunction listen(target: unknown, type: string, listener: (e: never) => void): () => void {\n const t = target as {\n addEventListener?: (type: string, listener: unknown) => void;\n removeEventListener?: (type: string, listener: unknown) => void;\n } | null | undefined;\n try {\n // only called for the targets the browser runtime was detected by, so this is a last guard\n /* v8 ignore next */\n if (!t || typeof t.addEventListener !== \"function\") return () => undefined;\n t.addEventListener(type, listener);\n } catch {\n return () => undefined;\n }\n return () => {\n try {\n t.removeEventListener?.(type, listener);\n } catch {\n /* nothing to remove */\n }\n };\n}\n\n// ================= HELPERS =================\nfunction uuidV4(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n if (typeof crypto !== \"undefined\" && crypto.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n\n // No Web Crypto (Node 18 without the global, odd runtimes): `track()` must\n // never throw, so fall back to a random v4-shaped id. The key only has to be\n // unique per event for server-side dedup, it is not a secret.\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n let t = Date.now();\n for (let i = 0; i < 6; i++) {\n bytes[i] ^= t & 0xff;\n t = Math.floor(t / 256);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst MAX_TIMER_MS = 2_147_483_647;\n// delivery attempts per batch: a billion would be a way to never give up, not a setting\nconst MAX_RETRIES = 20;\n// the ingest API refuses a batch of more than 500 events with 400, which would drop the whole batch\nconst MAX_BATCH_SIZE = 500;\n\nfunction isUrl(value: string): boolean {\n try {\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction warnOption(name: string, value: unknown, fallback: unknown): void {\n if (typeof console !== \"undefined\") {\n console.warn(`Eventra: option \"${name}\" is invalid (${String(value)}), using ${String(fallback)}`);\n }\n}\n\n/**\n * A numeric option that must be a finite number of at least `min` (and at most `max`). Anything else\n * (NaN, a string, a negative number, Infinity) used to be accepted and silently stop delivery; it now\n * falls back to the default with one warning.\n */\nfunction numberOption(name: string, value: unknown, fallback: number, min: number, max = Number.MAX_SAFE_INTEGER): number {\n if (value === undefined) return fallback;\n if (typeof value === \"number\" && Number.isFinite(value) && value >= min && value <= max) return value;\n warnOption(name, value, fallback);\n return fallback;\n}\n\n/**\n * Runs a callback of the integrator. It must never break the SDK: a throw, or a rejected promise from an\n * async callback, is swallowed (the SDK keeps working and the batch is not retried because of it).\n */\nfunction callSafely<A extends unknown[]>(callback: ((...args: A) => unknown) | undefined, ...args: A): void {\n if (!callback) return;\n try {\n const result = callback(...args);\n if (result && typeof (result as Promise<unknown>).catch === \"function\") {\n (result as Promise<unknown>).catch(() => undefined);\n }\n } catch {\n /* an integrator's callback must not break delivery */\n }\n}\n\n/**\n * Rejects when `signal` aborts (it is fresh, not aborted yet) even if `fetch` itself ignores it: a custom `fetchImpl` that does not honour the\n * signal would otherwise hold the SDK forever, since the request deadline works only through the signal.\n */\nfunction raceAbort<T>(request: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(Object.assign(new Error(\"Eventra: request timed out\"), { name: \"AbortError\" }));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n request.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n\n/** Only the status and headers are used: close the body so the connection is not held by a large unread reply. */\nfunction discardBody(res: Response): void {\n try {\n const closing = res.body?.cancel?.();\n if (closing && typeof closing.catch === \"function\") closing.catch(() => undefined);\n } catch {\n /* a reply without a readable body is fine */\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((r) => setTimeout(r, ms));\n}\n\n// A cut must not leave half of a character outside the basic plane (an emoji, say): the server drops a lone\n// surrogate, so the name or id it stores would differ from what was sent.\nfunction cut(value: string, max: number): string {\n if (value.length <= max) return value;\n const end = value.charCodeAt(max - 1) >= 0xd800 && value.charCodeAt(max - 1) <= 0xdbff ? max - 1 : max;\n return value.slice(0, end);\n}\n\n/** A user id is a string; a number is written out, anything else (null, an object) means no user id. */\nfunction normalizeUserId(value: unknown, max: number): string | undefined {\n if (typeof value === \"bigint\" || (typeof value === \"number\" && Number.isFinite(value))) return cut(String(value), max);\n if (typeof value !== \"string\") return undefined;\n return cut(value, max);\n}\n\n/**\n * Never throws — `track()` is called fire-and-forget from arbitrary call sites,\n * so a malformed name must degrade gracefully instead of crashing the caller.\n * Returns `null` for an empty name (event should be dropped); otherwise trims\n * and truncates to `MAX_EVENT_NAME`, matching the documented behavior.\n */\n// What the server removes from a name before storing it: NUL, CR, LF and half of a surrogate pair. Removed here\n// first, so a name made only of those is dropped on its own instead of reaching the server empty, where it fails the\n// whole batch with a 400. A loop, not a regex: lookbehind would be a syntax error in Safari before 16.4.\nfunction stripUnsafeForName(value: string): string {\n let out = \"\";\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code === 0 || code === 0x0a || code === 0x0d) continue;\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n out += value[i] + value[i + 1];\n i++;\n }\n continue;\n }\n if (code >= 0xdc00 && code <= 0xdfff) continue;\n out += value[i];\n }\n return out;\n}\n\nfunction normalizeEventName(name: string): string | null {\n if (typeof name !== \"string\") return null;\n const trimmed = stripUnsafeForName(name).trim();\n if (!trimmed) return null;\n // trimmed again after the cut: the CLI catalog holds the name the same way, so a name cut in the middle of a\n // space is the same event in both\n return cut(trimmed, MAX_EVENT_NAME).trimEnd();\n}\n\n// `attempt` is the 0-based index of the attempt that just failed, so the first\n// retry waits about `base`, the second about `base * 2`, and so on.\nfunction backoffMs(attempt: number, base: number): number {\n const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);\n const jitter = exp * (0.5 + Math.random() * 0.5);\n return jitter;\n}\n\n// one encoder, created on first use (the global is still checked on every call)\nlet textEncoder: TextEncoder | undefined;\n\nfunction utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n textEncoder ??= new TextEncoder();\n return textEncoder.encode(value).length;\n }\n const g = globalThis as { Buffer?: { byteLength: (s: string, enc: string) => number } };\n if (g.Buffer) {\n return g.Buffer.byteLength(value, \"utf8\");\n }\n return value.length;\n}\n\nfunction isStoredEvent(e: unknown): e is TrackEvent {\n if (e === null || typeof e !== \"object\") return false;\n const ev = e as Partial<TrackEvent>;\n return (\n typeof ev.idempotencyKey === \"string\" &&\n ev.idempotencyKey.length > 0 &&\n ev.idempotencyKey.length <= 100 &&\n typeof ev.name === \"string\" &&\n ev.name.length > 0 &&\n ev.name.length <= MAX_EVENT_NAME &&\n typeof ev.timestamp === \"string\" &&\n (ev.userId === undefined || (typeof ev.userId === \"string\" && ev.userId.length <= MAX_USER_ID)) &&\n (ev.properties === undefined || (ev.properties !== null && typeof ev.properties === \"object\" && !Array.isArray(ev.properties)))\n );\n}\n\nfunction mergeQueues(...queues: TrackEvent[][]): TrackEvent[] {\n const seen = new Set<string>();\n const out: TrackEvent[] = [];\n\n for (const q of queues) {\n for (const e of q) {\n // storage and other tabs are untrusted input: skip anything that is not\n // an event instead of throwing out of the constructor\n if (!isStoredEvent(e)) continue;\n if (seen.has(e.idempotencyKey)) continue;\n seen.add(e.idempotencyKey);\n // an event whose time cannot be read is kept (its age cannot be judged), but it is not sent as it is: the\n // server would refuse it, and a 4xx drops the whole batch it is in\n out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: new Date().toISOString() } : e);\n }\n }\n\n return out;\n}\n\n/** The newest events of the queue that fit in PERSISTED_QUEUE_MAX_CHARS, as a JSON array in queue order. */\nfunction persistedQueueJson(queue: TrackEvent[]): string {\n const parts: string[] = [];\n let chars = 2; // the brackets\n for (let i = queue.length - 1; i >= 0; i--) {\n let json: string;\n try {\n json = JSON.stringify(queue[i]);\n } catch {\n continue;\n }\n const next = chars + json.length + (parts.length ? 1 : 0);\n if (next > PERSISTED_QUEUE_MAX_CHARS) break;\n parts.push(json);\n chars = next;\n }\n return `[${parts.reverse().join(\",\")}]`;\n}\n\n// The depth walk visits shared references again for each path, so a fan-out of shared objects would take\n// time that grows with fanout^depth; past this many visits the properties are too large anyway.\nconst MAX_PROPERTIES_NODES = 50_000;\n\nfunction validateProperties(\n properties: unknown,\n): Record<string, unknown> {\n // Properties are an object of values: a number, a string, a list or null is not (it used to pass through as is).\n if (\n properties === null ||\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values\n Object.prototype.toString.call(properties) !== \"[object Object]\"\n ) {\n throw new Error(\"Eventra: properties must be an object\");\n }\n // Own keys are listed once per object with Object.keys (what JSON.stringify sends). Listing the keys of an\n // object costs time for each of them whatever is used (V8 builds the whole list even for a `for...in` that\n // stops at once), so a huge object is listed only once and refused right after: past the node budget it could\n // never fit in MAX_PROPERTIES_JSON_BYTES anyway.\n const topKeys = Object.keys(properties as object);\n // Nothing to walk or measure for an empty object (the common case), but it is still copied: the caller\n // keeps its own object and may fill it in later.\n if (topKeys.length === 0) return {};\n\n let visited = 0;\n const depth = (obj: unknown, level: number, keys?: string[]): void => {\n if (level > MAX_PROPERTIES_DEPTH) {\n throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);\n }\n if (++visited > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n if (obj === null || typeof obj !== \"object\") return;\n if (Array.isArray(obj)) {\n if (visited + obj.length > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n for (const item of obj) depth(item, level + 1);\n return;\n }\n const own = keys ?? Object.keys(obj);\n if (visited + own.length > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n for (const key of own) depth((obj as Record<string, unknown>)[key], level + 1);\n };\n\n depth(properties, 0, topKeys);\n\n const json = JSON.stringify(properties);\n if (json === undefined || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {\n throw new Error(\n `Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`,\n );\n }\n\n // Snapshot: the caller keeps its own object and may change it (even make it\n // circular) before the event is sent. What was validated is what is sent.\n const copy: unknown = JSON.parse(json);\n // an object with a toJSON() can serialize to something that is not an object\n if (copy === null || typeof copy !== \"object\" || Array.isArray(copy)) {\n throw new Error(\"Eventra: properties must be an object\");\n }\n return copy as Record<string, unknown>;\n}\n\n// Seconds (\"120\") or an HTTP date; anything else (or a past date) is ignored.\n// Capped so one odd header cannot park the queue for a long time.\nfunction parseRetryAfterMs(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n let ms: number;\n if (/^\\d+$/.test(trimmed)) {\n ms = Number(trimmed) * 1000;\n } else {\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n ms = at - Date.now();\n }\n if (!(ms > 0)) return undefined;\n return Math.min(ms, RETRY_AFTER_MAX_MS);\n}\n\ntype PreparedBatch = {\n events: TrackEvent[];\n // counters that travel with this batch (optional envelope metadata)\n diagnostics?: DiagnosticsReport;\n // each event serialized exactly once, joined into the payload by send()\n json: string[];\n bytes: number;\n};\n\nclass RetryableDeliveryError extends Error {\n constructor(\n message = \"retryable delivery error\",\n readonly retryAfterMs?: number,\n readonly reason: FailedReason = \"server_error\",\n ) {\n super(message);\n this.name = \"RetryableDeliveryError\";\n }\n}\n\n// ================= STORAGE =================\nclass Storage {\n private enabled = false;\n\n constructor() {\n try {\n if (typeof localStorage !== \"undefined\") {\n localStorage.setItem(\"__t\", \"1\");\n localStorage.removeItem(\"__t\");\n this.enabled = true;\n }\n } catch {\n /* private mode / blocked storage */\n }\n }\n\n get(key: string): unknown {\n if (!this.enabled) return null;\n try {\n return JSON.parse(localStorage.getItem(key) || \"null\");\n } catch {\n return null;\n }\n }\n\n set(key: string, value: unknown) {\n let json: string;\n try {\n json = JSON.stringify(value);\n } catch {\n // only the diagnostics counters are written here, plain numbers and strings\n /* v8 ignore next */\n return;\n }\n this.setRaw(key, json);\n }\n\n setRaw(key: string, json: string) {\n if (!this.enabled) return;\n try {\n localStorage.setItem(key, json);\n } catch {\n /* quota exceeded */\n }\n }\n\n // Not currently called anywhere in the client — kept for API symmetry with\n // get()/set() on this internal class. No real call site exists to exercise\n // it, and Storage isn't part of the public surface, so a direct call here\n // would only be a reflection-hack test, not real usage.\n /* v8 ignore start */\n remove(key: string) {\n if (!this.enabled) return;\n try {\n localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n }\n /* v8 ignore stop */\n}\n\n// ================= LEADER =================\n/** Whether `localStorage` can be used at all: in a sandboxed iframe even looking at it throws a SecurityError. */\nfunction storageAvailable(): boolean {\n try {\n return typeof localStorage !== \"undefined\" && localStorage !== null;\n } catch {\n return false;\n }\n}\n\nclass Leader {\n private tabId = uuidV4();\n private isLeader = false;\n private heartbeat?: ReturnType<typeof setInterval>;\n private election?: ReturnType<typeof setInterval>;\n private offStorage?: () => void;\n\n constructor(private onLeadershipChange?: (isLeader: boolean) => void) {\n if (!storageAvailable()) {\n this.isLeader = true;\n return;\n }\n\n this.tick();\n\n this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);\n\n // Leader is only constructed in the browser runtime, so `window` exists; listen() still never throws\n /* v8 ignore next */\n this.offStorage = listen(typeof window !== \"undefined\" ? window : undefined, \"storage\", (e: StorageEvent) => {\n if (e.key === LEADER_KEY) this.tick();\n });\n }\n\n private tick() {\n const was = this.isLeader;\n\n if (this.isLeader) {\n if (!this.verifyLease()) {\n this.isLeader = false;\n } else {\n this.renew();\n }\n } else {\n this.isLeader = this.tryAcquire();\n if (this.isLeader) {\n // This branch is only reached when isLeader was just flipped from\n // false to true. Whenever a tick() ends with isLeader false, the\n // check below (`!this.isLeader && this.heartbeat`) always clears\n // `heartbeat` back to undefined in that same tick — so on entry\n // here it can never already be set.\n /* v8 ignore else */\n if (!this.heartbeat) {\n this.heartbeat = setInterval(() => this.renew(), LEADER_TTL_MS / 2);\n }\n }\n }\n\n if (!this.isLeader && this.heartbeat) {\n clearInterval(this.heartbeat);\n this.heartbeat = undefined;\n }\n\n if (was !== this.isLeader) {\n this.onLeadershipChange?.(this.isLeader);\n }\n }\n\n private tryAcquire(): boolean {\n try {\n const now = Date.now();\n const raw = localStorage.getItem(LEADER_KEY);\n if (!raw) {\n this.renew();\n return true;\n }\n const parsed = JSON.parse(raw) as { ts: number; tabId: string };\n if (now - parsed.ts > LEADER_TTL_MS) {\n this.renew();\n return true;\n }\n if (parsed.tabId === this.tabId) {\n this.renew();\n return true;\n }\n return false;\n } catch {\n return true;\n }\n }\n\n private verifyLease(): boolean {\n try {\n const raw = localStorage.getItem(LEADER_KEY);\n if (!raw) return false;\n const parsed = JSON.parse(raw) as { ts: number; tabId: string };\n return (\n parsed.tabId === this.tabId && Date.now() - parsed.ts <= LEADER_TTL_MS\n );\n } catch {\n return false;\n }\n }\n\n private renew() {\n try {\n localStorage.setItem(\n LEADER_KEY,\n JSON.stringify({ ts: Date.now(), tabId: this.tabId }),\n );\n } catch {\n /* ignore */\n }\n }\n\n canSend() {\n return this.isLeader;\n }\n\n destroy() {\n if (this.election) clearInterval(this.election);\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.offStorage?.();\n if (this.isLeader && storageAvailable()) {\n try {\n const raw = localStorage.getItem(LEADER_KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as { tabId: string };\n if (parsed.tabId === this.tabId) {\n localStorage.removeItem(LEADER_KEY);\n }\n }\n } catch {\n /* ignore */\n }\n }\n }\n}\n\n// ================= SDK =================\n// The key is sent with every batch, so a plain http endpoint exposes it on the\n// network. Not an error (an internal http collector is a legitimate setup);\n// loopback is exempt.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\nfunction warnIfInsecureEndpoint(endpoint: string): void {\n if (typeof console === \"undefined\") return;\n try {\n const url = new URL(endpoint);\n if (url.protocol === \"http:\" && !LOOPBACK_HOSTS.has(url.hostname)) {\n console.warn(\n \"Eventra: endpoint uses plain http, the API key is sent unencrypted - use https\",\n );\n }\n } catch {\n /* a relative or malformed endpoint is left for fetch to reject */\n }\n}\n\n// fetch with `redirect: \"error\"` rejects with a TypeError whose cause says so\n// (undici: \"unexpected redirect\"). A browser only reports \"Failed to fetch\", so\n// there a redirect cannot be told from any other network failure.\nfunction isRedirectError(err: unknown): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 3 && current instanceof Error; depth++) {\n if (/redirect/i.test(current.message)) return true;\n current = (current as Error & { cause?: unknown }).cause;\n }\n return false;\n}\n\nexport class Eventra {\n private apiKey: string;\n private endpoint: string;\n private runtime: Runtime;\n private fetch: typeof fetch;\n\n private queue: TrackEvent[] = [];\n private sending: TrackEvent[] | null = null;\n private inFlight = false;\n private destroyed = false;\n private shuttingDown = false;\n\n private maxBatch: number;\n private maxQueue: number;\n private maxPayloadBytes: number;\n private flushInterval: number;\n private retries: number;\n private retryDelay: number;\n private persistQueue: boolean;\n private diagnosticsEnabled: boolean;\n private diagnostics: Diagnostics;\n\n private timer?: ReturnType<typeof setInterval>;\n\n private storage = new Storage();\n private leader: Leader | null = null;\n private channel?: BroadcastChannel;\n private offStorageQueue?: () => void;\n\n private failureCount = 0;\n private warnedRedirect = false;\n private circuitOpenUntil = 0;\n private circuitHalfOpen = false;\n // consecutive times the circuit opened without a success in between; drives\n // the exponential cooldown\n private circuitOpenCount = 0;\n\n private flushPromise: Promise<void> | null = null;\n private persistTimer?: ReturnType<typeof setTimeout>;\n private persistDirty = false;\n private deliveredKeys = new Set<string>();\n // a 429/5xx Retry-After that outlives the last attempt also delays the next\n // flush (timer, size trigger, manual); shutdown() ignores it\n private nextFlushAt = 0;\n // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it\n private shutdownDeadline = 0;\n private shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;\n private shutdownPromise?: Promise<void>;\n // the page is being left (`pagehide`)\n private leaving = false;\n\n private sdkInfo: SdkInfo;\n private options: TrackerOptions;\n\n private exitHandlers: Array<() => void> = [];\n\n constructor(options: TrackerOptions) {\n if (!options || typeof options !== \"object\" || typeof options.apiKey !== \"string\" || !options.apiKey) {\n throw new Error(\"Eventra: apiKey required - new Eventra({ apiKey: \\\"...\\\" })\");\n }\n // the key travels in an HTTP header: a character outside Latin-1 makes every request fail, and nothing says why\n if (/[^\\u0020-\\u00ff]/.test(options.apiKey)) {\n throw new Error(\"Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard\");\n }\n if (options.fetchImpl !== undefined && typeof options.fetchImpl !== \"function\") {\n throw new Error(\"Eventra: fetchImpl must be a function\");\n }\n\n activeInstances++;\n if (activeInstances > 1 && typeof console !== \"undefined\") {\n console.warn(\n \"Eventra: multiple SDK instances detected - duplicate timers and sends are possible\",\n );\n }\n\n try {\n this.options = options;\n this.apiKey = options.apiKey;\n if (options.endpoint !== undefined && (typeof options.endpoint !== \"string\" || !options.endpoint.trim())) {\n warnOption(\"endpoint\", options.endpoint, DEFAULT_ENDPOINT);\n }\n this.endpoint =\n typeof options.endpoint === \"string\" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;\n if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {\n warnOption(\"endpoint\", this.endpoint, DEFAULT_ENDPOINT);\n this.endpoint = DEFAULT_ENDPOINT;\n }\n if (options.multiTabMode !== undefined && options.multiTabMode !== \"independent\" && options.multiTabMode !== \"leader\") {\n warnOption(\"multiTabMode\", options.multiTabMode, \"independent\");\n }\n if (options.diagnostics !== undefined && typeof options.diagnostics !== \"boolean\") {\n warnOption(\"diagnostics\", options.diagnostics, \"true\");\n }\n for (const name of [\"maxBatchSize\", \"maxQueueSize\"] as const) {\n const value = options[name];\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {\n warnOption(name, value, Math.floor(value));\n }\n }\n this.runtime = detectRuntime();\n warnIfInsecureEndpoint(this.endpoint);\n\n this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);\n if (!this.fetch) {\n throw new Error(\"Eventra: fetch not available - provide fetchImpl\");\n }\n\n if (typeof options.maxBatchSize === \"number\" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {\n warnOption(\"maxBatchSize\", options.maxBatchSize, MAX_BATCH_SIZE);\n }\n this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption(\"maxBatchSize\", options.maxBatchSize, 50, 1)));\n this.maxQueue = Math.floor(numberOption(\"maxQueueSize\", options.maxQueueSize, 10000, 1));\n this.maxPayloadBytes = numberOption(\"maxPayloadBytes\", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);\n this.flushInterval = numberOption(\"flushInterval\", options.flushInterval, 2000, 1, MAX_TIMER_MS);\n this.retries = numberOption(\"maxRetries\", options.maxRetries, 3, 0, MAX_RETRIES);\n this.retryDelay = numberOption(\"retryBaseDelayMs\", options.retryBaseDelayMs, 300, 0);\n this.shutdownBudget = numberOption(\"shutdownTimeoutMs\", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);\n // Queued events may carry userId/properties - default on for durability\n // across reloads, but let privacy-sensitive integrators opt out of ever\n // writing that data to localStorage.\n this.persistQueue = options.persistQueue ?? true;\n\n // Counters of what could not be delivered travel with the next successful\n // batch; numbers only, never event content. Off with `diagnostics: false`.\n this.diagnosticsEnabled = options.diagnostics !== false;\n const shared = this.runtime === \"browser\" && this.persistQueue;\n this.diagnostics = new Diagnostics(\n shared ? new SharedStore(this.storage) : new MemoryStore(),\n DIAGNOSTICS_KEY,\n uuidV4,\n shared ? () => this.scheduleDiagnosticsSync() : undefined,\n );\n\n this.sdkInfo = {\n name: SDK_NAME,\n version: SDK_VERSION,\n runtime: this.runtime,\n };\n\n if (this.runtime === \"browser\") {\n if (this.persistQueue) {\n this.loadAndMergeQueue();\n }\n this.setupQueueSync();\n }\n\n if (this.runtime === \"browser\" && options.multiTabMode === \"leader\") {\n this.leader = new Leader((isLeader) => {\n if (isLeader) void this.flushNow(false);\n });\n }\n\n if (!options.disableTimer) {\n this.startTimer();\n }\n\n if (this.runtime === \"browser\") {\n this.setupBrowserExit();\n }\n\n if (options.autoFlushOnExit !== false && this.runtime !== \"browser\") {\n this.setupProcessExit();\n }\n\n // the key must not show in `console.log(tracker)`, `util.inspect` or `JSON.stringify(tracker)`\n Object.defineProperty(this, \"apiKey\", { enumerable: false });\n Object.defineProperty(this, \"options\", { enumerable: false });\n } catch (error) {\n // a constructor that fails must leave nothing behind: not a counted instance, not an open channel,\n // not a timer or a listener (a BroadcastChannel keeps a Node process alive for good)\n this.destroyed = true;\n activeInstances = Math.max(0, activeInstances - 1);\n for (const undo of [\n () => clearInterval(this.timer),\n () => this.leader?.destroy(),\n () => this.channel?.close(),\n () => this.exitHandlers.forEach((undoHandler) => undoHandler()),\n ]) {\n try {\n undo();\n } catch {\n /* nothing more to undo */\n }\n }\n throw error;\n }\n }\n\n track(name: string, options?: TrackOptions) {\n // `track()` is called fire-and-forget from anywhere: nothing it meets (a userId getter that throws, a\n // crypto that throws) may come out of it\n try {\n this.trackEvent(name, options);\n } catch {\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n }\n }\n\n private trackEvent(name: string, options?: TrackOptions) {\n if (this.destroyed || this.shuttingDown) return;\n\n const eventName = normalizeEventName(name);\n if (eventName === null) {\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n let properties: Record<string, unknown>;\n try {\n properties = validateProperties(options?.properties ?? {});\n } catch {\n // Oversized/too-deep properties can't be safely truncated — drop the\n // event instead of throwing out of a fire-and-forget call site.\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n if (this.queue.length >= this.maxQueue) {\n this.recordDiagnostic(\"queue_full\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n const event: TrackEvent = {\n idempotencyKey: uuidV4(),\n name: eventName,\n userId: normalizeUserId(options?.userId, MAX_USER_ID),\n properties,\n timestamp: new Date().toISOString(),\n };\n\n this.queue.push(event);\n\n if (this.runtime === \"browser\") {\n this.schedulePersist();\n this.broadcast({ type: \"queue-add\", events: [event] });\n }\n\n // fire-and-forget triggers start a flush when none is running; one that is running picks the new event up\n // itself (a flush() of the app, by contrast, waits for it and then sends what is left)\n if (this.queue.length >= this.maxBatch) {\n void this.flushNow(false);\n }\n\n if (this.runtime === \"serverless\") {\n void this.flushNow(false);\n }\n }\n\n async flush(): Promise<void> {\n // A flush already running (timer, size trigger, serverless auto-flush) must\n // be awaited, otherwise `await flush()` resolves while events are in flight\n // and a serverless handler can freeze before they are delivered.\n if (this.flushPromise) await this.flushPromise.catch(() => undefined);\n return this.flushNow(false);\n }\n\n // `force` skips only the Retry-After delay (the last chance at shutdown);\n // the circuit breaker still applies\n private async flushNow(force: boolean): Promise<void> {\n if (this.inFlight || this.destroyed) return;\n if (!this.queue.length && !this.sending?.length) return;\n if (!force && Date.now() < this.nextFlushAt) return;\n\n if (this.leader && !this.leader.canSend()) return;\n\n const now = Date.now();\n if (now < this.circuitOpenUntil) return;\n\n if (this.circuitOpenUntil > 0 && now >= this.circuitOpenUntil) {\n this.circuitHalfOpen = true;\n this.circuitOpenUntil = 0;\n }\n\n this.inFlight = true;\n\n const run = this.runFlush();\n this.flushPromise = run;\n\n try {\n await run;\n } finally {\n this.flushPromise = null;\n }\n }\n\n private async runFlush(): Promise<void> {\n try {\n while (this.queue.length > 0 && !this.destroyed) {\n const report = this.diagnosticsEnabled\n ? this.diagnostics.claim(this.queue.length, SDK_VERSION)\n : null;\n const batch = this.buildBatch(report);\n if (!batch.events.length) break;\n\n this.sending = batch.events;\n\n try {\n const accepted = await this.send(batch);\n // acknowledged only by a 2xx for the batch that carried the report\n if (accepted && batch.diagnostics) {\n this.diagnostics.ack(batch.diagnostics.reportId);\n }\n this.removeDelivered(batch.events);\n this.nextFlushAt = 0;\n this.failureCount = 0;\n this.circuitHalfOpen = false;\n this.circuitOpenCount = 0;\n } catch (err) {\n if (err instanceof RetryableDeliveryError) {\n this.recordDiagnostic(err.reason);\n if (err.retryAfterMs) {\n this.nextFlushAt = Date.now() + err.retryAfterMs;\n }\n this.failureCount++;\n if (this.circuitHalfOpen || this.failureCount >= CIRCUIT_FAILURE_THRESHOLD) {\n this.recordDiagnostic(\"circuit_open\");\n // Exponential cooldown, capped. A failed half-open probe counts\n // as another opening, so an outage is probed less and less often.\n const cooldown = Math.min(\n CIRCUIT_COOLDOWN_MAX_MS,\n CIRCUIT_COOLDOWN_MS * 2 ** this.circuitOpenCount,\n );\n this.circuitOpenCount++;\n this.circuitOpenUntil =\n Date.now() + Math.max(cooldown, err.retryAfterMs ?? 0);\n this.circuitHalfOpen = false;\n }\n break;\n }\n break;\n } finally {\n this.sending = null;\n }\n\n // Reachable only after a *successful* send() (the catch above always\n // `break`s immediately whenever circuitOpenUntil is set to a future\n // value). flush() already returned early at the top if\n // `now < circuitOpenUntil`, so by the time execution gets here\n // circuitOpenUntil can only be <= that earlier `now` — never in the\n // future. Defense-in-depth against a future refactor reordering the\n // checks above, not currently reachable.\n /* v8 ignore next */\n if (this.circuitOpenUntil > Date.now()) break;\n }\n } finally {\n this.inFlight = false;\n }\n }\n\n /**\n * Flush pending events, then tear down timers and listeners. Gives up after\n * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot\n * hold a SIGTERM shutdown past a typical grace period.\n */\n shutdown(): Promise<void> {\n // a second call (the app's own, after a signal handler started it) waits for the first instead of\n // returning at once, so `await shutdown()` followed by `process.exit()` does not lose the queue\n this.shutdownPromise ??= this.runShutdown();\n return this.shutdownPromise;\n }\n\n private async runShutdown(): Promise<void> {\n this.shuttingDown = true;\n\n const budget = this.shutdownBudget;\n this.shutdownDeadline = Date.now() + Math.max(0, budget);\n\n let budgetTimer: ReturnType<typeof setTimeout> | undefined;\n const outOfTime = new Promise<void>((resolve) => {\n budgetTimer = setTimeout(resolve, Math.max(0, budget));\n (budgetTimer as { unref?: () => void }).unref?.();\n });\n\n try {\n await Promise.race([this.flushEverything(), outOfTime]);\n } finally {\n clearTimeout(budgetTimer);\n this.destroy();\n }\n }\n\n private async flushEverything(): Promise<void> {\n // A flush may already be running (timer, size trigger): flush() would\n // return immediately and destroy() would drop what is still queued, so\n // let it finish and then send whatever is left.\n if (this.flushPromise) {\n await this.flushPromise;\n }\n await this.flushNow(true);\n }\n\n destroy() {\n if (this.destroyed) return;\n this.destroyed = true;\n activeInstances = Math.max(0, activeInstances - 1);\n\n if (this.timer) clearInterval(this.timer);\n\n // write any pending queue state before the listeners go away\n this.persistNow();\n\n this.leader?.destroy();\n\n if (this.channel) {\n try {\n this.channel.close();\n } catch {\n /* a channel that cannot be closed must not skip the rest of the teardown */\n }\n this.channel = undefined;\n }\n\n this.offStorageQueue?.();\n\n for (const off of this.exitHandlers) {\n off();\n }\n }\n\n private buildBatch(report: DiagnosticsReport | null): PreparedBatch {\n const events: TrackEvent[] = [];\n const json: string[] = [];\n const sentAt = new Date().toISOString();\n // size of the envelope with no events, `[]` included; every event then adds\n // its own bytes plus one comma between neighbours (equal to stringifying the\n // whole envelope, without redoing it for every candidate)\n const envelopeBytes = (withReport: boolean) =>\n utf8ByteLength(\n JSON.stringify({\n sentAt,\n sdk: this.sdkInfo,\n ...(withReport && report ? { diagnostics: report } : {}),\n events: [],\n }),\n );\n let withReport = report !== null;\n let bytes = envelopeBytes(withReport);\n let index = 0;\n\n while (index < this.queue.length && events.length < this.maxBatch) {\n const event = this.queue[index];\n let eventJson: string;\n try {\n eventJson = JSON.stringify(event);\n } catch {\n // cannot be serialized, so it can never be sent: drop it, do not let it\n // wedge the queue\n this.dropPoisonEvent(event);\n continue;\n }\n const total = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);\n\n if (total > this.maxPayloadBytes) {\n if (events.length === 0) {\n if (withReport) {\n // the report itself may be what does not fit: send this batch\n // without it (it stays pending) before judging the event\n withReport = false;\n bytes = envelopeBytes(false);\n continue;\n }\n // removed from this.queue, so `index` now points at the next event;\n // the following event may be small enough to carry the report\n this.dropPoisonEvent(event);\n withReport = report !== null;\n bytes = envelopeBytes(withReport);\n continue;\n }\n break;\n }\n\n events.push(event);\n json.push(eventJson);\n bytes = total;\n index++;\n }\n\n return {\n events,\n json,\n bytes,\n diagnostics: withReport && report ? report : undefined,\n };\n }\n\n private dropPoisonEvent(event: TrackEvent) {\n this.recordDiagnostic(\"too_large\");\n this.removeDelivered([event]);\n callSafely(this.options.onEventsDropped, 1);\n callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });\n }\n\n private removeDelivered(batch: TrackEvent[]) {\n const keys = new Set(batch.map((e) => e.idempotencyKey));\n // a delivered batch is nearly always the start of the queue: cut it off instead of testing every event\n // (filtering each batch made draining a large queue quadratic: 300,000 events blocked the loop for minutes)\n const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);\n this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));\n\n if (this.runtime === \"browser\") {\n this.rememberDelivered(keys);\n this.schedulePersist();\n this.broadcast({ type: \"delivered\", keys: [...keys] });\n }\n }\n\n // Resolves true only when the server answered 2xx for a payload that\n // carried the diagnostics report (the only case that acknowledges it).\n private async send(batch: PreparedBatch): Promise<boolean> {\n const { events } = batch;\n let carriesDiagnostics = batch.diagnostics !== undefined;\n // same shape and key order as JSON.stringify({ sentAt, sdk, events }), with\n // every event serialized once, in buildBatch()\n const buildPayload = (withDiagnostics: boolean) => {\n const head = JSON.stringify({\n sentAt: new Date().toISOString(),\n sdk: this.sdkInfo,\n ...(withDiagnostics && batch.diagnostics\n ? { diagnostics: batch.diagnostics }\n : {}),\n });\n return `${head.slice(0, -1)},\"events\":[${batch.json.join(\",\")}]}`;\n };\n let payload = buildPayload(carriesDiagnostics);\n\n const payloadBytes = batch.bytes;\n /* v8 ignore start */\n // buildBatch() only ever returns a batch whose size already fits within\n // maxPayloadBytes, and nothing mutates `events` or maxPayloadBytes between\n // that check and this one, so this re-check can't trip in practice.\n // Defense-in-depth, not dead logic to be deleted.\n if (payloadBytes > this.maxPayloadBytes) {\n this.dropPoisonEvents(events);\n return false;\n }\n /* v8 ignore stop */\n\n const useKeepalive =\n this.runtime === \"browser\" &&\n typeof document !== \"undefined\" &&\n (document.visibilityState === \"hidden\" || this.leaving) &&\n // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows\n payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);\n\n // A half-open breaker lets exactly one request through as a probe: no\n // retries while we don't know yet whether the endpoint is back.\n const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);\n // a server that rejects the unknown `diagnostics` field answers 400/422;\n // the batch is then sent once more without it\n let strippedDiagnostics = false;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const controller = new AbortController();\n const attemptTimeoutMs =\n this.shutdownDeadline > 0\n ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now()))\n : FETCH_TIMEOUT_MS;\n const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);\n\n try {\n const res = await raceAbort(\n this.fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n },\n body: payload,\n signal: controller.signal,\n keepalive: useKeepalive,\n // never follow a redirect: x-api-key is a custom header, so fetch\n // would forward it to wherever a compromised or misconfigured\n // endpoint points\n redirect: \"error\",\n }),\n controller.signal,\n );\n discardBody(res);\n\n if (res.status === 429 || res.status >= 500) {\n throw new RetryableDeliveryError(\n \"retryable delivery error\",\n parseRetryAfterMs(res.headers?.get?.(\"retry-after\")),\n res.status === 429 ? \"rate_limited\" : \"server_error\",\n );\n }\n\n if (res.status >= 400 && res.status < 500) {\n if (carriesDiagnostics && (res.status === 400 || res.status === 422)) {\n // maybe an older server that does not know the field: events must\n // not be lost over it, so try again without it (not a new attempt)\n carriesDiagnostics = false;\n strippedDiagnostics = true;\n payload = buildPayload(false);\n attempt--;\n continue;\n }\n this.recordDiagnostic(\"rejected\", events.length);\n // a copy: a callback that empties the array it is given must not empty the batch the SDK is working on\n callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });\n this.removeDelivered(events);\n return false;\n }\n\n if (!res.ok) {\n throw new RetryableDeliveryError();\n }\n\n if (strippedDiagnostics) {\n // accepted only once the field was left out: this server does not\n // take it, so stop sending it (the counters are kept, not reported)\n this.diagnosticsEnabled = false;\n return false;\n }\n\n return carriesDiagnostics;\n } catch (err) {\n if (!this.warnedRedirect && isRedirectError(err) && typeof console !== \"undefined\") {\n this.warnedRedirect = true;\n console.warn(\n \"Eventra: the endpoint answered with a redirect. It is not followed, so the API key is not forwarded, and events stay queued - check the endpoint URL (for example http instead of https)\",\n );\n }\n const isLast = attempt >= maxAttempts - 1;\n const retryAfter =\n err instanceof RetryableDeliveryError ? err.retryAfterMs : undefined;\n const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);\n // during shutdown there is no time left for another sleep + attempt\n const outOfBudget =\n this.shutdownDeadline > 0 && Date.now() + wait >= this.shutdownDeadline;\n\n if (isLast || outOfBudget) {\n throw err instanceof RetryableDeliveryError\n ? err\n : new RetryableDeliveryError(\"retryable delivery error\", undefined, \"network\");\n }\n\n await sleep(wait);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n // unreachable: the last attempt either returns or throws\n /* v8 ignore next */\n return false;\n }\n\n // Only caller is the defensive re-check in send() above, which is itself\n // unreachable in practice (see comment there) — see the same file's\n // ignore rationale. Kept for when that check trips defensively.\n /* v8 ignore start */\n private dropPoisonEvents(events: TrackEvent[]) {\n for (const event of events) {\n this.dropPoisonEvent(event);\n }\n }\n /* v8 ignore stop */\n\n private recordDiagnostic(reason: Parameters<Diagnostics[\"record\"]>[0], n = 1) {\n if (this.diagnosticsEnabled) this.diagnostics.record(reason, n);\n }\n\n // counters reach localStorage on the same debounce as the queue\n private scheduleDiagnosticsSync() {\n if (this.persistTimer !== undefined) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = undefined;\n this.persistNow();\n }, PERSIST_DEBOUNCE_MS);\n }\n\n private loadAndMergeQueue() {\n const remote = this.storage.get(QUEUE_KEY);\n if (Array.isArray(remote)) {\n const fresh = this.withoutExpired(remote as TrackEvent[]);\n // rewrite storage without what was dropped, so it does not come back\n if (fresh.length !== remote.length) this.persistDirty = true;\n this.queue = mergeQueues(this.queue, this.withoutDelivered(fresh));\n }\n this.queue = this.trimQueue();\n }\n\n // events whose timestamp is unreadable are kept: their age cannot be judged\n private withoutExpired(events: TrackEvent[]): TrackEvent[] {\n const oldest = Date.now() - PERSISTED_EVENT_MAX_AGE_MS;\n return events.filter((e) => {\n const at = Date.parse(e?.timestamp);\n return Number.isNaN(at) || at >= oldest;\n });\n }\n\n private withoutDelivered(events: TrackEvent[]): TrackEvent[] {\n if (!this.deliveredKeys.size) return events;\n return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));\n }\n\n private rememberDelivered(keys: Iterable<string>) {\n for (const key of keys) this.deliveredKeys.add(key);\n // Set iterates in insertion order, so this drops the oldest keys first\n for (const key of this.deliveredKeys) {\n if (this.deliveredKeys.size <= DELIVERED_KEYS_MAX) break;\n this.deliveredKeys.delete(key);\n }\n }\n\n // Burst of track() calls = one write. Reading, merging and rewriting the\n // whole queue on every call made each call cost O(queue size).\n private schedulePersist() {\n if (!this.persistQueue) return;\n this.persistDirty = true;\n if (this.persistTimer !== undefined) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = undefined;\n this.persistNow();\n }, PERSIST_DEBOUNCE_MS);\n }\n\n // Immediate write of the pending state (pagehide, tab hidden, destroy).\n // Merges what other tabs wrote first, so concurrent tabs never overwrite\n // each other's events; delivered events are filtered out so they stay gone.\n private persistNow() {\n if (this.persistTimer !== undefined) {\n clearTimeout(this.persistTimer);\n this.persistTimer = undefined;\n }\n // counters first: they are written even when the queue itself is not dirty\n this.diagnostics.sync();\n if (!this.persistQueue || !this.persistDirty) return;\n this.persistDirty = false;\n\n const remote = this.storage.get(QUEUE_KEY);\n const merged = mergeQueues(\n Array.isArray(remote)\n ? this.withoutDelivered(this.withoutExpired(remote as TrackEvent[]))\n : [],\n this.queue,\n );\n this.queue = this.trimQueue(merged);\n this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));\n }\n\n private trimQueue(queue: TrackEvent[] = this.queue): TrackEvent[] {\n if (queue.length <= this.maxQueue) return queue;\n const dropped = queue.length - this.maxQueue;\n this.recordDiagnostic(\"queue_full\", dropped);\n callSafely(this.options.onEventsDropped, dropped);\n return queue.slice(-this.maxQueue);\n }\n\n // Sends only what changed (a new event, or the keys just delivered) instead\n // of structured-cloning the whole queue on every call.\n private broadcast(message: unknown) {\n try {\n this.channel?.postMessage(message);\n } catch {\n /* ignore */\n }\n }\n\n private setupQueueSync() {\n if (typeof BroadcastChannel !== \"undefined\") {\n try {\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n } catch {\n // a browser or a sandbox that refuses the channel: tabs just do not share events\n this.channel = undefined;\n }\n }\n if (this.channel) {\n this.channel.onmessage = (e: MessageEvent) => {\n const data = e.data;\n\n if (data?.type === \"delivered\" && Array.isArray(data.keys)) {\n const keys = new Set<string>(data.keys as string[]);\n this.rememberDelivered(keys);\n this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));\n return;\n }\n\n // \"queue-add\" is the delta a tab sends for one new event; \"queue-sync\"\n // carries a whole queue and is still accepted from older SDK versions\n if (\n (data?.type !== \"queue-add\" && data?.type !== \"queue-sync\") ||\n !Array.isArray(data.events)\n ) {\n return;\n }\n this.queue = mergeQueues(this.queue, this.withoutDelivered(data.events as TrackEvent[]));\n this.queue = this.trimQueue();\n };\n }\n\n if (this.persistQueue && typeof window !== \"undefined\") {\n this.offStorageQueue = listen(window, \"storage\", (e: StorageEvent) => {\n if (e.key !== QUEUE_KEY) return;\n this.loadAndMergeQueue();\n });\n }\n }\n\n private startTimer() {\n this.timer = setInterval(() => {\n void this.flushNow(false);\n }, this.flushInterval);\n // a library timer must not keep a Node process alive on its own\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n private setupBrowserExit() {\n const handler = () => {\n if (document.visibilityState === \"hidden\") {\n this.persistNow();\n void this.flush();\n }\n };\n\n const pageHide = () => {\n // `pagehide` can fire while the page still counts as visible (a navigation, a closed tab): the request\n // must outlive the page all the same\n this.leaving = true;\n this.persistNow();\n if (this.inFlight) {\n // flush() would wait for the request in flight, which the browser cancels on unload, so the keepalive\n // send would never start\n this.sendOnLeave();\n } else {\n void this.flush();\n }\n };\n\n // a page restored from the back/forward cache is not being left any more: later sends are normal requests\n const pageShow = () => {\n this.leaving = false;\n };\n\n // `visibilitychange` only ever fires on `document`, never on `window` -\n // `pagehide` and `pageshow` are the opposite, `window`-only events.\n const offs = [\n listen(document, \"visibilitychange\", handler),\n listen(window, \"pagehide\", pageHide),\n listen(window, \"pageshow\", pageShow),\n ];\n\n this.exitHandlers.push(() => offs.forEach((off) => off()));\n }\n\n /**\n * The page is being left while a request is in flight: send what is queued at once with keepalive, without\n * waiting for that request. The events of the batch in flight go along too (after the others, as far as the\n * keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server\n * drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.\n */\n private sendOnLeave() {\n // a tab that lost leadership while its request was in flight leaves the sending to the new leader\n if (this.leader && !this.leader.canSend()) return;\n\n // `sending` is set whenever a flush is in flight and the page can see it\n /* v8 ignore next */\n const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));\n const candidates = [\n ...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),\n ...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey)),\n ];\n\n const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);\n const sentAt = new Date().toISOString();\n let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));\n const events: TrackEvent[] = [];\n const json: string[] = [];\n for (const event of candidates) {\n // the server's limit per batch; the keepalive size limit is normally reached first\n /* v8 ignore next */\n if (events.length >= MAX_BATCH_SIZE) break;\n let eventJson: string;\n try {\n eventJson = JSON.stringify(event);\n } catch {\n continue;\n }\n const total = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);\n // a smaller event further on may still fit\n if (total > limit) continue;\n events.push(event);\n json.push(eventJson);\n bytes = total;\n }\n if (!events.length) return;\n\n const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });\n const body = `${head.slice(0, -1)},\"events\":[${json.join(\",\")}]}`;\n try {\n const request = this.fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n },\n body,\n keepalive: true,\n redirect: \"error\",\n });\n Promise.resolve(request).then(\n (res) => {\n discardBody(res);\n // seen only when the page stays (a bfcache restore): what was accepted is not sent again\n if (res.ok && !this.destroyed) this.removeDelivered(events);\n },\n () => undefined,\n );\n } catch {\n /* the events stay queued (and in localStorage) for the next visit */\n }\n }\n\n private setupProcessExit() {\n type Proc = {\n pid?: number;\n on: (event: string, listener: (...args: unknown[]) => void) => void;\n once: (event: string, listener: (...args: unknown[]) => void) => void;\n prependOnceListener?: (event: string, listener: (...args: unknown[]) => void) => void;\n exit?: (code?: number) => void;\n off?: (event: string, listener: (...args: unknown[]) => void) => void;\n listenerCount?: (event: string) => number;\n kill?: (pid: number, signal: string) => void;\n };\n const proc = (globalThis as { process?: Proc }).process;\n if (!proc?.on) return;\n\n // Registering any handler cancels Node's default \"exit on SIGINT/SIGTERM\". So by default the SDK behaves\n // like that default: when nobody else listens to the signal, it flushes (bounded by shutdownTimeoutMs) and\n // then re-raises the signal so the process ends as it would have without the SDK. When the app has its own\n // listener, the SDK only flushes and the app owns its shutdown. Whether others listen is decided when the\n // signal arrives, not after the flush: an app that uses `process.once` or NestJS shutdown hooks removes its\n // listener while it shuts down, and a re-raise then would cut that shutdown off. The SDK's own listener is\n // put first, so at that moment every other listener is still registered. `exitOnSignal: false` turns the\n // re-raise off (flush only).\n const exitOnSignal = this.options.exitOnSignal !== false;\n const onSignal = (signal: string) => () => {\n // a once-listener has removed itself already when emitted; removing it here too makes the count below\n // everyone else whichever way this handler was called\n proc.off?.(signal, handlers[signal]);\n const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;\n void this.shutdown().finally(() => {\n if (!exitOnSignal || othersAtSignal) return;\n const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;\n if (othersListening) return;\n if (proc.pid === 1 && proc.exit) {\n // PID 1 (a container without an init) ignores a signal it has no handler for, so a re-raise would do\n // nothing: exit with the code the signal would have given\n proc.exit(128 + (signal === \"SIGINT\" ? 2 : 15));\n return;\n }\n if (proc.kill && proc.pid !== undefined) {\n proc.kill(proc.pid, signal);\n }\n });\n };\n // first in line, so the check above still sees every other listener (see the note above)\n const listenFirst = (event: string, listener: () => void) =>\n typeof proc.prependOnceListener === \"function\"\n ? proc.prependOnceListener(event, listener)\n : proc.once(event, listener);\n const handlers: Record<string, () => void> = {\n SIGINT: onSignal(\"SIGINT\"),\n SIGTERM: onSignal(\"SIGTERM\"),\n };\n\n // A script that tracks something and then simply ends: the (unref'd) timer\n // no longer keeps it alive, so deliver what is queued before it exits. The\n // pending fetch keeps the loop alive until it settles.\n const listenAgain = () => {\n if (!this.destroyed) proc.once(\"beforeExit\", onBeforeExit);\n };\n const onBeforeExit = () => {\n if (!this.queue.length) {\n // `beforeExit` fires each time the loop drains, and a script can track more events after this\n // one: keep listening\n listenAgain();\n return;\n }\n // The process is ending: bound the flush like shutdown() does, so a hanging server or a long\n // Retry-After cannot keep it alive for a minute. The deadline is lifted again afterwards in case\n // the app schedules more work after the loop drained.\n const own = this.shutdownDeadline === 0;\n if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;\n void this.flush().finally(() => {\n // the limit stays while events are still queued: a flush the timer starts later must not run without it\n // and hold the process while the server keeps failing\n if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;\n // Only after a flush that delivered everything. When events are still queued the server is not\n // taking them: trying again on every drain would keep the process alive for as long as it fails.\n if (!this.queue.length) listenAgain();\n });\n };\n\n listenFirst(\"SIGINT\", handlers.SIGINT);\n listenFirst(\"SIGTERM\", handlers.SIGTERM);\n proc.once(\"beforeExit\", onBeforeExit);\n\n this.exitHandlers.push(() => {\n proc.off?.(\"SIGINT\", handlers.SIGINT);\n proc.off?.(\"SIGTERM\", handlers.SIGTERM);\n proc.off?.(\"beforeExit\", onBeforeExit);\n });\n }\n}\n"],"mappings":";AA4BA,IAAM,kBAAuC,oBAAI,IAAI;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,iBAAsC,oBAAI,IAAI;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,YAAY;AAuCX,IAAM,cAAN,MAA8C;AAAA,EAA9C;AACL,SAAQ,OAAO,oBAAI,IAAqB;AAAA;AAAA,EAExC,IAAI,KAAsB;AACxB,WAAO,KAAK,KAAK,IAAI,GAAG,KAAK;AAAA,EAC/B;AAAA,EAEA,IAAI,KAAa,OAAgB;AAC/B,SAAK,KAAK,IAAI,KAAK,KAAK;AAAA,EAC1B;AACF;AAIO,IAAM,cAAN,MAA8C;AAAA,EAGnD,YAA6B,SAA2B;AAA3B;AAF7B,SAAQ,SAAS,IAAI,YAAY;AAAA,EAEwB;AAAA,EAEzD,IAAI,KAAsB;AACxB,WAAO,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,OAAO,IAAI,GAAG;AAAA,EACrD;AAAA,EAEA,IAAI,KAAa,OAAgB;AAC/B,SAAK,OAAO,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IAC3D;AACA,UAAM,eAAe,MAAM;AACzB,UAAI,CAAC,KAAK,MAAM,QAAQ;AAGtB,oBAAY;AACZ;AAAA,MACF;AAIA,YAAM,MAAM,KAAK,qBAAqB;AACtC,UAAI,IAAK,MAAK,mBAAmB,KAAK,IAAI,IAAI,KAAK;AACnD,WAAK,KAAK,MAAM,EAAE,QAAQ,MAAM;AAG9B,YAAI,OAAO,CAAC,KAAK,gBAAgB,CAAC,KAAK,MAAM,OAAQ,MAAK,mBAAmB;AAG7E,YAAI,CAAC,KAAK,MAAM,OAAQ,aAAY;AAAA,MACtC,CAAC;AAAA,IACH;AAEA,gBAAY,UAAU,SAAS,MAAM;AACrC,gBAAY,WAAW,SAAS,OAAO;AACvC,SAAK,KAAK,cAAc,YAAY;AAEpC,SAAK,aAAa,KAAK,MAAM;AAC3B,WAAK,MAAM,UAAU,SAAS,MAAM;AACpC,WAAK,MAAM,WAAW,SAAS,OAAO;AACtC,WAAK,MAAM,cAAc,YAAY;AAAA,IACvC,CAAC;AAAA,EACH;AACF;","names":["reportId","bytes","hex","withReport","total"]}
|
|
1
|
+
{"version":3,"sources":["../src/diagnostics.ts","../src/client.ts"],"sourcesContent":["// Delivery diagnostics: counters of what the SDK itself could not deliver, so\n// the dashboard can say how many events never arrived. Numbers only - never\n// event names, user ids or properties.\n//\n// Counters accumulate locally, are moved into a \"pending\" report right before\n// they are attached to a batch, and are removed only after the server answered\n// 2xx for that very batch. A failed send keeps the pending report, which is\n// re-sent with the same `reportId` (the server counts a reportId once), so a\n// retry or a lost response never double reports and a failure never loses it.\n\n// events the SDK gave up on\nexport type DroppedReason =\n | \"queue_full\" // queue overflow\n | \"invalid_event\" // empty name or unusable properties\n | \"too_large\" // a single event above the payload limit\n | \"rejected\"; // the server answered 4xx (not 429)\n\n// failed send attempts: one per batch that could not be delivered after all\n// retries (the events stay queued). `failedTotal` counts these; `circuit_open`\n// is listed by reason only and is not added to the total.\nexport type FailedReason =\n | \"network\" // blocked, offline, DNS, timeout\n | \"server_error\" // 5xx\n | \"rate_limited\" // 429\n | \"circuit_open\"; // the circuit breaker opened\n\nexport type DiagnosticsReason = DroppedReason | FailedReason;\n\nconst DROPPED_REASONS: ReadonlySet<string> = new Set([\n \"queue_full\",\n \"invalid_event\",\n \"too_large\",\n \"rejected\",\n]);\nconst FAILED_REASONS: ReadonlySet<string> = new Set([\n \"network\",\n \"server_error\",\n \"rate_limited\",\n \"circuit_open\",\n]);\n\n// a counter can never exceed this, so the payload stays tiny and numeric\nconst COUNT_MAX = 1_000_000_000;\n\nexport interface DiagnosticsReport {\n /** one id per report, the server counts it once */\n reportId: string;\n /** when the oldest counted problem happened (ISO) */\n since: string;\n droppedTotal: number;\n /** failed send attempts (batches that failed after retries), not events */\n failedTotal: number;\n byReason: Record<string, number>;\n /** events waiting in the queue when the report was built */\n queued: number;\n sdkVersion: string;\n}\n\ninterface Counts {\n dropped: number;\n failed: number;\n byReason: Record<string, number>;\n since?: string;\n}\n\ninterface PendingReport {\n reportId: string;\n counts: Counts;\n}\n\ninterface StoredRecord {\n counts: Counts;\n pending?: PendingReport;\n}\n\nexport interface DiagnosticsStore {\n get(key: string): unknown;\n set(key: string, value: unknown): void;\n}\n\n// used in Node, and in the browser when the queue must not touch localStorage\nexport class MemoryStore implements DiagnosticsStore {\n private data = new Map<string, unknown>();\n\n get(key: string): unknown {\n return this.data.get(key) ?? null;\n }\n\n set(key: string, value: unknown) {\n this.data.set(key, value);\n }\n}\n\n// localStorage first (shared by tabs and surviving a reload), memory as the\n// fallback when storage is blocked (private mode) and so reads nothing back\nexport class SharedStore implements DiagnosticsStore {\n private memory = new MemoryStore();\n\n constructor(private readonly storage: DiagnosticsStore) {}\n\n get(key: string): unknown {\n return this.storage.get(key) ?? this.memory.get(key);\n }\n\n set(key: string, value: unknown) {\n this.memory.set(key, value);\n this.storage.set(key, value);\n }\n}\n\nfunction emptyCounts(): Counts {\n return { dropped: 0, failed: 0, byReason: {} };\n}\n\nfunction isCount(value: unknown): value is number {\n return (\n typeof value === \"number\" &&\n Number.isInteger(value) &&\n value >= 0 &&\n value <= COUNT_MAX\n );\n}\n\nfunction parseCounts(value: unknown): Counts | null {\n if (typeof value !== \"object\" || value === null) return null;\n const v = value as Record<string, unknown>;\n if (!isCount(v.dropped) || !isCount(v.failed)) return null;\n\n const byReason: Record<string, number> = {};\n const raw = v.byReason;\n if (typeof raw === \"object\" && raw !== null) {\n for (const [reason, count] of Object.entries(raw)) {\n if (\n (DROPPED_REASONS.has(reason) || FAILED_REASONS.has(reason)) &&\n isCount(count)\n ) {\n byReason[reason] = count;\n }\n }\n }\n\n const since =\n typeof v.since === \"string\" && !Number.isNaN(Date.parse(v.since))\n ? v.since\n : undefined;\n\n return { dropped: v.dropped, failed: v.failed, byReason, since };\n}\n\n// what is in storage may be stale, hand-edited or from another version: only\n// a well-formed record is used, anything else starts over\nfunction parseRecord(value: unknown): StoredRecord {\n if (typeof value !== \"object\" || value === null) {\n return { counts: emptyCounts() };\n }\n const v = value as Record<string, unknown>;\n const counts = parseCounts(v.counts) ?? emptyCounts();\n\n let pending: PendingReport | undefined;\n const p = v.pending as Record<string, unknown> | undefined;\n if (typeof p === \"object\" && p !== null && typeof p.reportId === \"string\") {\n const pendingCounts = parseCounts(p.counts);\n if (pendingCounts) pending = { reportId: p.reportId, counts: pendingCounts };\n }\n\n return { counts, pending };\n}\n\nfunction total(counts: Counts): number {\n return counts.dropped + counts.failed;\n}\n\nfunction add(into: Counts, from: Counts) {\n into.dropped = Math.min(COUNT_MAX, into.dropped + from.dropped);\n into.failed = Math.min(COUNT_MAX, into.failed + from.failed);\n for (const [reason, count] of Object.entries(from.byReason)) {\n into.byReason[reason] = Math.min(\n COUNT_MAX,\n (into.byReason[reason] ?? 0) + count,\n );\n }\n if (from.since && (!into.since || from.since < into.since)) {\n into.since = from.since;\n }\n}\n\nexport class Diagnostics {\n // not yet merged into the (possibly shared) record\n private local: Counts = emptyCounts();\n private dirty = false;\n\n constructor(\n private readonly store: DiagnosticsStore,\n private readonly key: string,\n private readonly newId: () => string,\n private readonly onChange: () => void = () => {},\n ) {}\n\n record(reason: DiagnosticsReason, n = 1) {\n if (!(n > 0)) return;\n const isDropped = DROPPED_REASONS.has(reason);\n\n if (isDropped) {\n this.local.dropped = Math.min(COUNT_MAX, this.local.dropped + n);\n } else if (reason !== \"circuit_open\") {\n // `circuit_open` is an extra detail of a failure that was already\n // counted, so it appears in byReason only and never in failedTotal\n this.local.failed = Math.min(COUNT_MAX, this.local.failed + n);\n }\n this.local.byReason[reason] = Math.min(\n COUNT_MAX,\n (this.local.byReason[reason] ?? 0) + n,\n );\n this.local.since ??= new Date().toISOString();\n\n this.dirty = true;\n this.onChange();\n }\n\n // writes the local counters into the shared record (debounced by the client,\n // immediate on pagehide/destroy); a no-op when nothing changed\n sync() {\n if (!this.dirty) return;\n const record = this.read();\n add(record.counts, this.local);\n this.local = emptyCounts();\n this.dirty = false;\n this.store.set(this.key, record);\n }\n\n // Moves the counters into a pending report and returns it; an unacknowledged\n // pending report is returned again as it is. null when there is nothing to\n // report or another tab claimed the same counters first.\n claim(queued: number, sdkVersion: string): DiagnosticsReport | null {\n this.dirty = this.dirty || total(this.local) > 0;\n this.sync();\n\n const record = this.read();\n\n if (!record.pending) {\n if (total(record.counts) === 0) return null;\n\n const reportId = this.newId();\n record.pending = { reportId, counts: record.counts };\n record.counts = emptyCounts();\n this.store.set(this.key, record);\n\n // two tabs claiming at the same moment: only the one whose claim is what\n // is stored sends it, the other sends nothing this round\n const stored = this.read();\n if (stored.pending?.reportId !== reportId) return null;\n }\n\n const { reportId, counts } = record.pending;\n return {\n reportId,\n since: counts.since ?? new Date().toISOString(),\n droppedTotal: counts.dropped,\n failedTotal: counts.failed,\n byReason: { ...counts.byReason },\n queued,\n sdkVersion,\n };\n }\n\n // the server accepted the batch the report travelled with\n ack(reportId: string) {\n const record = this.read();\n if (record.pending?.reportId !== reportId) return;\n record.pending = undefined;\n this.store.set(this.key, record);\n }\n\n private read(): StoredRecord {\n return parseRecord(this.store.get(this.key));\n }\n}\n","import { TrackerOptions, TrackEvent, SdkInfo, TrackOptions, EventraScope } from \"./types\";\nimport {\n Diagnostics,\n DiagnosticsReport,\n FailedReason,\n MemoryStore,\n SharedStore,\n} from \"./diagnostics\";\n\ndeclare const __SDK_VERSION__: string | undefined;\ndeclare const __EVENTRA_ENDPOINT__: string | undefined;\n\nconst SDK_NAME = \"@eventra_dev/eventra-sdk\";\n// `__EVENTRA_ENDPOINT__`/`__SDK_VERSION__` are build-time constants substituted\n// by the bundler (see tsup/vitest `define`). Under this package's test config\n// (vitest.config.ts) they're always statically defined to a truthy string, so\n// the `|| default` fallback below can't be exercised by any test — it only\n// matters for a build that omits the define entirely.\n/* v8 ignore next 3 */\nconst DEFAULT_ENDPOINT =\n (typeof __EVENTRA_ENDPOINT__ !== \"undefined\" && __EVENTRA_ENDPOINT__) ||\n \"https://api.eventra.dev/api/v1/ingest/batch\";\n/* v8 ignore next 2 */\nconst SDK_VERSION =\n (typeof __SDK_VERSION__ !== \"undefined\" && __SDK_VERSION__) || \"0.0.0-dev\";\n\nconst LEADER_KEY = \"__eventra_leader__\";\nconst LEADER_TTL_MS = 4000;\nconst QUEUE_KEY = \"__eventra_q__\";\nconst DIAGNOSTICS_KEY = \"__eventra_d__\";\n// the user set by identify(), kept so a reload does not send the first events without it; the key ends with a\n// hash of the API key, so two Eventra projects on one site (a third-party widget, say) never share a user\nconst USER_KEY_PREFIX = \"__eventra_u__\";\nconst CHANNEL_NAME = \"eventra-sdk\";\n\nconst MAX_EVENT_NAME = 64;\nconst MAX_USER_ID = 120;\nconst MAX_PROPERTIES_JSON_BYTES = 32_000;\nconst MAX_PROPERTIES_DEPTH = 8;\nconst DEFAULT_MAX_PAYLOAD_BYTES = 60_000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 30_000;\nconst FETCH_TIMEOUT_MS = 5000;\nconst CIRCUIT_FAILURE_THRESHOLD = 5;\nconst CIRCUIT_COOLDOWN_MS = 5000;\nconst CIRCUIT_COOLDOWN_MAX_MS = 60_000;\nconst RETRY_AFTER_MAX_MS = 30_000;\n// How long a burst of track() calls is coalesced into one localStorage write.\n// A crash inside this window (not a normal tab close: pagehide, hidden and\n// shutdown() write immediately) can lose the events tracked in it.\nconst PERSIST_DEBOUNCE_MS = 50;\n// A queued event kept in localStorage longer than this is dropped when it is\n// loaded again. The server only remembers idempotency keys for 30 days, so an\n// event that was delivered during pagehide (whose response is never seen) and\n// is re-sent by a visitor who returns after a long time could otherwise be\n// accepted a second time.\nconst PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000;\n// The most the queue may take in localStorage, in characters of JSON (browsers count the quota of about\n// 5M per site in characters). The storage is shared with the host app, whose own writes must keep working:\n// past this, only the newest events are written, the rest stay in the in-memory queue.\nconst PERSISTED_QUEUE_MAX_CHARS = 1_000_000;\n// the most a keepalive request may carry: Chrome and Firefox refuse more than 64 KiB\nconst KEEPALIVE_MAX_BYTES = 60_000;\n// Keys of events already delivered, remembered so a stale copy in\n// localStorage or from another tab cannot put them back in the queue.\nconst DELIVERED_KEYS_MAX = 10_000;\n// In the default `independent` mode every tab holds every tab's events (so the events of a tab that closes\n// are not lost). An event another open tab just announced is left to that tab this long: it sends within\n// its flush interval and tells the others it was delivered. Sent by everyone at once, each event went out\n// once per open tab. Events read from storage (an earlier page, a closed tab) are sent at once, as before.\nconst LIVE_TAB_GRACE_MS = 15_000;\nconst LIVE_TAB_KEYS_MAX = 10_000;\n// identifyHint: how many events without a user id, from the start, before the one warning\nconst IDENTIFY_HINT_AFTER = 50;\n\nlet activeInstances = 0;\n\n// ================= RUNTIME =================\ntype Runtime = \"browser\" | \"node\" | \"edge\" | \"serverless\" | \"unknown\";\n\nfunction detectRuntime(): Runtime {\n const g = globalThis as typeof globalThis & {\n EdgeRuntime?: unknown;\n process?: { env?: Record<string, string>; versions?: { node?: string } };\n };\n\n if (g.EdgeRuntime) return \"edge\";\n if (hasBrowserEvents()) return \"browser\";\n if (g.process?.env?.AWS_LAMBDA_FUNCTION_NAME) return \"serverless\";\n if (g.process?.versions?.node) return \"node\";\n\n return \"unknown\";\n}\n\n/**\n * A global `window` alone does not make a browser: React Native defines `window` without `addEventListener`,\n * and Deno 1.x has `window` without `document`. The browser mode needs both event targets.\n */\nfunction hasBrowserEvents(): boolean {\n try {\n return (\n typeof window !== \"undefined\" &&\n window !== null &&\n typeof window.addEventListener === \"function\" &&\n typeof document !== \"undefined\" &&\n document !== null &&\n typeof document.addEventListener === \"function\"\n );\n } catch {\n return false;\n }\n}\n\n/** Adds a listener and returns how to remove it; a target without the API is skipped instead of throwing. */\nfunction listen(target: unknown, type: string, listener: (e: never) => void): () => void {\n const t = target as {\n addEventListener?: (type: string, listener: unknown) => void;\n removeEventListener?: (type: string, listener: unknown) => void;\n } | null | undefined;\n try {\n // only called for the targets the browser runtime was detected by, so this is a last guard\n /* v8 ignore next */\n if (!t || typeof t.addEventListener !== \"function\") return () => undefined;\n t.addEventListener(type, listener);\n } catch {\n return () => undefined;\n }\n return () => {\n try {\n t.removeEventListener?.(type, listener);\n } catch {\n /* nothing to remove */\n }\n };\n}\n\n// ================= HELPERS =================\nfunction uuidV4(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n if (typeof crypto !== \"undefined\" && crypto.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n\n // No Web Crypto (Node 18 without the global, odd runtimes): `track()` must\n // never throw, so fall back to a random v4-shaped id. The key only has to be\n // unique per event for server-side dedup, it is not a secret.\n const bytes = new Uint8Array(16);\n // Stryker disable next-line EqualityOperator: equivalent, a Uint8Array ignores a write past its end\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n let t = Date.now();\n // Stryker disable next-line EqualityOperator: equivalent until the year 10889, when Date.now() first needs a 7th byte\n for (let i = 0; i < 6; i++) {\n bytes[i] ^= t & 0xff;\n t = Math.floor(t / 256);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst MAX_TIMER_MS = 2_147_483_647;\n// delivery attempts per batch: a billion would be a way to never give up, not a setting\nconst MAX_RETRIES = 20;\n// the ingest API refuses a batch of more than 500 events with 400, which would drop the whole batch\nconst MAX_BATCH_SIZE = 500;\n\nfunction isUrl(value: string): boolean {\n try {\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction warn(message: string): void {\n if (typeof console !== \"undefined\") console.warn(message);\n}\n\nfunction warnOption(name: string, value: unknown, fallback: unknown): void {\n warn(`Eventra: option \"${name}\" is invalid (${String(value)}), using ${String(fallback)}`);\n}\n\n/**\n * A numeric option that must be a finite number of at least `min` (and at most `max`). Anything else\n * (NaN, a string, a negative number, Infinity) used to be accepted and silently stop delivery; it now\n * falls back to the default with one warning.\n */\nfunction numberOption(name: string, value: unknown, fallback: number, min: number, max = Number.MAX_SAFE_INTEGER): number {\n if (value === undefined) return fallback;\n if (typeof value === \"number\" && Number.isFinite(value) && value >= min && value <= max) return value;\n warnOption(name, value, fallback);\n return fallback;\n}\n\n/**\n * Runs a callback of the integrator. It must never break the SDK: a throw, or a rejected promise from an\n * async callback, is swallowed (the SDK keeps working and the batch is not retried because of it).\n */\nfunction callSafely<A extends unknown[]>(callback: ((...args: A) => unknown) | undefined, ...args: A): void {\n if (!callback) return;\n try {\n const result = callback(...args);\n if (result && typeof (result as Promise<unknown>).catch === \"function\") {\n (result as Promise<unknown>).catch(() => undefined);\n }\n } catch {\n /* an integrator's callback must not break delivery */\n }\n}\n\n/**\n * Rejects when `signal` aborts (it is fresh, not aborted yet) even if `fetch` itself ignores it: a custom `fetchImpl` that does not honour the\n * signal would otherwise hold the SDK forever, since the request deadline works only through the signal.\n */\nfunction raceAbort<T>(request: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(Object.assign(new Error(\"Eventra: request timed out\"), { name: \"AbortError\" }));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n request.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n\n/** Only the status and headers are used: close the body so the connection is not held by a large unread reply. */\nfunction discardBody(res: Response): void {\n try {\n const closing = res.body?.cancel?.();\n if (closing && typeof closing.catch === \"function\") closing.catch(() => undefined);\n } catch {\n /* a reply without a readable body is fine */\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((r) => setTimeout(r, ms));\n}\n\n// A cut must not leave half of a character outside the basic plane (an emoji, say): the server drops a lone\n// surrogate, so the name or id it stores would differ from what was sent.\nfunction cut(value: string, max: number): string {\n if (value.length <= max) return value;\n const end = value.charCodeAt(max - 1) >= 0xd800 && value.charCodeAt(max - 1) <= 0xdbff ? max - 1 : max;\n return value.slice(0, end);\n}\n\n/** A user id is a string; a number is written out, anything else (null, an object) means no user id. */\nfunction normalizeUserId(value: unknown, max: number): string | undefined {\n // Stryker disable next-line ConditionalExpression: equivalent, Number.isFinite is false for anything but a number\n if (typeof value === \"bigint\" || (typeof value === \"number\" && Number.isFinite(value))) return cut(String(value), max);\n if (typeof value !== \"string\") return undefined;\n return cut(value, max);\n}\n\n/**\n * A user id that names someone: as in track(), not empty or only spaces, and not the text a missing id turns into\n * (`String(user?.id)` gives \"undefined\", JSON.stringify of a missing field \"null\").\n */\nfunction identifiedUserId(value: unknown): string | undefined {\n const id = normalizeUserId(value, MAX_USER_ID);\n if (id === undefined) return undefined;\n const trimmed = id.trim();\n return trimmed && trimmed !== \"undefined\" && trimmed !== \"null\" ? id : undefined;\n}\n\n/** FNV-1a of the API key, in hex: names the stored user per project without putting the key itself in storage. */\nfunction keyHash(value: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16);\n}\n\n/** React Native: one user per app, like a browser tab, though it has no `document`. */\n// Stryker disable OptionalChaining,BlockStatement: equivalent here; a missing navigator throws into the catch, and\n// the catch's undefined is as falsy as false for the one caller\nfunction isReactNative(): boolean {\n try {\n return (globalThis as { navigator?: { product?: unknown } }).navigator?.product === \"ReactNative\";\n } catch {\n return false;\n }\n}\n// Stryker restore OptionalChaining,BlockStatement\n\n/**\n * `process.env.NODE_ENV` is written out in full so bundlers (Vite, webpack, esbuild) replace it when the app is\n * built; without the replacement a browser has no `process` (null here).\n */\nfunction nodeEnv(): string | undefined | null {\n try {\n return process.env.NODE_ENV;\n } catch {\n return null;\n }\n}\n\n/**\n * During development, for the identify hint. A browser bundle counts as development unless built for production\n * (the bundler sets NODE_ENV). A server often has no NODE_ENV in production (Lambda, plain Docker), so there only an\n * explicit \"development\" counts. Test runs never count.\n */\nfunction isDevelopment(server: boolean): boolean {\n const env = nodeEnv();\n if (env === null || env === \"test\") return false;\n return server ? env === \"development\" : env !== \"production\";\n}\n\n/**\n * Never throws — `track()` is called fire-and-forget from arbitrary call sites,\n * so a malformed name must degrade gracefully instead of crashing the caller.\n * Returns `null` for an empty name (event should be dropped); otherwise trims\n * and truncates to `MAX_EVENT_NAME`, matching the documented behavior.\n */\n// What the server removes from a name before storing it: NUL, CR, LF and half of a surrogate pair. Removed here\n// first, so a name made only of those is dropped on its own instead of reaching the server empty, where it fails the\n// whole batch with a 400. A loop, not a regex: lookbehind would be a syntax error in Safari before 16.4.\nfunction stripUnsafeForName(value: string): string {\n let out = \"\";\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code === 0 || code === 0x0a || code === 0x0d) continue;\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n out += value[i] + value[i + 1];\n i++;\n }\n continue;\n }\n if (code >= 0xdc00 && code <= 0xdfff) continue;\n out += value[i];\n }\n return out;\n}\n\nfunction normalizeEventName(name: string): string | null {\n // Stryker disable next-line ConditionalExpression: equivalent, a non-string falls out as an empty name below (or throws into track()'s catch)\n if (typeof name !== \"string\") return null;\n const trimmed = stripUnsafeForName(name).trim();\n if (!trimmed) return null;\n // trimmed again after the cut: the CLI catalog holds the name the same way, so a name cut in the middle of a\n // space is the same event in both\n return cut(trimmed, MAX_EVENT_NAME).trimEnd();\n}\n\n// `attempt` is the 0-based index of the attempt that just failed, so the first\n// retry waits about `base`, the second about `base * 2`, and so on.\nfunction backoffMs(attempt: number, base: number): number {\n const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);\n const jitter = exp * (0.5 + Math.random() * 0.5);\n return jitter;\n}\n\n// one encoder, created on first use (the global is still checked on every call)\nlet textEncoder: TextEncoder | undefined;\n\nfunction utf8ByteLength(value: string): number {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent where Buffer exists (Node, the test runtime), which counts UTF-8 the same way\n if (typeof TextEncoder !== \"undefined\") {\n textEncoder ??= new TextEncoder();\n return textEncoder.encode(value).length;\n }\n const g = globalThis as { Buffer?: { byteLength: (s: string, enc: string) => number } };\n if (g.Buffer) {\n // Stryker disable next-line StringLiteral: equivalent, Buffer.byteLength counts UTF-8 by default\n return g.Buffer.byteLength(value, \"utf8\");\n }\n return value.length;\n}\n\nfunction isStoredEvent(e: unknown): e is TrackEvent {\n // Stryker disable next-line ConditionalExpression: equivalent, a non-object has no idempotencyKey and fails the next check\n if (e === null || typeof e !== \"object\") return false;\n const ev = e as Partial<TrackEvent>;\n return (\n typeof ev.idempotencyKey === \"string\" &&\n ev.idempotencyKey.length > 0 &&\n ev.idempotencyKey.length <= 100 &&\n // Stryker disable next-line ConditionalExpression: equivalent, a name that is not a string has no length and fails the next check\n typeof ev.name === \"string\" &&\n ev.name.length > 0 &&\n ev.name.length <= MAX_EVENT_NAME &&\n typeof ev.timestamp === \"string\" &&\n // Stryker disable next-line ConditionalExpression: equivalent, a user id that is not a string has no length to pass the check\n (ev.userId === undefined || (typeof ev.userId === \"string\" && ev.userId.length <= MAX_USER_ID)) &&\n (ev.properties === undefined || (ev.properties !== null && typeof ev.properties === \"object\" && !Array.isArray(ev.properties)))\n );\n}\n\nfunction mergeQueues(...queues: TrackEvent[][]): TrackEvent[] {\n const seen = new Set<string>();\n const out: TrackEvent[] = [];\n\n for (const q of queues) {\n for (const e of q) {\n // storage and other tabs are untrusted input: skip anything that is not\n // an event instead of throwing out of the constructor\n if (!isStoredEvent(e)) continue;\n if (seen.has(e.idempotencyKey)) continue;\n seen.add(e.idempotencyKey);\n // an event whose time cannot be read is kept (its age cannot be judged), but it is not sent as it is: the\n // server would refuse it, and a 4xx drops the whole batch it is in\n out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: new Date().toISOString() } : e);\n }\n }\n\n return out;\n}\n\n/** The newest events of the queue that fit in PERSISTED_QUEUE_MAX_CHARS, as a JSON array in queue order. */\nfunction persistedQueueJson(queue: TrackEvent[]): string {\n const parts: string[] = [];\n let chars = 2; // the brackets\n for (let i = queue.length - 1; i >= 0; i--) {\n let json: string;\n try {\n json = JSON.stringify(queue[i]);\n } catch {\n continue;\n }\n const next = chars + json.length + (parts.length ? 1 : 0);\n if (next > PERSISTED_QUEUE_MAX_CHARS) break;\n parts.push(json);\n chars = next;\n }\n return `[${parts.reverse().join(\",\")}]`;\n}\n\n// The depth walk visits shared references again for each path, so a fan-out of shared objects would take\n// time that grows with fanout^depth; past this many visits the properties are too large anyway.\nconst MAX_PROPERTIES_NODES = 50_000;\n\nfunction validateProperties(\n properties: unknown,\n): Record<string, unknown> {\n // Properties are an object of values: a number, a string, a list or null is not (it used to pass through as is).\n if (\n // Stryker disable next-line all: equivalent, track() passes `properties ?? {}`, and any other non-object fails the toString check below\n properties === null ||\n // Stryker disable next-line all: equivalent, see the line above\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values\n Object.prototype.toString.call(properties) !== \"[object Object]\"\n ) {\n // Stryker disable next-line StringLiteral: the message is never read, track() catches it and drops the event\n throw new Error(\"Eventra: properties must be an object\");\n }\n // Own keys are listed once per object with Object.keys (what JSON.stringify sends). Listing the keys of an\n // object costs time for each of them whatever is used (V8 builds the whole list even for a `for...in` that\n // stops at once), so a huge object is listed only once and refused right after: past the node budget it could\n // never fit in MAX_PROPERTIES_JSON_BYTES anyway.\n const topKeys = Object.keys(properties as object);\n // Nothing to walk or measure for an empty object (the common case), but it is still copied: the caller\n // keeps its own object and may fill it in later.\n // Stryker disable next-line ConditionalExpression: equivalent, an empty object is walked and copied to the same {}\n if (topKeys.length === 0) return {};\n\n let visited = 0;\n const depth = (obj: unknown, level: number, keys?: string[]): void => {\n if (level > MAX_PROPERTIES_DEPTH) {\n // Stryker disable next-line StringLiteral: the message is never read\n throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);\n }\n // Stryker disable next-line all: a speed guard only; past 50,000 values the JSON is far over the size limit and refused there\n if (++visited > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n if (obj === null || typeof obj !== \"object\") return;\n if (Array.isArray(obj)) {\n // Stryker disable next-line all: a speed guard only, as above\n if (visited + obj.length > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n for (const item of obj) depth(item, level + 1);\n return;\n }\n const own = keys ?? Object.keys(obj);\n // Stryker disable next-line all: a speed guard only, as above\n if (visited + own.length > MAX_PROPERTIES_NODES) {\n throw new Error(\"Eventra: properties are too large to check\");\n }\n for (const key of own) depth((obj as Record<string, unknown>)[key], level + 1);\n };\n\n depth(properties, 0, topKeys);\n\n const json = JSON.stringify(properties);\n // Stryker disable next-line ConditionalExpression: equivalent, a plain object always serializes\n if (json === undefined || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {\n throw new Error(\n `Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`,\n );\n }\n\n // Snapshot: the caller keeps its own object and may change it (even make it\n // circular) before the event is sent. What was validated is what is sent.\n const copy: unknown = JSON.parse(json);\n // an object with a toJSON() can serialize to something that is not an object\n if (copy === null || typeof copy !== \"object\" || Array.isArray(copy)) {\n // Stryker disable next-line StringLiteral: the message is never read\n throw new Error(\"Eventra: properties must be an object\");\n }\n return copy as Record<string, unknown>;\n}\n\n// Seconds (\"120\") or an HTTP date; anything else (or a past date) is ignored.\n// Capped so one odd header cannot park the queue for a long time.\nfunction parseRetryAfterMs(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n // Stryker disable next-line MethodExpression: equivalent with fetch, whose Headers already strip the spaces around a value\n const trimmed = value.trim();\n let ms: number;\n // Stryker disable next-line Regex: equivalent, a value with other characters becomes NaN and is refused below\n if (/^\\d+$/.test(trimmed)) {\n ms = Number(trimmed) * 1000;\n } else {\n const at = Date.parse(trimmed);\n // Stryker disable next-line ConditionalExpression: equivalent, NaN minus now is NaN, refused by the check below\n if (Number.isNaN(at)) return undefined;\n ms = at - Date.now();\n }\n // Stryker disable next-line EqualityOperator: equivalent, a wait of 0 is ignored by both callers\n if (!(ms > 0)) return undefined;\n return Math.min(ms, RETRY_AFTER_MAX_MS);\n}\n\ntype PreparedBatch = {\n events: TrackEvent[];\n // counters that travel with this batch (optional envelope metadata)\n diagnostics?: DiagnosticsReport;\n // each event serialized exactly once, joined into the payload by send()\n json: string[];\n bytes: number;\n};\n\nclass RetryableDeliveryError extends Error {\n constructor(\n message = \"retryable delivery error\",\n readonly retryAfterMs?: number,\n readonly reason: FailedReason = \"server_error\",\n ) {\n super(message);\n this.name = \"RetryableDeliveryError\";\n }\n}\n\n// the SDK was destroyed between two attempts: stop retrying, the batch is neither failed nor delivered\nclass DeliveryStopped extends Error {\n constructor() {\n super(\"delivery stopped by destroy()\");\n this.name = \"DeliveryStopped\";\n }\n}\n\n// ================= STORAGE =================\nclass Storage {\n private enabled = false;\n\n constructor() {\n try {\n if (typeof localStorage !== \"undefined\") {\n localStorage.setItem(\"__t\", \"1\");\n localStorage.removeItem(\"__t\");\n this.enabled = true;\n }\n } catch {\n /* private mode / blocked storage */\n }\n }\n\n // localStorage works here (not in Node, a blocked or private-mode browser)\n get isEnabled(): boolean {\n return this.enabled;\n }\n\n get(key: string): unknown {\n if (!this.enabled) return null;\n try {\n return JSON.parse(localStorage.getItem(key) || \"null\");\n } catch {\n return null;\n }\n }\n\n set(key: string, value: unknown) {\n let json: string;\n try {\n json = JSON.stringify(value);\n } catch {\n // only the diagnostics counters are written here, plain numbers and strings\n /* v8 ignore next */\n return;\n }\n this.setRaw(key, json);\n }\n\n setRaw(key: string, json: string) {\n if (!this.enabled) return;\n try {\n localStorage.setItem(key, json);\n } catch {\n /* quota exceeded */\n }\n }\n\n remove(key: string) {\n if (!this.enabled) return;\n try {\n localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n }\n}\n\n// ================= LEADER =================\n/** Whether `localStorage` can be used at all: in a sandboxed iframe even looking at it throws a SecurityError. */\nfunction storageAvailable(): boolean {\n try {\n return typeof localStorage !== \"undefined\" && localStorage !== null;\n } catch {\n return false;\n }\n}\n\nclass Leader {\n private tabId = uuidV4();\n private isLeader = false;\n private heartbeat?: ReturnType<typeof setInterval>;\n private election?: ReturnType<typeof setInterval>;\n private offStorage?: () => void;\n\n constructor(private onLeadershipChange?: (isLeader: boolean) => void) {\n if (!storageAvailable()) {\n this.isLeader = true;\n return;\n }\n\n this.tick();\n\n this.election = setInterval(() => this.tick(), LEADER_TTL_MS / 2);\n\n // Leader is only constructed in the browser runtime, so `window` exists; listen() still never throws\n /* v8 ignore next */\n this.offStorage = listen(typeof window !== \"undefined\" ? window : undefined, \"storage\", (e: StorageEvent) => {\n if (e.key === LEADER_KEY) this.tick();\n });\n }\n\n private tick() {\n const was = this.isLeader;\n\n if (this.isLeader) {\n if (!this.verifyLease()) {\n this.isLeader = false;\n } else {\n this.renew();\n }\n } else {\n this.isLeader = this.tryAcquire();\n if (this.isLeader) {\n // This branch is only reached when isLeader was just flipped from\n // false to true. Whenever a tick() ends with isLeader false, the\n // check below (`!this.isLeader && this.heartbeat`) always clears\n // `heartbeat` back to undefined in that same tick — so on entry\n // here it can never already be set.\n /* v8 ignore else */\n if (!this.heartbeat) {\n this.heartbeat = setInterval(() => this.renew(), LEADER_TTL_MS / 2);\n }\n }\n }\n\n if (!this.isLeader && this.heartbeat) {\n clearInterval(this.heartbeat);\n this.heartbeat = undefined;\n }\n\n if (was !== this.isLeader) {\n this.onLeadershipChange?.(this.isLeader);\n }\n }\n\n private tryAcquire(): boolean {\n try {\n const now = Date.now();\n const raw = localStorage.getItem(LEADER_KEY);\n if (!raw) {\n this.renew();\n return true;\n }\n const parsed = JSON.parse(raw) as { ts: number; tabId: string };\n if (now - parsed.ts > LEADER_TTL_MS) {\n this.renew();\n return true;\n }\n if (parsed.tabId === this.tabId) {\n this.renew();\n return true;\n }\n return false;\n } catch {\n return true;\n }\n }\n\n private verifyLease(): boolean {\n try {\n const raw = localStorage.getItem(LEADER_KEY);\n if (!raw) return false;\n const parsed = JSON.parse(raw) as { ts: number; tabId: string };\n return (\n parsed.tabId === this.tabId && Date.now() - parsed.ts <= LEADER_TTL_MS\n );\n } catch {\n return false;\n }\n }\n\n private renew() {\n try {\n localStorage.setItem(\n LEADER_KEY,\n JSON.stringify({ ts: Date.now(), tabId: this.tabId }),\n );\n } catch {\n /* ignore */\n }\n }\n\n canSend() {\n return this.isLeader;\n }\n\n destroy() {\n if (this.election) clearInterval(this.election);\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.offStorage?.();\n if (this.isLeader && storageAvailable()) {\n try {\n const raw = localStorage.getItem(LEADER_KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as { tabId: string };\n if (parsed.tabId === this.tabId) {\n localStorage.removeItem(LEADER_KEY);\n }\n }\n } catch {\n /* ignore */\n }\n }\n }\n}\n\n// ================= SDK =================\n// The key is sent with every batch, so a plain http endpoint exposes it on the\n// network. Not an error (an internal http collector is a legitimate setup);\n// loopback is exempt.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\nfunction warnIfInsecureEndpoint(endpoint: string): void {\n if (typeof console === \"undefined\") return;\n try {\n const url = new URL(endpoint);\n if (url.protocol === \"http:\" && !LOOPBACK_HOSTS.has(url.hostname)) {\n console.warn(\n \"Eventra: endpoint uses plain http, the API key is sent unencrypted - use https\",\n );\n }\n } catch {\n /* a relative or malformed endpoint is left for fetch to reject */\n }\n}\n\n// fetch with `redirect: \"error\"` rejects with a TypeError whose cause says so\n// (undici: \"unexpected redirect\"). A browser only reports \"Failed to fetch\", so\n// there a redirect cannot be told from any other network failure.\nfunction isRedirectError(err: unknown): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 3 && current instanceof Error; depth++) {\n if (/redirect/i.test(current.message)) return true;\n current = (current as Error & { cause?: unknown }).cause;\n }\n return false;\n}\n\nexport class Eventra {\n private apiKey: string;\n private endpoint: string;\n private runtime: Runtime;\n private fetch: typeof fetch;\n\n private queue: TrackEvent[] = [];\n private sending: TrackEvent[] | null = null;\n // events other open tabs announced on the channel, by key, and until when they are theirs to send\n private liveTabEvents = new Map<string, number>();\n private inFlight = false;\n private destroyed = false;\n private shuttingDown = false;\n\n private maxBatch: number;\n private maxQueue: number;\n private maxPayloadBytes: number;\n private flushInterval: number;\n private retries: number;\n private retryDelay: number;\n private persistQueue: boolean;\n private diagnosticsEnabled: boolean;\n private diagnostics: Diagnostics;\n\n private timer?: ReturnType<typeof setInterval>;\n\n private storage = new Storage();\n private leader: Leader | null = null;\n private channel?: BroadcastChannel;\n private offStorageQueue?: () => void;\n\n private failureCount = 0;\n private warnedRedirect = false;\n private circuitOpenUntil = 0;\n private circuitHalfOpen = false;\n // consecutive times the circuit opened without a success in between; drives\n // the exponential cooldown\n private circuitOpenCount = 0;\n\n private flushPromise: Promise<void> | null = null;\n private persistTimer?: ReturnType<typeof setTimeout>;\n private persistDirty = false;\n private deliveredKeys = new Set<string>();\n // a 429/5xx Retry-After that outlives the last attempt also delays the next\n // flush (timer, size trigger, manual); shutdown() ignores it\n private nextFlushAt = 0;\n // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it\n private shutdownDeadline = 0;\n private shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;\n private shutdownPromise?: Promise<void>;\n // the page is being left (`pagehide`)\n private leaving = false;\n\n private sdkInfo: SdkInfo;\n private options: TrackerOptions;\n\n private exitHandlers: Array<() => void> = [];\n\n // the user set by identify() (browser and other single-user runtimes), added to every event without its own\n private userId?: string;\n private warnedServerIdentify = false;\n private warnedInvalidIdentify = false;\n private warnedInvalidUser = false;\n // one user for the whole instance is safe only where the instance serves one person: a browser tab, a React\n // Native app. Everything else (Node, edge, Lambda, Deno, Cloudflare Workers) may serve many requests at once.\n private singleUser = false;\n private userKey = USER_KEY_PREFIX;\n // identifyHint: events without a user id so far, and whether the check is over\n private eventsWithoutUser = 0;\n private identifyHintDone = false;\n\n constructor(options: TrackerOptions) {\n if (!options || typeof options !== \"object\" || typeof options.apiKey !== \"string\" || !options.apiKey) {\n throw new Error(\"Eventra: apiKey required - new Eventra({ apiKey: \\\"...\\\" })\");\n }\n // the key travels in an HTTP header: a character outside Latin-1 makes every request fail, and nothing says why\n if (/[^\\u0020-\\u00ff]/.test(options.apiKey)) {\n throw new Error(\"Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard\");\n }\n if (options.fetchImpl !== undefined && typeof options.fetchImpl !== \"function\") {\n throw new Error(\"Eventra: fetchImpl must be a function\");\n }\n\n activeInstances++;\n if (activeInstances > 1 && typeof console !== \"undefined\") {\n console.warn(\n \"Eventra: multiple SDK instances detected - duplicate timers and sends are possible\",\n );\n }\n\n try {\n this.options = options;\n this.apiKey = options.apiKey;\n if (options.endpoint !== undefined && (typeof options.endpoint !== \"string\" || !options.endpoint.trim())) {\n warnOption(\"endpoint\", options.endpoint, DEFAULT_ENDPOINT);\n }\n this.endpoint =\n typeof options.endpoint === \"string\" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;\n if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {\n warnOption(\"endpoint\", this.endpoint, DEFAULT_ENDPOINT);\n this.endpoint = DEFAULT_ENDPOINT;\n }\n if (options.multiTabMode !== undefined && options.multiTabMode !== \"independent\" && options.multiTabMode !== \"leader\") {\n warnOption(\"multiTabMode\", options.multiTabMode, \"independent\");\n }\n if (options.diagnostics !== undefined && typeof options.diagnostics !== \"boolean\") {\n warnOption(\"diagnostics\", options.diagnostics, \"true\");\n }\n if (options.identifyHint !== undefined && typeof options.identifyHint !== \"boolean\") {\n warnOption(\"identifyHint\", options.identifyHint, \"true\");\n }\n this.identifyHintDone = options.identifyHint === false;\n for (const name of [\"maxBatchSize\", \"maxQueueSize\"] as const) {\n const value = options[name];\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {\n warnOption(name, value, Math.floor(value));\n }\n }\n this.runtime = detectRuntime();\n this.singleUser = this.runtime === \"browser\" || isReactNative();\n this.userKey = `${USER_KEY_PREFIX}${keyHash(options.apiKey)}`;\n warnIfInsecureEndpoint(this.endpoint);\n\n this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);\n if (!this.fetch) {\n throw new Error(\"Eventra: fetch not available - provide fetchImpl\");\n }\n\n if (typeof options.maxBatchSize === \"number\" && options.maxBatchSize > MAX_BATCH_SIZE && Number.isFinite(options.maxBatchSize)) {\n warnOption(\"maxBatchSize\", options.maxBatchSize, MAX_BATCH_SIZE);\n }\n this.maxBatch = Math.min(MAX_BATCH_SIZE, Math.floor(numberOption(\"maxBatchSize\", options.maxBatchSize, 50, 1)));\n this.maxQueue = Math.floor(numberOption(\"maxQueueSize\", options.maxQueueSize, 10000, 1));\n this.maxPayloadBytes = numberOption(\"maxPayloadBytes\", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);\n this.flushInterval = numberOption(\"flushInterval\", options.flushInterval, 2000, 1, MAX_TIMER_MS);\n this.retries = numberOption(\"maxRetries\", options.maxRetries, 3, 0, MAX_RETRIES);\n this.retryDelay = numberOption(\"retryBaseDelayMs\", options.retryBaseDelayMs, 300, 0);\n this.shutdownBudget = numberOption(\"shutdownTimeoutMs\", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);\n // Queued events may carry userId/properties - default on for durability\n // across reloads, but let privacy-sensitive integrators opt out of ever\n // writing that data to localStorage.\n this.persistQueue = options.persistQueue ?? true;\n\n // Counters of what could not be delivered travel with the next successful\n // batch; numbers only, never event content. Off with `diagnostics: false`.\n this.diagnosticsEnabled = options.diagnostics !== false;\n const shared = this.runtime === \"browser\" && this.persistQueue;\n this.diagnostics = new Diagnostics(\n shared ? new SharedStore(this.storage) : new MemoryStore(),\n DIAGNOSTICS_KEY,\n uuidV4,\n shared ? () => this.scheduleDiagnosticsSync() : undefined,\n );\n\n this.sdkInfo = {\n name: SDK_NAME,\n version: SDK_VERSION,\n runtime: this.runtime,\n };\n\n if (this.runtime === \"browser\") {\n if (this.persistQueue) {\n this.userId = this.loadStoredUser();\n this.loadAndMergeQueue();\n } else {\n // a user kept by an earlier visit with persistence on must not outlive the switch to memory only\n this.storage.remove(this.userKey);\n }\n this.setupQueueSync();\n }\n\n if (this.runtime === \"browser\" && options.multiTabMode === \"leader\") {\n this.leader = new Leader((isLeader) => {\n if (isLeader) void this.flushNow(false);\n });\n }\n\n if (!options.disableTimer) {\n this.startTimer();\n }\n\n if (this.runtime === \"browser\") {\n this.setupBrowserExit();\n }\n\n if (options.autoFlushOnExit !== false && this.runtime !== \"browser\") {\n this.setupProcessExit();\n }\n\n // the key must not show in `console.log(tracker)`, `util.inspect` or `JSON.stringify(tracker)`\n Object.defineProperty(this, \"apiKey\", { enumerable: false });\n Object.defineProperty(this, \"options\", { enumerable: false });\n } catch (error) {\n // a constructor that fails must leave nothing behind: not a counted instance, not an open channel,\n // not a timer or a listener (a BroadcastChannel keeps a Node process alive for good)\n this.destroyed = true;\n activeInstances = Math.max(0, activeInstances - 1);\n for (const undo of [\n () => clearInterval(this.timer),\n () => this.leader?.destroy(),\n () => this.channel?.close(),\n () => this.exitHandlers.forEach((undoHandler) => undoHandler()),\n ]) {\n try {\n undo();\n } catch {\n /* nothing more to undo */\n }\n }\n throw error;\n }\n }\n\n track(name: string, options?: TrackOptions) {\n this.trackSafely(name, options, undefined);\n }\n\n /**\n * Sets the user of every following event that does not name its own, in a browser or a React Native app. In\n * the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open\n * tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may\n * serve many users at once, so it is ignored with one warning: use `withUser()` there.\n */\n identify(userId: string | number): void {\n if (this.destroyed) return;\n if (!this.singleUser) {\n if (!this.warnedServerIdentify) {\n this.warnedServerIdentify = true;\n warn(\n \"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)\",\n );\n }\n return;\n }\n const id = identifiedUserId(userId);\n if (id === undefined) {\n if (!this.warnedInvalidIdentify) {\n this.warnedInvalidIdentify = true;\n warn(\"Eventra: identify() needs a user id (a non-empty string or a number) - to sign a user out, call reset()\");\n }\n return;\n }\n this.identifyHintDone = true;\n if (id !== this.userId) this.setUser(id);\n }\n\n /** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */\n reset(): void {\n if (this.destroyed || !this.singleUser) return;\n // also when this tab holds no user: another tab or an earlier visit may have stored one\n this.setUser(undefined);\n }\n\n /** The user set by `identify()`, if any. */\n getUserId(): string | undefined {\n return this.userId;\n }\n\n /**\n * A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares\n * this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events\n * without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.\n */\n withUser(userId: string | number | null | undefined): EventraScope {\n let id: string | undefined;\n if (userId !== undefined && userId !== null) {\n id = identifiedUserId(userId);\n if (id === undefined && !this.warnedInvalidUser) {\n this.warnedInvalidUser = true;\n warn(\"Eventra: withUser() got an invalid user id (it needs a non-empty string or a number), its events are sent without one\");\n }\n }\n if (id !== undefined) this.identifyHintDone = true;\n // null: a scope without a user, which does not fall back to identify()\n const scopeUser = id ?? null;\n return {\n track: (name: string, options?: TrackOptions) => this.trackSafely(name, options, scopeUser),\n };\n }\n\n private setUser(id: string | undefined) {\n this.userId = id;\n if (this.runtime !== \"browser\") return;\n // removing is unconditional: a user stored with persistence on must go on sign-out whatever the setting now\n if (id === undefined) this.storage.remove(this.userKey);\n else if (this.persistQueue) this.storage.set(this.userKey, id);\n this.broadcast({ type: \"user\", key: this.userKey, userId: id ?? null });\n }\n\n private loadStoredUser(): string | undefined {\n const saved = this.storage.get(this.userKey);\n return typeof saved === \"string\" ? identifiedUserId(saved) : undefined;\n }\n\n // scopeUserId: undefined outside a scope, null for a scope without a user\n private trackSafely(name: string, options: TrackOptions | undefined, scopeUserId: string | null | undefined) {\n // `track()` is called fire-and-forget from anywhere: nothing it meets (a userId getter that throws, a\n // crypto that throws) may come out of it\n try {\n this.trackEvent(name, options, scopeUserId);\n } catch {\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n }\n }\n\n private trackEvent(name: string, options: TrackOptions | undefined, scopeUserId: string | null | undefined) {\n if (this.destroyed || this.shuttingDown) return;\n\n const eventName = normalizeEventName(name);\n if (eventName === null) {\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n let properties: Record<string, unknown>;\n try {\n properties = validateProperties(options?.properties ?? {});\n } catch {\n // Oversized/too-deep properties can't be safely truncated — drop the\n // event instead of throwing out of a fire-and-forget call site.\n this.recordDiagnostic(\"invalid_event\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n if (this.queue.length >= this.maxQueue) {\n this.recordDiagnostic(\"queue_full\");\n callSafely(this.options.onEventsDropped, 1);\n return;\n }\n\n // a userId of the call wins (null: no user; an empty or blank one counts as not given), then the scope of\n // withUser() (null: a scope without a user), then the user of identify()\n const given = options?.userId;\n const ownUserId = typeof given === \"string\" && !given.trim() ? undefined : given;\n const event: TrackEvent = {\n idempotencyKey: uuidV4(),\n name: eventName,\n userId:\n ownUserId !== undefined\n ? normalizeUserId(ownUserId, MAX_USER_ID)\n : scopeUserId !== undefined\n ? (scopeUserId ?? undefined)\n : this.userId,\n properties,\n timestamp: new Date().toISOString(),\n };\n\n this.queue.push(event);\n if (!this.identifyHintDone) this.checkIdentifyHint(identifiedUserId(event.userId) !== undefined);\n\n // Stryker disable next-line ConditionalExpression: equivalent outside a browser, where there is no storage to persist to and no channel\n if (this.runtime === \"browser\") {\n this.schedulePersist();\n this.broadcast({ type: \"queue-add\", events: [event] });\n }\n\n // fire-and-forget triggers start a flush when none is running; one that is running picks the new event up\n // itself (a flush() of the app, by contrast, waits for it and then sends what is left)\n if (this.queue.length >= this.maxBatch) {\n void this.flushNow(false);\n }\n\n if (this.runtime === \"serverless\") {\n void this.flushNow(false);\n }\n }\n\n async flush(): Promise<void> {\n // A flush already running (timer, size trigger, serverless auto-flush) must\n // be awaited, otherwise `await flush()` resolves while events are in flight\n // and a serverless handler can freeze before they are delivered.\n if (this.flushPromise) await this.flushPromise.catch(() => undefined);\n return this.flushNow(false);\n }\n\n // `force` skips only the Retry-After delay (the last chance at shutdown);\n // the circuit breaker still applies\n private async flushNow(force: boolean): Promise<void> {\n if (this.inFlight || this.destroyed) return;\n if (!this.queue.length && !this.sending?.length) return;\n if (!force && Date.now() < this.nextFlushAt) return;\n\n if (this.leader && !this.leader.canSend()) return;\n\n const now = Date.now();\n if (now < this.circuitOpenUntil) return;\n\n if (this.circuitOpenUntil > 0 && now >= this.circuitOpenUntil) {\n this.circuitHalfOpen = true;\n this.circuitOpenUntil = 0;\n }\n\n this.inFlight = true;\n\n const run = this.runFlush();\n this.flushPromise = run;\n\n try {\n await run;\n } finally {\n this.flushPromise = null;\n }\n }\n\n private async runFlush(): Promise<void> {\n try {\n while (this.queue.length > 0 && !this.destroyed) {\n const report = this.diagnosticsEnabled\n ? this.diagnostics.claim(this.queue.length, SDK_VERSION)\n : null;\n const batch = this.buildBatch(report);\n if (!batch.events.length) break;\n\n this.sending = batch.events;\n\n try {\n const accepted = await this.send(batch);\n // acknowledged only by a 2xx for the batch that carried the report\n if (accepted && batch.diagnostics) {\n this.diagnostics.ack(batch.diagnostics.reportId);\n }\n this.removeDelivered(batch.events);\n this.nextFlushAt = 0;\n this.failureCount = 0;\n this.circuitHalfOpen = false;\n this.circuitOpenCount = 0;\n } catch (err) {\n if (err instanceof RetryableDeliveryError) {\n this.recordDiagnostic(err.reason);\n if (err.retryAfterMs) {\n this.nextFlushAt = Date.now() + err.retryAfterMs;\n }\n this.failureCount++;\n if (this.circuitHalfOpen || this.failureCount >= CIRCUIT_FAILURE_THRESHOLD) {\n this.recordDiagnostic(\"circuit_open\");\n // Exponential cooldown, capped. A failed half-open probe counts\n // as another opening, so an outage is probed less and less often.\n const cooldown = Math.min(\n CIRCUIT_COOLDOWN_MAX_MS,\n CIRCUIT_COOLDOWN_MS * 2 ** this.circuitOpenCount,\n );\n this.circuitOpenCount++;\n this.circuitOpenUntil =\n Date.now() + Math.max(cooldown, err.retryAfterMs ?? 0);\n this.circuitHalfOpen = false;\n }\n break;\n }\n break;\n } finally {\n this.sending = null;\n }\n\n // Reachable only after a *successful* send() (the catch above always\n // `break`s immediately whenever circuitOpenUntil is set to a future\n // value). flush() already returned early at the top if\n // `now < circuitOpenUntil`, so by the time execution gets here\n // circuitOpenUntil can only be <= that earlier `now` — never in the\n // future. Defense-in-depth against a future refactor reordering the\n // checks above, not currently reachable.\n /* v8 ignore next */\n if (this.circuitOpenUntil > Date.now()) break;\n }\n } finally {\n this.inFlight = false;\n }\n }\n\n /**\n * Flush pending events, then tear down timers and listeners. Gives up after\n * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot\n * hold a SIGTERM shutdown past a typical grace period.\n */\n shutdown(): Promise<void> {\n // a second call (the app's own, after a signal handler started it) waits for the first instead of\n // returning at once, so `await shutdown()` followed by `process.exit()` does not lose the queue\n this.shutdownPromise ??= this.runShutdown();\n return this.shutdownPromise;\n }\n\n private async runShutdown(): Promise<void> {\n this.shuttingDown = true;\n\n const budget = this.shutdownBudget;\n this.shutdownDeadline = Date.now() + Math.max(0, budget);\n\n let budgetTimer: ReturnType<typeof setTimeout> | undefined;\n const outOfTime = new Promise<void>((resolve) => {\n budgetTimer = setTimeout(resolve, Math.max(0, budget));\n (budgetTimer as { unref?: () => void }).unref?.();\n });\n\n try {\n await Promise.race([this.flushEverything(), outOfTime]);\n } finally {\n clearTimeout(budgetTimer);\n this.destroy();\n }\n }\n\n private async flushEverything(): Promise<void> {\n // A flush may already be running (timer, size trigger): flush() would\n // return immediately and destroy() would drop what is still queued, so\n // let it finish and then send whatever is left.\n if (this.flushPromise) {\n await this.flushPromise;\n }\n await this.flushNow(true);\n }\n\n destroy() {\n if (this.destroyed) return;\n this.destroyed = true;\n activeInstances = Math.max(0, activeInstances - 1);\n\n if (this.timer) clearInterval(this.timer);\n\n // write any pending queue state before the listeners go away\n this.persistNow();\n\n // Without storage the queue goes with this instance (Node, where a saved queue is never read back,\n // `persistQueue: false`, or a browser that refuses localStorage): say how many events that is, as\n // for every other drop. A batch still in flight is not counted, its request may yet arrive.\n // (shutdown() with the circuit breaker open used to drop them without a word.)\n const kept = this.runtime === \"browser\" && this.persistQueue && this.storage.isEnabled;\n if (!kept) {\n const inFlight = new Set(this.sending ?? []);\n const lost = this.queue.filter((event) => !inFlight.has(event)).length;\n if (lost > 0) callSafely(this.options.onEventsDropped, lost);\n }\n\n this.leader?.destroy();\n\n if (this.channel) {\n try {\n this.channel.close();\n } catch {\n /* a channel that cannot be closed must not skip the rest of the teardown */\n }\n this.channel = undefined;\n }\n\n this.offStorageQueue?.();\n\n for (const off of this.exitHandlers) {\n off();\n }\n }\n\n private buildBatch(report: DiagnosticsReport | null): PreparedBatch {\n const events: TrackEvent[] = [];\n const json: string[] = [];\n const sentAt = new Date().toISOString();\n // size of the envelope with no events, `[]` included; every event then adds\n // its own bytes plus one comma between neighbours (equal to stringifying the\n // whole envelope, without redoing it for every candidate)\n const envelopeBytes = (withReport: boolean) =>\n utf8ByteLength(\n JSON.stringify({\n sentAt,\n sdk: this.sdkInfo,\n ...(withReport && report ? { diagnostics: report } : {}),\n events: [],\n }),\n );\n let withReport = report !== null;\n let bytes = envelopeBytes(withReport);\n let index = 0;\n\n while (index < this.queue.length && events.length < this.maxBatch) {\n const event = this.queue[index];\n if (this.leftToItsTab(event)) {\n index++;\n continue;\n }\n let eventJson: string;\n try {\n eventJson = JSON.stringify(event);\n } catch {\n // cannot be serialized, so it can never be sent: drop it, do not let it\n // wedge the queue\n this.dropPoisonEvent(event);\n continue;\n }\n const total = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);\n\n if (total > this.maxPayloadBytes) {\n if (events.length === 0) {\n if (withReport) {\n // the report itself may be what does not fit: send this batch\n // without it (it stays pending) before judging the event\n withReport = false;\n bytes = envelopeBytes(false);\n continue;\n }\n // removed from this.queue, so `index` now points at the next event;\n // the following event may be small enough to carry the report\n this.dropPoisonEvent(event);\n withReport = report !== null;\n bytes = envelopeBytes(withReport);\n continue;\n }\n break;\n }\n\n events.push(event);\n json.push(eventJson);\n bytes = total;\n index++;\n }\n\n return {\n events,\n json,\n bytes,\n diagnostics: withReport && report ? report : undefined,\n };\n }\n\n // one warning during development when an app sends events without ever saying whose they are\n private checkIdentifyHint(hasUser: boolean) {\n if (hasUser) {\n this.identifyHintDone = true;\n return;\n }\n if (++this.eventsWithoutUser < IDENTIFY_HINT_AFTER) return;\n this.identifyHintDone = true;\n if (!isDevelopment(!this.singleUser)) return;\n const how = this.singleUser\n ? \"call tracker.identify(userId) after sign-in\"\n : \"track through tracker.withUser(userId) in each request\";\n warn(\n `Eventra: none of the first ${IDENTIFY_HINT_AFTER} events has a userId, so unique users cannot be counted - ${how} (identifyHint: false turns this off)`,\n );\n }\n\n private dropPoisonEvent(event: TrackEvent) {\n this.recordDiagnostic(\"too_large\");\n this.removeDelivered([event]);\n callSafely(this.options.onEventsDropped, 1);\n callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });\n }\n\n private removeDelivered(batch: TrackEvent[]) {\n const keys = new Set(batch.map((e) => e.idempotencyKey));\n // a delivered batch is nearly always the start of the queue: cut it off instead of testing every event\n // (filtering each batch made draining a large queue quadratic: 300,000 events blocked the loop for minutes)\n // Stryker disable next-line ConditionalExpression,EqualityOperator,ArrowFunction,BooleanLiteral: equivalent, a wrong \"no\" takes the filter path, which gives the same queue (the shortcut is speed only)\n const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);\n this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));\n\n // Stryker disable next-line ConditionalExpression: equivalent outside a browser, where there is no storage and no channel\n if (this.runtime === \"browser\") {\n this.rememberDelivered(keys);\n this.schedulePersist();\n this.broadcast({ type: \"delivered\", keys: [...keys] });\n }\n }\n\n // Resolves true only when the server answered 2xx for a payload that\n // carried the diagnostics report (the only case that acknowledges it).\n private async send(batch: PreparedBatch): Promise<boolean> {\n const { events } = batch;\n let carriesDiagnostics = batch.diagnostics !== undefined;\n // same shape and key order as JSON.stringify({ sentAt, sdk, events }), with\n // every event serialized once, in buildBatch()\n const buildPayload = (withDiagnostics: boolean) => {\n const head = JSON.stringify({\n sentAt: new Date().toISOString(),\n sdk: this.sdkInfo,\n ...(withDiagnostics && batch.diagnostics\n ? { diagnostics: batch.diagnostics }\n : {}),\n });\n return `${head.slice(0, -1)},\"events\":[${batch.json.join(\",\")}]}`;\n };\n let payload = buildPayload(carriesDiagnostics);\n\n const payloadBytes = batch.bytes;\n /* v8 ignore start */\n // buildBatch() only ever returns a batch whose size already fits within\n // maxPayloadBytes, and nothing mutates `events` or maxPayloadBytes between\n // that check and this one, so this re-check can't trip in practice.\n // Defense-in-depth, not dead logic to be deleted.\n if (payloadBytes > this.maxPayloadBytes) {\n this.dropPoisonEvents(events);\n return false;\n }\n /* v8 ignore stop */\n\n const useKeepalive =\n // Stryker disable next-line all: equivalent, document exists exactly in the browser runtime\n this.runtime === \"browser\" &&\n // Stryker disable next-line all: equivalent, see the line above\n typeof document !== \"undefined\" &&\n (document.visibilityState === \"hidden\" || this.leaving) &&\n // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows\n // Stryker disable next-line EqualityOperator: a body of exactly the keepalive limit; not worth a 60,000-byte fixture\n payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);\n\n // A half-open breaker lets exactly one request through as a probe: no\n // retries while we don't know yet whether the endpoint is back.\n const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);\n // a server that rejects the unknown `diagnostics` field answers 400/422;\n // the batch is then sent once more without it\n let strippedDiagnostics = false;\n\n // Stryker disable next-line EqualityOperator: equivalent, the last attempt always returns or throws\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const controller = new AbortController();\n const attemptTimeoutMs =\n this.shutdownDeadline > 0\n ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now()))\n : FETCH_TIMEOUT_MS;\n const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);\n\n try {\n const res = await raceAbort(\n this.fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n },\n body: payload,\n signal: controller.signal,\n keepalive: useKeepalive,\n // never follow a redirect: x-api-key is a custom header, so fetch\n // would forward it to wherever a compromised or misconfigured\n // endpoint points\n redirect: \"error\",\n }),\n controller.signal,\n );\n discardBody(res);\n\n if (res.status === 429 || res.status >= 500) {\n throw new RetryableDeliveryError(\n // Stryker disable next-line StringLiteral: the message is never read\n \"retryable delivery error\",\n // Stryker disable next-line OptionalChaining: equivalent with a real Response, which always has headers.get\n parseRetryAfterMs(res.headers?.get?.(\"retry-after\")),\n res.status === 429 ? \"rate_limited\" : \"server_error\",\n );\n }\n\n if (res.status >= 400 && res.status < 500) {\n if (carriesDiagnostics && (res.status === 400 || res.status === 422)) {\n // maybe an older server that does not know the field: events must\n // not be lost over it, so try again without it (not a new attempt)\n carriesDiagnostics = false;\n strippedDiagnostics = true;\n payload = buildPayload(false);\n attempt--;\n continue;\n }\n this.recordDiagnostic(\"rejected\", events.length);\n // a copy: a callback that empties the array it is given must not empty the batch the SDK is working on\n callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });\n this.removeDelivered(events);\n return false;\n }\n\n if (!res.ok) {\n throw new RetryableDeliveryError();\n }\n\n if (strippedDiagnostics) {\n // accepted only once the field was left out: this server does not\n // take it, so stop sending it (the counters are kept, not reported)\n this.diagnosticsEnabled = false;\n // Stryker disable next-line BooleanLiteral: equivalent, the counters are never sent once diagnostics are off\n return false;\n }\n\n return carriesDiagnostics;\n } catch (err) {\n // Stryker disable next-line ConditionalExpression,StringLiteral: equivalent wherever console exists (everywhere the tests run)\n if (!this.warnedRedirect && isRedirectError(err) && typeof console !== \"undefined\") {\n this.warnedRedirect = true;\n console.warn(\n \"Eventra: the endpoint answered with a redirect. It is not followed, so the API key is not forwarded, and events stay queued - check the endpoint URL (for example http instead of https)\",\n );\n }\n const isLast = attempt >= maxAttempts - 1;\n const retryAfter =\n err instanceof RetryableDeliveryError ? err.retryAfterMs : undefined;\n const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);\n // during shutdown there is no time left for another sleep + attempt\n const outOfBudget =\n this.shutdownDeadline > 0 && Date.now() + wait >= this.shutdownDeadline;\n\n if (isLast || outOfBudget) {\n throw err instanceof RetryableDeliveryError\n ? err\n // Stryker disable next-line StringLiteral: the message is never read\n : new RetryableDeliveryError(\"retryable delivery error\", undefined, \"network\");\n }\n\n await sleep(wait);\n // destroy() during the wait: no more attempts (they used to go on after it)\n if (this.destroyed) throw new DeliveryStopped();\n } finally {\n clearTimeout(timeout);\n }\n }\n\n // unreachable: the last attempt either returns or throws\n /* v8 ignore next */\n return false;\n }\n\n // Only caller is the defensive re-check in send() above, which is itself\n // unreachable in practice (see comment there) — see the same file's\n // ignore rationale. Kept for when that check trips defensively.\n /* v8 ignore start */\n private dropPoisonEvents(events: TrackEvent[]) {\n for (const event of events) {\n this.dropPoisonEvent(event);\n }\n }\n /* v8 ignore stop */\n\n private recordDiagnostic(reason: Parameters<Diagnostics[\"record\"]>[0], n = 1) {\n if (this.diagnosticsEnabled) this.diagnostics.record(reason, n);\n }\n\n // counters reach localStorage on the same debounce as the queue\n private scheduleDiagnosticsSync() {\n if (this.persistTimer !== undefined) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = undefined;\n this.persistNow();\n }, PERSIST_DEBOUNCE_MS);\n }\n\n private loadAndMergeQueue() {\n const remote = this.storage.get(QUEUE_KEY);\n if (Array.isArray(remote)) {\n const fresh = this.withoutExpired(remote as TrackEvent[]);\n // rewrite storage without what was dropped, so it does not come back\n if (fresh.length !== remote.length) this.persistDirty = true;\n this.queue = mergeQueues(this.queue, this.withoutDelivered(fresh));\n }\n this.queue = this.trimQueue();\n }\n\n // events whose timestamp is unreadable are kept: their age cannot be judged\n private withoutExpired(events: TrackEvent[]): TrackEvent[] {\n const oldest = Date.now() - PERSISTED_EVENT_MAX_AGE_MS;\n return events.filter((e) => {\n const at = Date.parse(e?.timestamp);\n return Number.isNaN(at) || at >= oldest;\n });\n }\n\n private withoutDelivered(events: TrackEvent[]): TrackEvent[] {\n // Stryker disable next-line ConditionalExpression: equivalent, filtering against an empty set keeps every event\n if (!this.deliveredKeys.size) return events;\n return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));\n }\n\n private rememberDelivered(keys: Iterable<string>) {\n for (const key of keys) this.deliveredKeys.add(key);\n // Set iterates in insertion order, so this drops the oldest keys first\n for (const key of this.deliveredKeys) {\n if (this.deliveredKeys.size <= DELIVERED_KEYS_MAX) break;\n this.deliveredKeys.delete(key);\n }\n }\n\n // Burst of track() calls = one write. Reading, merging and rewriting the\n // whole queue on every call made each call cost O(queue size).\n private schedulePersist() {\n if (!this.persistQueue) return;\n this.persistDirty = true;\n if (this.persistTimer !== undefined) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = undefined;\n this.persistNow();\n }, PERSIST_DEBOUNCE_MS);\n }\n\n // Immediate write of the pending state (pagehide, tab hidden, destroy).\n // Merges what other tabs wrote first, so concurrent tabs never overwrite\n // each other's events; delivered events are filtered out so they stay gone.\n private persistNow() {\n if (this.persistTimer !== undefined) {\n clearTimeout(this.persistTimer);\n this.persistTimer = undefined;\n }\n // counters first: they are written even when the queue itself is not dirty\n this.diagnostics.sync();\n if (!this.persistQueue || !this.persistDirty) return;\n this.persistDirty = false;\n\n const remote = this.storage.get(QUEUE_KEY);\n const merged = mergeQueues(\n Array.isArray(remote)\n ? this.withoutDelivered(this.withoutExpired(remote as TrackEvent[]))\n : [],\n this.queue,\n );\n this.queue = this.trimQueue(merged);\n this.storage.setRaw(QUEUE_KEY, persistedQueueJson(this.queue));\n }\n\n private trimQueue(queue: TrackEvent[] = this.queue): TrackEvent[] {\n // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent, at or under the limit nothing is removed either way\n if (queue.length <= this.maxQueue) return queue;\n const removed = queue.slice(0, queue.length - this.maxQueue);\n // every open tab holds every tab's events and trims the same ones: an event another open tab announced\n // is that tab's to count, so a dropped event is reported once, not once per open tab\n // Stryker disable next-line OptionalChaining: equivalent, the queue holds only checked events (mergeQueues), never null\n const dropped = removed.filter((e) => !this.liveTabEvents.has(e?.idempotencyKey)).length;\n if (dropped > 0) {\n this.recordDiagnostic(\"queue_full\", dropped);\n callSafely(this.options.onEventsDropped, dropped);\n }\n return queue.slice(-this.maxQueue);\n }\n\n // events another open tab just announced on the channel, with the time until which that tab sends them\n private rememberLiveTabEvents(events: TrackEvent[]) {\n const until = Date.now() + LIVE_TAB_GRACE_MS;\n for (const event of events) {\n // Stryker disable next-line OptionalChaining: equivalent, announced events are checked by mergeQueues first\n const key = event?.idempotencyKey;\n if (typeof key === \"string\" && !this.liveTabEvents.has(key)) this.liveTabEvents.set(key, until);\n }\n // Map iterates in insertion order: the oldest keys go first\n for (const key of this.liveTabEvents.keys()) {\n if (this.liveTabEvents.size <= LIVE_TAB_KEYS_MAX) break;\n this.liveTabEvents.delete(key);\n }\n }\n\n // In `independent` mode, an event another open tab announced less than LIVE_TAB_GRACE_MS ago is that\n // tab's to send. After that (the tab was closed, or it cannot reach the server either) anyone sends it.\n // The leader in `leader` mode sends everything, so it never waits.\n private leftToItsTab(event: TrackEvent): boolean {\n if (this.leader) return false;\n // Stryker disable next-line OptionalChaining: equivalent, the queue holds only checked events\n const until = this.liveTabEvents.get(event?.idempotencyKey);\n // Stryker disable next-line ConditionalExpression: equivalent, Date.now() < undefined is false\n return until !== undefined && Date.now() < until;\n }\n\n // Sends only what changed (a new event, or the keys just delivered) instead\n // of structured-cloning the whole queue on every call.\n private broadcast(message: unknown) {\n try {\n this.channel?.postMessage(message);\n } catch {\n /* ignore */\n }\n }\n\n private setupQueueSync() {\n if (typeof BroadcastChannel !== \"undefined\") {\n try {\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n } catch {\n // a browser or a sandbox that refuses the channel: tabs just do not share events\n this.channel = undefined;\n }\n }\n if (this.channel) {\n this.channel.onmessage = (e: MessageEvent) => {\n const data = e.data;\n\n if (data?.type === \"user\") {\n // another project on the same site has its own user\n if (data.key !== this.userKey) return;\n if (data.userId === null) this.userId = undefined;\n else if (typeof data.userId === \"string\") this.userId = identifiedUserId(data.userId) ?? this.userId;\n return;\n }\n\n if (data?.type === \"delivered\" && Array.isArray(data.keys)) {\n const keys = new Set<string>(data.keys as string[]);\n this.rememberDelivered(keys);\n for (const key of keys) this.liveTabEvents.delete(key);\n this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));\n return;\n }\n\n // \"queue-add\" is the delta a tab sends for one new event; \"queue-sync\"\n // carries a whole queue and is still accepted from older SDK versions\n if (\n (data?.type !== \"queue-add\" && data?.type !== \"queue-sync\") ||\n !Array.isArray(data.events)\n ) {\n return;\n }\n const announced = this.withoutDelivered(data.events as TrackEvent[]);\n this.rememberLiveTabEvents(announced);\n this.queue = mergeQueues(this.queue, announced);\n this.queue = this.trimQueue();\n };\n }\n\n if (this.persistQueue && typeof window !== \"undefined\") {\n this.offStorageQueue = listen(window, \"storage\", (e: StorageEvent) => {\n // another tab called identify() or reset(), or cleared the storage (key null)\n if (e.key === this.userKey || e.key === null) this.userId = this.loadStoredUser();\n if (e.key !== QUEUE_KEY) return;\n this.loadAndMergeQueue();\n });\n }\n }\n\n private startTimer() {\n this.timer = setInterval(() => {\n void this.flushNow(false);\n }, this.flushInterval);\n // a library timer must not keep a Node process alive on its own\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n private setupBrowserExit() {\n const handler = () => {\n if (document.visibilityState === \"hidden\") {\n this.persistNow();\n void this.flush();\n }\n };\n\n const pageHide = () => {\n // `pagehide` can fire while the page still counts as visible (a navigation, a closed tab): the request\n // must outlive the page all the same\n this.leaving = true;\n this.persistNow();\n if (this.inFlight) {\n // flush() would wait for the request in flight, which the browser cancels on unload, so the keepalive\n // send would never start\n this.sendOnLeave();\n } else {\n void this.flush();\n }\n };\n\n // a page restored from the back/forward cache is not being left any more: later sends are normal requests\n const pageShow = () => {\n this.leaving = false;\n };\n\n // `visibilitychange` only ever fires on `document`, never on `window` -\n // `pagehide` and `pageshow` are the opposite, `window`-only events.\n const offs = [\n listen(document, \"visibilitychange\", handler),\n listen(window, \"pagehide\", pageHide),\n listen(window, \"pageshow\", pageShow),\n ];\n\n this.exitHandlers.push(() => offs.forEach((off) => off()));\n }\n\n /**\n * The page is being left while a request is in flight: send what is queued at once with keepalive, without\n * waiting for that request. The events of the batch in flight go along too (after the others, as far as the\n * keepalive size allows), since the browser cancels that request on unload; if it did arrive, the server\n * drops the copies by their idempotencyKey. The queue is not changed unless the reply is seen.\n */\n private sendOnLeave() {\n // a tab that lost leadership while its request was in flight leaves the sending to the new leader\n if (this.leader && !this.leader.canSend()) return;\n\n // `sending` is set whenever a flush is in flight and the page can see it\n /* v8 ignore next */\n const inFlightKeys = new Set((this.sending ?? []).map((e) => e.idempotencyKey));\n const candidates = [\n ...this.queue.filter((e) => !inFlightKeys.has(e.idempotencyKey)),\n ...this.queue.filter((e) => inFlightKeys.has(e.idempotencyKey)),\n ];\n\n const limit = Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);\n const sentAt = new Date().toISOString();\n let bytes = utf8ByteLength(JSON.stringify({ sentAt, sdk: this.sdkInfo, events: [] }));\n const events: TrackEvent[] = [];\n const json: string[] = [];\n for (const event of candidates) {\n // the server's limit per batch; the keepalive size limit is normally reached first\n /* v8 ignore next */\n if (events.length >= MAX_BATCH_SIZE) break;\n let eventJson: string;\n try {\n eventJson = JSON.stringify(event);\n } catch {\n continue;\n }\n const total = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);\n // a smaller event further on may still fit\n if (total > limit) continue;\n events.push(event);\n json.push(eventJson);\n bytes = total;\n }\n if (!events.length) return;\n\n const head = JSON.stringify({ sentAt, sdk: this.sdkInfo });\n const body = `${head.slice(0, -1)},\"events\":[${json.join(\",\")}]}`;\n try {\n const request = this.fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n },\n body,\n keepalive: true,\n redirect: \"error\",\n });\n Promise.resolve(request).then(\n (res) => {\n discardBody(res);\n // seen only when the page stays (a bfcache restore): what was accepted is not sent again\n if (res.ok && !this.destroyed) this.removeDelivered(events);\n },\n () => undefined,\n );\n } catch {\n /* the events stay queued (and in localStorage) for the next visit */\n }\n }\n\n private setupProcessExit() {\n type Proc = {\n pid?: number;\n on: (event: string, listener: (...args: unknown[]) => void) => void;\n once: (event: string, listener: (...args: unknown[]) => void) => void;\n prependOnceListener?: (event: string, listener: (...args: unknown[]) => void) => void;\n exit?: (code?: number) => void;\n off?: (event: string, listener: (...args: unknown[]) => void) => void;\n listenerCount?: (event: string) => number;\n kill?: (pid: number, signal: string) => void;\n };\n const proc = (globalThis as { process?: Proc }).process;\n if (!proc?.on) return;\n\n // Registering any handler cancels Node's default \"exit on SIGINT/SIGTERM\". So by default the SDK behaves\n // like that default: when nobody else listens to the signal, it flushes (bounded by shutdownTimeoutMs) and\n // then re-raises the signal so the process ends as it would have without the SDK. When the app has its own\n // listener, the SDK only flushes and the app owns its shutdown. Whether others listen is decided when the\n // signal arrives, not after the flush: an app that uses `process.once` or NestJS shutdown hooks removes its\n // listener while it shuts down, and a re-raise then would cut that shutdown off. The SDK's own listener is\n // put first, so at that moment every other listener is still registered. `exitOnSignal: false` turns the\n // re-raise off (flush only).\n const exitOnSignal = this.options.exitOnSignal !== false;\n const onSignal = (signal: string) => () => {\n // a once-listener has removed itself already when emitted; removing it here too makes the count below\n // everyone else whichever way this handler was called\n proc.off?.(signal, handlers[signal]);\n const othersAtSignal = (proc.listenerCount?.(signal) ?? 0) > 0;\n void this.shutdown().finally(() => {\n if (!exitOnSignal || othersAtSignal) return;\n const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;\n if (othersListening) return;\n if (proc.pid === 1 && proc.exit) {\n // PID 1 (a container without an init) ignores a signal it has no handler for, so a re-raise would do\n // nothing: exit with the code the signal would have given\n proc.exit(128 + (signal === \"SIGINT\" ? 2 : 15));\n return;\n }\n if (proc.kill && proc.pid !== undefined) {\n proc.kill(proc.pid, signal);\n }\n });\n };\n // first in line, so the check above still sees every other listener (see the note above)\n const listenFirst = (event: string, listener: () => void) =>\n typeof proc.prependOnceListener === \"function\"\n ? proc.prependOnceListener(event, listener)\n : proc.once(event, listener);\n const handlers: Record<string, () => void> = {\n SIGINT: onSignal(\"SIGINT\"),\n SIGTERM: onSignal(\"SIGTERM\"),\n };\n\n // A script that tracks something and then simply ends: the (unref'd) timer\n // no longer keeps it alive, so deliver what is queued before it exits. The\n // pending fetch keeps the loop alive until it settles.\n const listenAgain = () => {\n if (!this.destroyed) proc.once(\"beforeExit\", onBeforeExit);\n };\n const onBeforeExit = () => {\n if (!this.queue.length) {\n // `beforeExit` fires each time the loop drains, and a script can track more events after this\n // one: keep listening\n listenAgain();\n return;\n }\n // The process is ending: bound the flush like shutdown() does, so a hanging server or a long\n // Retry-After cannot keep it alive for a minute. The deadline is lifted again afterwards in case\n // the app schedules more work after the loop drained.\n const own = this.shutdownDeadline === 0;\n if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;\n void this.flush().finally(() => {\n // the limit stays while events are still queued: a flush the timer starts later must not run without it\n // and hold the process while the server keeps failing\n if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;\n // Only after a flush that delivered everything. When events are still queued the server is not\n // taking them: trying again on every drain would keep the process alive for as long as it fails.\n if (!this.queue.length) listenAgain();\n });\n };\n\n listenFirst(\"SIGINT\", handlers.SIGINT);\n listenFirst(\"SIGTERM\", handlers.SIGTERM);\n proc.once(\"beforeExit\", onBeforeExit);\n\n this.exitHandlers.push(() => {\n proc.off?.(\"SIGINT\", handlers.SIGINT);\n proc.off?.(\"SIGTERM\", handlers.SIGTERM);\n proc.off?.(\"beforeExit\", onBeforeExit);\n });\n }\n}\n"],"m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