@edraj/sauron-browser 1.5.0 → 1.6.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils.ts","../src/identity.ts","../src/context.ts","../src/dsn.ts","../src/envelope.ts","../src/integrations/instrument.ts","../src/integrations/console.ts","../src/integrations/dom.ts","../src/integrations/fetch.ts","../src/screen.ts","../src/stacktrace/parse.ts","../src/api/capture.ts","../src/integrations/globalHandlers.ts","../src/integrations/history.ts","../src/scope.ts","../src/workflow.ts","../src/api/product.ts","../src/integrations/performance.ts","../src/integrations/xhr.ts","../src/transport/beacon.ts","../src/transport/compress.ts","../src/transport/queue.ts","../src/transport/transport.ts","../src/client.ts","../src/api/breadcrumbs.ts","../src/index.ts"],"names":["g","init","anonymousId","sessionId","resolveUrl","resolveMethod","flush","captureException","captureMessage","track","identify","trackTransaction","setScreen","getScreen","startWorkflow","endWorkflow","cancelWorkflow","getWorkflow","addBreadcrumb"],"mappings":";;;;;;;;;AAGO,IAAM,QAAA,GAAW;AACjB,IAAM,WAAA,GAAc;AAGpB,SAAS,SAAA,GAA+B;AAC7C,EAAA,OAAO,UAAA;AACT;AAOA,SAAS,SAAA,GAAoC;AAC3C,EAAA,MAAMA,KAAI,SAAA,EAAU;AACpB,EAAA,OAAOA,EAAAA,CAAE,MAAA;AACX;AAGO,SAAS,MAAA,GAAiB;AAC/B,EAAA,MAAM,IAAI,SAAA,EAAU;AACpB,EAAA,IAAI,CAAA,IAAK,OAAO,CAAA,CAAE,UAAA,KAAe,UAAA,EAAY;AAC3C,IAAA,OAAO,EAAE,UAAA,EAAW;AAAA,EACtB;AACA,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAC/B,EAAA,IAAI,CAAA,IAAK,OAAO,CAAA,CAAE,eAAA,KAAoB,UAAA,EAAY;AAChD,IAAA,CAAA,CAAE,gBAAgB,KAAK,CAAA;AA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gBAAA,EAAAM,iBAAAA;AAAA,EACA,cAAA,EAAAC,eAAAA;AAAA,EACA,KAAA,EAAAC,MAAAA;AAAA,EACA,gBAAA,EAAAE,iBAAAA;AAAA,EACA,QAAA,EAAAD,SAAAA;AAAA,EACA,aAAA,EAAAQ,cAAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA,EAAAN,UAAAA;AAAA,EACA,SAAA,EAAAC,UAAAA;AAAA,EACA,aAAA,EAAAC,cAAAA;AAAA,EACA,WAAA,EAAAC,YAAAA;AAAA,EACA,cAAA,EAAAC,eAAAA;AAAA,EACA,WAAA,EAAAC,YAAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF;AAEA,IAAO,aAAA,GAAQ","file":"index.cjs","sourcesContent":["/** Small dependency-free helpers shared across the SDK. */\n\n/** SDK identity, embedded in every envelope header. */\nexport const SDK_NAME = 'sauron.javascript';\nexport const SDK_VERSION = '1.5.0';\n\n/** The ambient global, regardless of environment (window / self / global). */\nexport function getGlobal(): typeof globalThis {\n return globalThis;\n}\n\ninterface CryptoLike {\n randomUUID?: () => string;\n getRandomValues?: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nfunction getCrypto(): CryptoLike | undefined {\n const g = getGlobal() as { crypto?: CryptoLike };\n return g.crypto;\n}\n\n/** RFC-4122 v4 UUID, using Web Crypto when available. */\nexport function uuidv4(): string {\n const c = getCrypto();\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n // Set version (4) and variant (10xx) bits.\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex: string[] = [];\n for (let i = 0; i < 16; i++) hex.push(bytes[i].toString(16).padStart(2, '0'));\n const s = hex.join('');\n return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;\n}\n\n/** Current time as an ISO-8601 UTC string, e.g. `2026-07-12T10:30:00.123Z`. */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\n/**\n * `JSON.stringify` that never throws: strips circular references, functions and\n * coerces bigint to string. Returns `\"{}\"` on catastrophic failure.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>();\n try {\n return JSON.stringify(value, (_key, val) => {\n if (typeof val === 'bigint') return val.toString();\n if (typeof val === 'function') return undefined;\n if (typeof val === 'object' && val !== null) {\n if (seen.has(val)) return '[Circular]';\n seen.add(val);\n }\n return val;\n });\n } catch {\n return '{}';\n }\n}\n\n/** UTF-8 byte length of a string. */\nexport function byteLength(s: string): number {\n if (typeof TextEncoder !== 'undefined') {\n return new TextEncoder().encode(s).length;\n }\n let len = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) len += 1;\n else if (c < 0x800) len += 2;\n else if (c >= 0xd800 && c <= 0xdbff) {\n len += 4;\n i++; // surrogate pair\n } else len += 3;\n }\n return len;\n}\n\n/**\n * Full-jitter exponential backoff, capped. Attempt 0 => up to `baseMs`,\n * attempt n => up to `min(capMs, baseMs * 2^n)`, then a uniform random point\n * in `[0, that]`.\n */\nexport function computeBackoff(attempt: number, baseMs = 1000, capMs = 30000): number {\n const ceiling = Math.min(capMs, baseMs * Math.pow(2, Math.max(0, attempt)));\n return Math.round(Math.random() * ceiling);\n}\n\n/** Clamp a number into `[min, max]`. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\n/** A tiny logger gated on `debug`. */\nexport function makeLogger(debug: boolean): {\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n} {\n const noop = (): void => {};\n if (!debug || typeof console === 'undefined') {\n return { log: noop, warn: noop };\n }\n return {\n log: (...args: unknown[]) => console.log('[sauron]', ...args),\n warn: (...args: unknown[]) => console.warn('[sauron]', ...args),\n };\n}\n\n/**\n * Largest serialized `extra` a single transaction may carry, in bytes.\n *\n * Transactions are the highest-volume signal and they ship in BATCHED\n * envelopes, so one oversized payload does not fail alone — ingest rejects the\n * whole envelope past `INGEST_MAX_BODY_BYTES` (1 MiB by default) and every\n * unrelated span batched with it is lost. Since the motivating use of\n * transaction `extra` is request and response bodies, that is not a remote\n * hazard.\n */\nexport const MAX_TRANSACTION_EXTRA_BYTES = 16 * 1024;\n\n/**\n * Cap a transaction's `extra`, substituting a marker when it is too large.\n *\n * Replaces the WHOLE map rather than trimming keys: a half-written JSON value\n * is worse than an honest marker, and per-key trimming would make the result\n * depend on key iteration order, which differs across the five SDKs. The\n * marker is deliberately readable on the dashboard — `_truncated` says data\n * was dropped rather than silently serving a short object that looks complete.\n *\n * Returns the input unchanged when it fits. A value that cannot be serialized\n * at all (a cycle, a BigInt) is replaced by the same marker with `_bytes: -1`,\n * because the alternative is throwing from inside `trackTransaction` — and an\n * SDK that crashes the app it is measuring is worse than one that drops a\n * payload.\n */\nexport function capTransactionExtra(\n extra: Record<string, unknown>,\n maxBytes = MAX_TRANSACTION_EXTRA_BYTES,\n): Record<string, unknown> {\n let bytes: number;\n try {\n const json = JSON.stringify(extra);\n if (json === undefined) return { _truncated: true, _bytes: -1 };\n // `Blob`/`Buffer` are not available everywhere this SDK runs; UTF-8 byte\n // length is what the wire actually costs, so it is computed rather than\n // approximated by `json.length` (which undercounts every non-ASCII byte —\n // exactly what a response body full of user text contains).\n bytes = utf8Length(json);\n } catch {\n return { _truncated: true, _bytes: -1 };\n }\n if (bytes <= maxBytes) return extra;\n return { _truncated: true, _bytes: bytes };\n}\n\n/** UTF-8 byte length of a string, without depending on `TextEncoder`. */\nfunction utf8Length(s: string): number {\n let n = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) n += 1;\n else if (c < 0x800) n += 2;\n else if (c >= 0xd800 && c <= 0xdbff) {\n // A surrogate PAIR is one 4-byte code point; advance past its low half\n // so it is not counted twice.\n n += 4;\n i++;\n } else n += 3;\n }\n return n;\n}\n","/**\n * Stable device + session identity.\n *\n * - `device_id` is persisted in `localStorage` (`sauron.device_id`) so it\n * survives reloads and tabs — the backend uses it as the durable device\n * identity (`context.device.device_id`).\n * - `session_id` is persisted in `sessionStorage` (`sauron.session_id`) so it is\n * shared across a tab's page loads but starts fresh for a new browsing\n * session. It is attached to every event, error and transaction item.\n * - `last_identified` is persisted in `localStorage` (`sauron.last_identified`)\n * as a short one-way digest (`hashIdentity`) of the id passed to\n * `identify()` — never the identifier itself — so a login by a DIFFERENT\n * user than last time can be detected even when the app never wired\n * `reset()` on logout — see `SauronClient.prepareIdentify`.\n *\n * All degrade gracefully: with no writable Web Storage (SSR, private mode,\n * blocked cookies) we fall back to a per-process id generated once in memory.\n */\n\nimport { uuidv4 } from './utils.js';\n\n/** localStorage key holding the durable device id. */\nexport const DEVICE_ID_KEY = 'sauron.device_id';\n/** sessionStorage key holding the per-session id. */\nexport const SESSION_ID_KEY = 'sauron.session_id';\n/**\n * localStorage key holding the durable anonymous id.\n *\n * It used to live in a field on the client, re-minted on every page load, so\n * `track()` sent a new `distinct_id` each time and active users for any web app\n * counted PAGE LOADS, not people — a systematic 5-10x inflation, all of it\n * landing in the guest half of the report.\n *\n * Persisting it is a retention and consent consequence, not just an\n * implementation detail: the anon id becomes a durable first-party identifier\n * stored on the user's terminal. It is also why `reset()` exists — see\n * `SauronClient.reset`.\n */\nexport const ANON_ID_KEY = 'sauron.anon_id';\n/**\n * localStorage key holding a short one-way digest (`hashIdentity`) of the id\n * of the last user who called `identify()` — never the identifier itself,\n * which is very often personally identifying (an email, a username) and would\n * otherwise become a second, durable, plaintext copy of it.\n *\n * Exists so a login by a DIFFERENT user can be detected on a device where the\n * app never wired `reset()` on logout. Without it, person B's anonymous\n * activity keeps flowing under person A's already-burned alias, and the server\n * resolves it to A — permanently, and with no client-side symptom.\n */\nexport const LAST_IDENTIFIED_KEY = 'sauron.last_identified';\n\n/**\n * Format tag prefixed to the stored `sauron.last_identified` value, as\n * `<tag>:<digest>`.\n *\n * `hashIdentity`'s output has already changed shape once (8 hex digits → 16),\n * and an untagged store cannot tell \"a digest in a format I no longer\n * produce\" from \"a digest of a different person\". Both read as a SWITCH, so a\n * widening would mint a fresh anonymous id and rotate the session for every\n * returning user on their next `identify()` — once, silently, with no error\n * and nothing in the data saying why guest counts moved.\n *\n * With the tag, an unrecognised (or absent) prefix reads as **no previous\n * identity**, which is the safe reading: the first identify on a device is\n * never a switch, so nothing is rotated and the next write re-tags the entry\n * in the current format. The cost of guessing wrong that way is one missed\n * switch on one device — the same exposure as before anything was persisted\n * at all — instead of a fleet-wide rotation.\n *\n * Byte-compatible with the Flutter SDK, which writes the identical\n * `<tag>:<digest>` string under the same key (see\n * `LastIdentifiedStore` in `sdks/flutter/lib/src/context/last_identified_store.dart`).\n * The tag is on the STORED VALUE, not on `hashIdentity` itself, so the\n * cross-SDK digest golden is unaffected by it.\n */\nexport const LAST_IDENTIFIED_FORMAT = 'v1';\n\n/** Wrap a digest in the current storage format. */\nfunction encodeLastIdentified(digest: string): string {\n return `${LAST_IDENTIFIED_FORMAT}:${digest}`;\n}\n\n/**\n * Unwrap a stored value, or `null` if it is not in a format this build\n * understands — which callers must treat as \"nobody has identified here yet\".\n */\nfunction decodeLastIdentified(raw: string | null): string | null {\n if (raw === null) return null;\n const sep = raw.indexOf(':');\n // No separator at all is the pre-tag format; a different tag is a newer (or\n // older) build's. Both are unreadable here, and both fail to \"no previous\n // identity\" rather than to a false switch.\n if (sep < 0 || raw.slice(0, sep) !== LAST_IDENTIFIED_FORMAT) return null;\n const digest = raw.slice(sep + 1);\n return digest === '' ? null : digest;\n}\n\n/** One 32-bit FNV-1a pass, returned as an 8-hex-digit string. */\nfunction fnv1a32(s: string): string {\n let h = 0x811c9dc5; // FNV-1a 32-bit offset basis\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193); // FNV-1a 32-bit prime\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Two decorrelated 32-bit FNV-1a passes concatenated into a 16-hex-digit\n * (64-bit) digest.\n *\n * `last_identified` only ever needs an EQUALITY check (\"is this the same\n * person as last time\"), comparing exactly one previous digest against one\n * current digest — never a set lookup — so the birthday bound doesn't apply\n * here: a collision is ~2^-64 for one consecutive-login pair, and it fails\n * OPEN to the pre-task behaviour for that one pair (a missed switch), never\n * worse.\n *\n * The second pass is decorrelated by INPUT — a `'\\x01'`-prefixed copy — not\n * by a different offset basis/prime: two FNV-1a passes over identical bytes\n * with the same constants are structurally correlated, so changing only the\n * basis buys far less independence than it looks like it does.\n *\n * NOT a security boundary, and widening this does not change that: this is\n * an UNKEYED hash over what can be a low-entropy space (an email address),\n * so it is a confirmation oracle, not a secret — anyone with local read\n * access and a guess can verify it instantly by hashing the guess and\n * comparing. It exists only so `sauron.last_identified` isn't a second\n * plaintext copy of the app's user id, not to keep that id confidential.\n * `crypto.subtle` would be equally an oracle here (still unkeyed) and is\n * async, so it wouldn't buy anything worth the API becoming asynchronous.\n */\nexport function hashIdentity(id: string): string {\n return fnv1a32(id) + fnv1a32('\\x01' + id);\n}\n\n/** The minimal Web Storage surface we need (a subset of `Storage`). */\ninterface WebStorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** Return a named Web Storage area if present and writable, else `null`. */\nfunction webStorage(name: 'localStorage' | 'sessionStorage'): WebStorageLike | null {\n try {\n const s = (globalThis as Record<string, unknown>)[name] as WebStorageLike | undefined;\n if (!s) return null;\n const probe = '__sauron_probe__';\n s.setItem(probe, '1');\n s.removeItem(probe);\n return s;\n } catch {\n // Storage disabled (private mode, blocked cookies, SSR, ...).\n return null;\n }\n}\n\n/**\n * Return the persisted id under `key`, generating and persisting a fresh v4\n * uuid when absent. `cached` short-circuits repeated lookups and doubles as the\n * in-memory fallback when no storage is available.\n */\nfunction persistentId(cached: string | null, storage: WebStorageLike | null, key: string): string {\n if (cached) return cached;\n if (storage) {\n try {\n const existing = storage.getItem(key);\n if (existing) return existing;\n } catch {\n /* fall through and generate */\n }\n }\n const fresh = uuidv4();\n if (storage) {\n try {\n storage.setItem(key, fresh);\n } catch {\n /* best effort — degrade to the in-memory value returned below */\n }\n }\n return fresh;\n}\n\nlet deviceId: string | null = null;\nlet sessionId: string | null = null;\nlet anonymousId: string | null = null;\nlet lastIdentified: string | null = null;\n\n/** The stable device id (persisted in localStorage; per-process fallback). */\nexport function getDeviceId(): string {\n deviceId = persistentId(deviceId, webStorage('localStorage'), DEVICE_ID_KEY);\n return deviceId;\n}\n\n/** The current session id (persisted in sessionStorage; in-memory fallback). */\nexport function getSessionId(): string {\n sessionId = persistentId(sessionId, webStorage('sessionStorage'), SESSION_ID_KEY);\n return sessionId;\n}\n\n/**\n * Mint and persist a fresh session id.\n *\n * `reset()` calls this so a `sessions` row never spans two people. The server's\n * `bump_session` sets `distinct_id = COALESCE(EXCLUDED.distinct_id, …)`, i.e.\n * last-write-wins, so without rotation one session row records only whichever\n * of two consecutive users wrote last.\n */\nexport function rotateSessionId(): string {\n sessionId = null;\n const storage = webStorage('sessionStorage');\n if (storage) {\n try {\n storage.removeItem(SESSION_ID_KEY);\n } catch {\n /* best effort */\n }\n }\n return getSessionId();\n}\n\n/** The stable anonymous id (persisted in localStorage; per-process fallback). */\nexport function getAnonymousId(): string {\n if (anonymousId) return anonymousId;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n const existing = storage.getItem(ANON_ID_KEY);\n if (existing) {\n anonymousId = existing;\n return anonymousId;\n }\n } catch {\n /* fall through and generate */\n }\n }\n const fresh = `anon_${uuidv4()}`;\n if (storage) {\n try {\n storage.setItem(ANON_ID_KEY, fresh);\n } catch {\n /* best effort — degrade to the in-memory value */\n }\n }\n anonymousId = fresh;\n return anonymousId;\n}\n\n/**\n * Mint and persist a fresh anonymous id.\n *\n * MUST be reachable from application code. A persisted anon id plus\n * `process_identify`'s `identities(app_id, alias_id, distinct_id)` insert means\n * one `identify()` permanently binds this browser profile to a named user\n * server-side — so on a kiosk or a shared machine, person B's anonymous\n * activity would be aliased to person A's account, forever, with no escape\n * hatch.\n */\nexport function resetAnonymousId(): string {\n anonymousId = null;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.removeItem(ANON_ID_KEY);\n } catch {\n /* best effort */\n }\n }\n return getAnonymousId();\n}\n\n/**\n * The digest of the last user who identified on this device, or null.\n *\n * Falls back to the in-memory value not only when storage is absent/throws,\n * but also when storage IS present and simply has nothing under the key —\n * that also covers the case where `setLastIdentified`'s own write silently\n * failed (e.g. quota), so the value it set in memory is still the only place\n * this identify() is recorded at all.\n *\n * Returns the bare DIGEST: the `<tag>:` prefix is a storage concern and never\n * reaches the comparison in `SauronClient.prepareIdentify`. A value whose tag\n * this build does not recognise comes back `null` — see\n * `LAST_IDENTIFIED_FORMAT`.\n */\nexport function getLastIdentified(): string | null {\n const storage = webStorage('localStorage');\n if (!storage) return decodeLastIdentified(lastIdentified);\n try {\n const stored = storage.getItem(LAST_IDENTIFIED_KEY);\n return decodeLastIdentified(stored ?? lastIdentified);\n } catch {\n return decodeLastIdentified(lastIdentified);\n }\n}\n\n/**\n * Record the digest of the user who just identified.\n *\n * The in-memory copy holds the ENCODED value, not the bare digest, so the\n * storage-absent path and the storage-present path decode through exactly the\n * same function — a memory fallback that skipped the tag would be a second\n * format, and the two would drift.\n */\nexport function setLastIdentified(id: string): void {\n const encoded = encodeLastIdentified(id);\n lastIdentified = encoded;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.setItem(LAST_IDENTIFIED_KEY, encoded);\n } catch {\n /* best effort — the in-memory value above still applies this session */\n }\n }\n}\n\n/** Forget the last identified digest (called by `reset()`). */\nexport function clearLastIdentified(): void {\n lastIdentified = null;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.removeItem(LAST_IDENTIFIED_KEY);\n } catch {\n /* best effort */\n }\n }\n}\n\n/** Drop the in-memory memoization (used by tests and teardown). */\nexport function resetIdentity(): void {\n deviceId = null;\n sessionId = null;\n anonymousId = null;\n lastIdentified = null;\n}\n","import { getDeviceId } from './identity.js';\nimport type { AppContext, Context, DeviceContext, OsContext, RuntimeContext, UserContext } from './types.js';\n\n/**\n * Best-effort environment detection from `navigator`. All of this is fuzzy by\n * nature (UA freezing, spoofing, non-browser hosts) so every field degrades to\n * `null` rather than guessing wrong in a way that breaks the wire contract.\n */\n\ninterface NavigatorLike {\n userAgent?: string;\n platform?: string;\n userAgentData?: { platform?: string };\n}\n\nfunction getNavigator(): NavigatorLike | undefined {\n const g = globalThis as { navigator?: NavigatorLike };\n return g.navigator;\n}\n\nfunction detectOs(ua: string): OsContext {\n // Windows\n let m = ua.match(/Windows NT ([\\d.]+)/);\n if (m) return { name: 'Windows', version: m[1] };\n // iOS (before macOS, since iPad UAs can contain \"Mac OS X\")\n m = ua.match(/iPhone OS (\\d+[_\\d]*)/) || ua.match(/CPU OS (\\d+[_\\d]*) like Mac/);\n if (m) return { name: 'iOS', version: m[1].replace(/_/g, '.') };\n // macOS\n m = ua.match(/Mac OS X (\\d+[_\\d]*)/);\n if (m) return { name: 'macOS', version: m[1].replace(/_/g, '.') };\n // Android\n m = ua.match(/Android ([\\d.]+)/);\n if (m) return { name: 'Android', version: m[1] };\n if (/Linux/.test(ua)) return { name: 'Linux', version: null };\n if (/CrOS/.test(ua)) return { name: 'Chrome OS', version: null };\n return { name: null, version: null };\n}\n\nfunction detectRuntime(ua: string): RuntimeContext {\n // Order matters: Edge/Opera masquerade as Chrome; Chrome masquerades as Safari.\n let m = ua.match(/Edg(?:e|A|iOS)?\\/([\\d.]+)/);\n if (m) return { name: 'Edge', version: major(m[1]) };\n m = ua.match(/OPR\\/([\\d.]+)/) || ua.match(/Opera\\/([\\d.]+)/);\n if (m) return { name: 'Opera', version: major(m[1]) };\n m = ua.match(/Firefox\\/([\\d.]+)/);\n if (m) return { name: 'Firefox', version: major(m[1]) };\n m = ua.match(/Chrome\\/([\\d.]+)/);\n if (m) return { name: 'Chrome', version: major(m[1]) };\n m = ua.match(/Version\\/([\\d.]+).*Safari/);\n if (m) return { name: 'Safari', version: major(m[1]) };\n if (/Safari/.test(ua)) return { name: 'Safari', version: null };\n return { name: null, version: null };\n}\n\nfunction detectDevice(nav: NavigatorLike | undefined, ua: string): DeviceContext {\n const platform = nav?.userAgentData?.platform ?? nav?.platform ?? '';\n let family: string | null = null;\n if (/Mac|iPhone|iPad|iPod/.test(platform) || /iPhone|iPad|Macintosh/.test(ua)) {\n family = 'Apple';\n } else if (/Win/.test(platform) || /Windows/.test(ua)) {\n family = 'Microsoft';\n } else if (/Android/.test(ua)) {\n family = 'Google';\n } else if (/Linux/.test(platform) || /Linux/.test(ua)) {\n family = 'Linux';\n }\n return { device_id: getDeviceId(), family, model: null, arch: null };\n}\n\n/** Take the leading major version component of a dotted version string. */\nfunction major(version: string): string {\n const dot = version.indexOf('.');\n return dot === -1 ? version : version.slice(0, dot);\n}\n\n/** Derive `app.version` from a `name@version` release string. */\nfunction appFromRelease(release: string | null): AppContext {\n if (!release) return { version: null, build: null };\n const at = release.lastIndexOf('@');\n const version = at === -1 ? release : release.slice(at + 1);\n return { version: version || null, build: null };\n}\n\n/**\n * Build the environment portion of the context (everything except the user).\n * The user is merged in by the client from its `Scope`.\n */\nexport function detectContext(release: string | null): Omit<Context, 'user'> {\n const nav = getNavigator();\n const ua = nav?.userAgent ?? '';\n return {\n device: detectDevice(nav, ua),\n os: detectOs(ua),\n app: appFromRelease(release),\n runtime: detectRuntime(ua),\n };\n}\n\n/** Combine the detected environment context with the current user. */\nexport function buildContext(release: string | null, user: UserContext): Context {\n return { ...detectContext(release), user };\n}\n","/**\n * DSN parsing.\n *\n * A DSN looks like `https://<public_key>@<host>/<project_id>`. The public key\n * is a non-secret, write-only credential — it is safe to ship in client code.\n */\n\nexport interface Dsn {\n /** The raw DSN string (embedded verbatim into the envelope header). */\n raw: string;\n publicKey: string;\n /** `host:port` — used for the infinite-loop denylist. */\n host: string;\n /** Hostname without port. */\n hostname: string;\n /** `https` or `http` (no trailing colon). */\n protocol: string;\n projectId: string;\n /** `POST` target for the primary transport. */\n envelopeUrl: string;\n /** `POST` target for the `sendBeacon` fallback (key in query string). */\n beaconUrl: string;\n}\n\nexport class DsnError extends Error {\n constructor(message: string) {\n super(`[sauron] invalid DSN: ${message}`);\n this.name = 'DsnError';\n }\n}\n\n/** Parse and validate a DSN, deriving the transport URLs. */\nexport function parseDsn(dsn: string): Dsn {\n if (typeof dsn !== 'string' || dsn.length === 0) {\n throw new DsnError('DSN must be a non-empty string');\n }\n\n let url: URL;\n try {\n url = new URL(dsn);\n } catch {\n throw new DsnError(`could not parse \"${dsn}\"`);\n }\n\n const protocol = url.protocol.replace(/:$/, '');\n if (protocol !== 'http' && protocol !== 'https') {\n throw new DsnError(`unsupported protocol \"${protocol}\"`);\n }\n\n const publicKey = url.username;\n if (!publicKey) {\n throw new DsnError('missing public key (the \"user\" part of the URL)');\n }\n if (url.password) {\n throw new DsnError('DSN must not contain a secret (password component)');\n }\n\n const host = url.host; // includes port when present\n const hostname = url.hostname;\n if (!host) {\n throw new DsnError('missing host');\n }\n\n const projectId = url.pathname.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (!projectId) {\n throw new DsnError('missing project id (the path segment)');\n }\n\n const base = `${protocol}://${host}/api/${projectId}/envelope`;\n const beaconUrl = `${base}?k=${encodeURIComponent(publicKey)}`;\n\n return {\n raw: dsn,\n publicKey,\n host,\n hostname,\n protocol,\n projectId,\n envelopeUrl: base,\n beaconUrl,\n };\n}\n","import type { Context, Envelope, EnvelopeHeader, EnvelopeItem } from './types.js';\n\n/**\n * Assemble a canonical envelope. This is intentionally trivial — the shape is\n * the contract, so keep it a pure, side-effect-free constructor that mirrors\n * the golden JSON exactly (header, context, items, in that order).\n */\nexport function buildEnvelope(\n header: EnvelopeHeader,\n context: Context,\n items: EnvelopeItem[],\n): Envelope {\n return {\n header,\n context,\n items,\n };\n}\n","/**\n * Instrumentation primitives shared by every integration:\n *\n * - a reentrancy guard so SDK-internal work never triggers its own breadcrumbs\n * (e.g. the transport's own `fetch` must not create a \"fetch\" breadcrumb that\n * schedules another send — an infinite loop),\n * - a DSN-host denylist (belt-and-suspenders alongside the guard),\n * - an idempotent \"already wrapped\" tag so double-`init` doesn't stack wrappers,\n * - a patch registry so `close()` can restore every original.\n */\n\nconst WRAPPED = '__sauron_wrapped__';\n\nlet internalDepth = 0;\n\n/** Enter SDK-internal execution (breadcrumb capture is suppressed while > 0). */\nexport function beginInternal(): void {\n internalDepth++;\n}\n\n/** Leave SDK-internal execution. */\nexport function endInternal(): void {\n internalDepth = Math.max(0, internalDepth - 1);\n}\n\n/** Run `fn` with the reentrancy guard held (synchronous scope only). */\nexport function withInternal<T>(fn: () => T): T {\n beginInternal();\n try {\n return fn();\n } finally {\n endInternal();\n }\n}\n\n/** True while SDK-internal code is running. */\nexport function isInternal(): boolean {\n return internalDepth > 0;\n}\n\nlet dsnHost: string | null = null;\n\n/** Register the DSN host (`host:port`) used for the request denylist. */\nexport function setDsnHost(host: string | null): void {\n dsnHost = host;\n}\n\n/** True when `rawUrl` targets the DSN host — such requests must be ignored. */\nexport function isDsnRequest(rawUrl: string): boolean {\n if (!dsnHost || !rawUrl) return false;\n try {\n const base = (globalThis as { location?: { href?: string } }).location?.href;\n const u = new URL(rawUrl, base);\n return u.host === dsnHost;\n } catch {\n return false;\n }\n}\n\n/** Tag a wrapper function so we never wrap it twice. */\nexport function markWrapped<T>(fn: T): T {\n try {\n (fn as Record<string, unknown>)[WRAPPED] = true;\n } catch {\n /* frozen function — best effort */\n }\n return fn;\n}\n\n/** True when `fn` was produced by {@link markWrapped}. */\nexport function isWrapped(fn: unknown): boolean {\n if (fn === null || (typeof fn !== 'function' && typeof fn !== 'object')) return false;\n return (fn as Record<string, unknown>)[WRAPPED] === true;\n}\n\ntype Unpatch = () => void;\n\nconst patches: Array<{ name: string; unpatch: Unpatch }> = [];\n\n/** Register an undo function to be run by {@link unpatchAll}. */\nexport function registerPatch(name: string, unpatch: Unpatch): void {\n patches.push({ name, unpatch });\n}\n\n/** Restore every patched global to its original, in reverse order. */\nexport function unpatchAll(): void {\n while (patches.length) {\n const p = patches.pop();\n try {\n p?.unpatch();\n } catch {\n /* ignore restore failures */\n }\n }\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport type { Level } from '../types.js';\nimport { isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\ntype ConsoleMethod = 'log' | 'info' | 'warn' | 'error' | 'debug';\nconst METHODS: ConsoleMethod[] = ['log', 'info', 'warn', 'error', 'debug'];\n\nfunction toLevel(method: ConsoleMethod): Level {\n switch (method) {\n case 'warn':\n return 'warning';\n case 'error':\n return 'error';\n case 'debug':\n return 'debug';\n default:\n return 'info';\n }\n}\n\nfunction argToString(arg: unknown): string {\n if (typeof arg === 'string') return arg;\n if (arg instanceof Error) return `${arg.name}: ${arg.message}`;\n try {\n return JSON.stringify(arg);\n } catch {\n return String(arg);\n }\n}\n\n/** Record a breadcrumb for each `console.*` call while leaving output intact. */\nexport function installConsole(): void {\n const consoleObj = (globalThis as { console?: Console }).console;\n if (!consoleObj) return;\n const c = consoleObj as unknown as Record<string, unknown>;\n\n for (const method of METHODS) {\n const original = c[method];\n if (typeof original !== 'function' || isWrapped(original)) continue;\n const originalFn = original as (...args: unknown[]) => unknown;\n\n const wrapped = markWrapped(function sauronConsole(this: unknown, ...args: unknown[]): unknown {\n if (!isInternal()) {\n withInternal(() => {\n try {\n addBreadcrumb({\n type: 'default',\n category: 'console',\n level: toLevel(method),\n message: args.map(argToString).join(' ').slice(0, 512),\n data: { arguments: args.length },\n });\n } catch {\n /* never break the app's console */\n }\n });\n }\n return originalFn.apply(this, args);\n });\n\n c[method] = wrapped;\n registerPatch(`console.${method}`, () => {\n c[method] = originalFn;\n });\n }\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { isInternal, registerPatch, withInternal } from './instrument.js';\n\n/**\n * Build a stable CSS-ish selector `tag#id.class` for a clicked element.\n * NEVER serializes `innerText`/attribute values — that would leak PII.\n */\nexport function domSelector(el: unknown): string | null {\n try {\n const node = el as { tagName?: string; id?: string; className?: unknown } | null;\n if (!node || typeof node.tagName !== 'string') return null;\n\n let selector = node.tagName.toLowerCase();\n if (node.id && typeof node.id === 'string') {\n selector += `#${node.id}`;\n }\n if (typeof node.className === 'string' && node.className.trim()) {\n const classes = node.className.trim().split(/\\s+/).slice(0, 3);\n if (classes.length) selector += `.${classes.join('.')}`;\n }\n return selector;\n } catch {\n return null;\n }\n}\n\n/** Record a `ui.click` breadcrumb (selector only, never text) for each click. */\nexport function installDom(): void {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc || typeof doc.addEventListener !== 'function') return;\n\n const handler = (event: Event): void => {\n if (isInternal()) return;\n const selector = domSelector(event.target);\n if (!selector) return;\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'ui.click',\n level: 'info',\n message: selector,\n data: null,\n });\n });\n };\n\n const options = { capture: true, passive: true } as AddEventListenerOptions;\n doc.addEventListener('click', handler, options);\n registerPatch('dom.click', () => {\n try {\n doc.removeEventListener('click', handler, options);\n } catch {\n /* ignore */\n }\n });\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { nowIso } from '../utils.js';\nimport { isDsnRequest, isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\nfunction resolveUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const withUrl = input as { url?: string; href?: string };\n if (typeof withUrl.url === 'string') return withUrl.url;\n if (typeof withUrl.href === 'string') return withUrl.href;\n }\n return String(input);\n}\n\nfunction resolveMethod(input: unknown, init: unknown): string {\n const fromInit = (init as { method?: string } | undefined)?.method;\n const fromReq = (input as { method?: string } | null)?.method;\n return String(fromInit ?? fromReq ?? 'GET').toUpperCase();\n}\n\nfunction addFetchBreadcrumb(\n method: string,\n url: string,\n status: number | null,\n startedAt: string,\n): void {\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'fetch',\n level: status !== null && status >= 400 ? 'warning' : 'info',\n message: `${method} ${url}`,\n timestamp: startedAt,\n data: { method, url, status_code: status },\n });\n });\n}\n\n/**\n * Wrap `fetch` to leave a breadcrumb per request. Requests to the DSN host (our\n * own ingest traffic) and requests made while SDK code runs are skipped — this\n * is what prevents an infinite send→breadcrumb→send loop.\n */\nexport function installFetch(): void {\n const g = globalThis as { fetch?: typeof fetch };\n const original = g.fetch;\n if (typeof original !== 'function' || isWrapped(original)) return;\n\n const wrapped = markWrapped(function sauronFetch(\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n const url = resolveUrl(input);\n const shouldRecord = !isInternal() && !isDsnRequest(url);\n const method = resolveMethod(input, init);\n const startedAt = nowIso();\n\n const promise = original.call(this, input as RequestInfo, init);\n\n if (shouldRecord) {\n promise.then(\n (res) => addFetchBreadcrumb(method, url, res?.status ?? null, startedAt),\n () => addFetchBreadcrumb(method, url, null, startedAt),\n );\n }\n return promise;\n });\n\n g.fetch = wrapped;\n registerPatch('fetch', () => {\n g.fetch = original;\n });\n}\n","/**\n * Current-screen state. The SDK stamps this on every event/exception and\n * auto-emits a `$screen` view event when it changes (see api/product.ts).\n */\nlet currentScreen: string | null = null;\n\n/** The current screen name, or null if none set. */\nexport function getScreen(): string | null {\n return currentScreen;\n}\n\n/** Set the current screen. Returns true iff the value actually changed. */\nexport function setScreenState(name: string | null): boolean {\n if (name === currentScreen) return false;\n currentScreen = name;\n return true;\n}\n\n/** Drop the in-memory value (tests + teardown). */\nexport function resetScreen(): void {\n currentScreen = null;\n}\n","import type { Frame } from '../types.js';\n\n/**\n * Cross-browser `Error.stack` parser.\n *\n * Produces neutral frames with the CRASHING FRAME LAST (raw stacks list the\n * crash site first, so the parsed list is reversed). Depth is capped at\n * {@link MAX_FRAMES}, keeping the frames nearest the crash. No symbolication is\n * performed — line/column/filename are passed through verbatim.\n */\n\nexport const MAX_FRAMES = 50;\n\n/** V8 / Chrome / Node / Edge: ` at fn (file:line:col)` or ` at file:line:col`. */\nconst V8_RE =\n /^\\s*at (?:(.+?) )?\\(?((?:[a-z][\\w.+-]*:\\/\\/)?[^\\s()]+?):(\\d+):(\\d+)\\)?\\s*$/i;\n\n/**\n * Firefox / Safari: `fn@file:line:col`, `@file:line:col`, `fn/<@file:line:col`.\n * The function name may contain spaces (Safari's `global code`, `module code`).\n */\nconst GECKO_RE =\n /^\\s*(?:([^@]*?)@)?((?:[a-z][\\w.+-]*:\\/\\/)?[^@\\s]+?):(\\d+):(\\d+)\\s*$/i;\n\nfunction cleanFunction(fn: string | undefined): string | null {\n if (!fn) return null;\n let name = fn.trim();\n // V8 async / constructor prefixes and Safari's trailing markers.\n name = name.replace(/^async\\s+/, '').replace(/^new\\s+/, 'new ');\n name = name.replace(/\\s+\\[as .+\\]$/, '');\n if (name === '<anonymous>' || name === '') return null;\n return name;\n}\n\n/**\n * Heuristic for whether a frame belongs to first-party (\"in app\") code:\n * same-origin URLs and bare/relative paths are in-app; cross-origin URLs\n * (typically CDN or third-party scripts) and internal frames are not.\n */\nexport function isInAppFrame(filename: string | null): boolean {\n if (!filename) return false;\n if (filename === '<anonymous>' || filename.startsWith('node:') || filename.startsWith('internal/')) {\n return false;\n }\n const hasProtocol = /^[a-z][\\w.+-]*:\\/\\//i.test(filename);\n if (!hasProtocol) {\n // A bare or relative path (e.g. \"app.js\", \"/static/app.js\").\n return true;\n }\n const origin = getOrigin();\n if (origin && filename.startsWith(origin)) {\n return true;\n }\n // Cross-origin absolute URL — treat as third-party / vendor.\n return false;\n}\n\nfunction getOrigin(): string {\n const loc = (globalThis as { location?: { origin?: string } }).location;\n return loc?.origin ?? '';\n}\n\nfunction parseLine(line: string): Frame | null {\n let m = V8_RE.exec(line);\n if (!m) m = GECKO_RE.exec(line);\n if (!m) return null;\n\n const filename = m[2] || null;\n const lineno = m[3] ? parseInt(m[3], 10) : null;\n const colno = m[4] ? parseInt(m[4], 10) : null;\n\n return {\n function: cleanFunction(m[1]),\n filename,\n lineno: Number.isNaN(lineno) ? null : lineno,\n colno: Number.isNaN(colno) ? null : colno,\n in_app: isInAppFrame(filename),\n };\n}\n\n/**\n * Parse a raw `Error.stack` string into normalized frames (crash frame last).\n * Non-frame lines (the `Error: message` header, `[native code]`, etc.) are\n * skipped.\n */\nexport function parseStackString(stack: string | undefined | null): Frame[] {\n if (!stack) return [];\n const frames: Frame[] = [];\n const lines = stack.split('\\n');\n for (const raw of lines) {\n const line = raw.replace(/\\r$/, '');\n if (!line.trim()) continue;\n const frame = parseLine(line);\n if (frame) {\n frames.push(frame);\n if (frames.length >= MAX_FRAMES) break; // keep the frames nearest the crash\n }\n }\n // Raw stacks are crash-first; the wire contract wants crash-last.\n frames.reverse();\n return frames;\n}\n\n/** Parse an `Error`-like object's `.stack`. */\nexport function parseError(err: unknown): Frame[] {\n if (err && typeof err === 'object' && 'stack' in err) {\n const stack = (err as { stack?: unknown }).stack;\n if (typeof stack === 'string') return parseStackString(stack);\n }\n return [];\n}\n","import { getClient } from '../client.js';\nimport { getSessionId } from '../identity.js';\nimport { getScreen } from '../screen.js';\nimport { parseError } from '../stacktrace/parse.js';\nimport type { Breadcrumb, ErrorItem, ExceptionValue, Frame, Hint, Level, Mechanism } from '../types.js';\nimport { nowIso, safeStringify } from '../utils.js';\n\nconst DEFAULT_MECHANISM: Mechanism = { type: 'generic', handled: true };\n\n/** Copy any NON-EMPTY per-call tags/contexts/extra off the hint onto the item. */\nfunction attachCallMeta(item: ErrorItem, hint?: Hint): void {\n if (hint?.tags && Object.keys(hint.tags).length > 0) item.tags = { ...hint.tags };\n if (hint?.contexts && Object.keys(hint.contexts).length > 0) item.contexts = { ...hint.contexts };\n if (hint?.extra && Object.keys(hint.extra).length > 0) item.extra = { ...hint.extra };\n}\n\ninterface ExtractedError {\n type: string;\n value: string | null;\n stacktrace: Frame[];\n}\n\nfunction isErrorLike(err: unknown): err is Error {\n return (\n err instanceof Error ||\n (typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n 'message' in err &&\n typeof (err as { message?: unknown }).message === 'string')\n );\n}\n\n/** Reduce any thrown value into `{type, value, stacktrace}`. */\nfunction extractError(err: unknown): ExtractedError {\n if (isErrorLike(err)) {\n const e = err as Error;\n return {\n type: e.name || 'Error',\n value: e.message ?? '',\n stacktrace: parseError(e),\n };\n }\n if (typeof err === 'string') {\n return { type: 'Error', value: err, stacktrace: [] };\n }\n if (typeof err === 'object' && err !== null) {\n const ctor = (err as { constructor?: { name?: string } }).constructor;\n return {\n type: ctor?.name ?? 'Object',\n value: safeStringify(err),\n stacktrace: [],\n };\n }\n return { type: typeof err, value: String(err), stacktrace: [] };\n}\n\n/** Build an error item from a thrown value plus the current breadcrumb trail. */\nexport function buildErrorItem(err: unknown, breadcrumbs: Breadcrumb[], hint?: Hint): ErrorItem {\n const extracted = extractError(err);\n const mechanism = (hint?.mechanism as Mechanism | undefined) ?? DEFAULT_MECHANISM;\n const level = (hint?.level as Level | undefined) ?? 'error';\n const fingerprint = (hint?.fingerprint as string[] | null | undefined) ?? null;\n\n const exception: ExceptionValue = {\n type: extracted.type,\n value: extracted.value,\n mechanism,\n stacktrace: extracted.stacktrace,\n };\n\n const item: ErrorItem = {\n type: 'error',\n timestamp: nowIso(),\n level,\n exception,\n breadcrumbs,\n fingerprint,\n session_id: getSessionId(),\n screen: (hint?.screen as string | undefined) ?? getScreen(),\n };\n attachCallMeta(item, hint);\n return item;\n}\n\n/** Capture an exception (or any thrown value) as an error item. */\nexport function captureException(err: unknown, hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n const breadcrumbs = client.getScope().getBreadcrumbs();\n const fullHint: Hint = { ...hint, originalException: err };\n const item = buildErrorItem(err, breadcrumbs, fullHint);\n client.captureItem(item, fullHint);\n}\n\n/**\n * Capture a plain message as an error item at the given `level` (default info).\n *\n * The item carries NO `exception` block — a message is not an exception, and the\n * backend's `ExceptionInfo.ty` is a non-`Option` `String` with no serde default,\n * so the `{ type: null }` placeholder this used to send failed to deserialize\n * and 400'd the WHOLE envelope (`invalid_envelope`), taking every unrelated\n * error and event in the batch with it — silently, because every SDK treats a\n * 400 as a non-retryable drop.\n *\n * Omitting `exception` and setting `message` is python's shape. It also routes\n * server-side onto the `message\\n<normalized message>` fingerprint branch, so\n * messages group by their text instead of piling into one bucket keyed by a\n * synthetic exception type.\n */\nexport function captureMessage(message: string, level: Level = 'info', hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n const breadcrumbs = client.getScope().getBreadcrumbs();\n const item: ErrorItem = {\n type: 'error',\n timestamp: nowIso(),\n level,\n message,\n breadcrumbs,\n fingerprint: (hint?.fingerprint as string[] | null | undefined) ?? null,\n session_id: getSessionId(),\n screen: getScreen(),\n };\n attachCallMeta(item, hint);\n client.captureItem(item, hint);\n}\n","import { captureException } from '../api/capture.js';\nimport { getClient } from '../client.js';\nimport { isWrapped, markWrapped, registerPatch } from './instrument.js';\n\n/**\n * Install `window.onerror` and `window.onunhandledrejection`, chaining any\n * previously-registered handler so we never clobber the host app's own logging.\n */\nexport function installGlobalHandlers(): void {\n const win = globalThis as typeof globalThis & {\n onerror?: OnErrorEventHandler;\n onunhandledrejection?: ((event: PromiseRejectionEvent) => unknown) | null;\n };\n\n installOnError(win);\n installOnUnhandledRejection(win);\n}\n\nfunction installOnError(win: typeof globalThis & { onerror?: OnErrorEventHandler }): void {\n const previous = win.onerror;\n if (isWrapped(previous)) return;\n\n const handler = markWrapped(function sauronOnError(\n this: unknown,\n message: Event | string,\n source?: string,\n lineno?: number,\n colno?: number,\n error?: unknown,\n ): boolean {\n if (getClient()) {\n const err = error ?? syntheticError(message, source, lineno, colno);\n captureException(err, { mechanism: { type: 'onerror', handled: false }, level: 'error' });\n }\n if (typeof previous === 'function') {\n return Boolean(\n previous.call(this, message, source, lineno, colno, error as Error | undefined),\n );\n }\n return false;\n });\n\n win.onerror = handler as OnErrorEventHandler;\n registerPatch('onerror', () => {\n win.onerror = (previous ?? null) as OnErrorEventHandler;\n });\n}\n\nfunction installOnUnhandledRejection(\n win: typeof globalThis & {\n onunhandledrejection?: ((event: PromiseRejectionEvent) => unknown) | null;\n },\n): void {\n const previous = win.onunhandledrejection;\n if (isWrapped(previous)) return;\n\n const handler = markWrapped(function sauronOnRejection(\n this: unknown,\n event: PromiseRejectionEvent,\n ): unknown {\n if (getClient()) {\n const reason =\n event && typeof event === 'object' && 'reason' in event ? event.reason : event;\n captureException(reason, {\n mechanism: { type: 'onunhandledrejection', handled: false },\n level: 'error',\n });\n }\n if (typeof previous === 'function') {\n return previous.call(this, event);\n }\n return undefined;\n });\n\n win.onunhandledrejection = handler as (event: PromiseRejectionEvent) => unknown;\n registerPatch('onunhandledrejection', () => {\n win.onunhandledrejection = previous ?? null;\n });\n}\n\n/** Build an Error carrying a best-effort stack from `onerror` positional args. */\nfunction syntheticError(\n message: Event | string,\n source?: string,\n lineno?: number,\n colno?: number,\n): Error {\n const msg = typeof message === 'string' ? message : 'Unknown error';\n const err = new Error(msg);\n if (source) {\n err.stack = `Error: ${msg}\\n at ${source}:${lineno ?? 0}:${colno ?? 0}`;\n }\n return err;\n}\n","import { addNavigationBreadcrumb } from '../api/breadcrumbs.js';\nimport { isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\nlet navHandler: ((path: string) => void) | null = null;\n\n/** Register (or clear) a callback fired with the new path on each SPA navigation. */\nexport function onNavigation(cb: ((path: string) => void) | null): void {\n navHandler = cb;\n}\n\n/** Reduce a URL to its path portion (relative to the current origin). */\nfunction toPath(url: string | null, base: string | undefined): string | null {\n if (url === null || url === undefined) return url;\n try {\n const parsed = new URL(url, base);\n return parsed.pathname + parsed.search + parsed.hash;\n } catch {\n return url;\n }\n}\n\n/**\n * Patch `history.pushState`/`replaceState` and listen for `popstate` to emit\n * `{from, to}` navigation breadcrumbs for SPA route changes.\n */\nexport function installHistory(): void {\n const g = globalThis as typeof globalThis & {\n history?: History;\n location?: Location;\n addEventListener?: (t: string, h: () => void) => void;\n removeEventListener?: (t: string, h: () => void) => void;\n };\n const hist = g.history;\n const loc = g.location;\n if (!hist) return;\n\n let lastPath = toPath(loc?.href ?? null, loc?.href);\n\n const emit = (toHref: string | null): void => {\n const to = toPath(toHref, loc?.href);\n const from = lastPath;\n lastPath = to;\n if (from === to) return;\n withInternal(() => addNavigationBreadcrumb(from, to));\n if (to && navHandler) {\n try {\n navHandler(to);\n } catch {\n /* never let screen tracking break navigation */\n }\n }\n };\n\n const wrap = (name: 'pushState' | 'replaceState'): void => {\n const original = hist[name];\n if (typeof original !== 'function' || isWrapped(original)) return;\n\n hist[name] = markWrapped(function sauronHistory(this: History, ...args: unknown[]) {\n const result = (original as (...a: unknown[]) => unknown).apply(this, args);\n if (!isInternal()) {\n const urlArg = args[2];\n emit(urlArg != null ? String(urlArg) : (loc?.href ?? null));\n }\n return result;\n }) as History[typeof name];\n\n registerPatch(`history.${name}`, () => {\n hist[name] = original;\n });\n };\n\n wrap('pushState');\n wrap('replaceState');\n\n if (typeof g.addEventListener === 'function') {\n const onPopState = (): void => {\n if (!isInternal()) emit(loc?.href ?? null);\n };\n g.addEventListener('popstate', onPopState);\n registerPatch('popstate', () => {\n g.removeEventListener?.('popstate', onPopState);\n });\n }\n}\n","import type { Breadcrumb, UserContext, UserInput } from './types.js';\n\n/** An empty user context (all fields null, no traits). */\nexport function emptyUser(): UserContext {\n return { id: null, email: null, traits: {} };\n}\n\n/**\n * Shallow-merge a per-call override map over a base map. The override wins per\n * top-level key — tags/extra merge by key, contexts merge by block name (a\n * per-call block replaces the same-named base block). Returns a fresh object;\n * callers OMIT the field entirely when the result is empty (emit convention).\n */\nexport function mergeMeta(\n base: Record<string, unknown>,\n override?: Record<string, unknown>,\n): Record<string, unknown> {\n return override ? { ...base, ...override } : { ...base };\n}\n\n/**\n * Mutable per-client state: the current user, a ring buffer of breadcrumbs and\n * free-form tags. The breadcrumb buffer is capped at `maxBreadcrumbs`; the\n * oldest entries fall off the front (FIFO).\n */\nexport class Scope {\n private user: UserContext | null = null;\n private breadcrumbs: Breadcrumb[] = [];\n private maxBreadcrumbs: number;\n readonly tags: Record<string, string> = {};\n readonly contexts: Record<string, unknown> = {};\n readonly extra: Record<string, unknown> = {};\n\n constructor(maxBreadcrumbs = 50) {\n this.maxBreadcrumbs = Math.max(0, maxBreadcrumbs);\n }\n\n setMaxBreadcrumbs(max: number): void {\n this.maxBreadcrumbs = Math.max(0, max);\n this.trim();\n }\n\n /**\n * Replace the scope user.\n *\n * `id` is coerced with `String()` for the same reason `SauronClient.\n * prepareIdentify` coerces its own — a plain-JS caller can (and does) pass\n * `setUser({ id: user.id })` where `user.id` is a number, and TypeScript\n * cannot stop them. This path is the one that BYPASSES `identify()`'s\n * coercion entirely, and the consequence is not cosmetic: the scope user\n * lands in the envelope context, where the server's `distinct_id` is a\n * non-`Option` Rust `String`. A JSON number there fails deserialization of\n * the ENVELOPE, not of the one field — so the whole batch 400s, and a 400\n * is non-retryable, so every event in it is dropped for good.\n *\n * Rebuilding the whole object (rather than merging into the existing one)\n * is deliberate and is the behaviour the Flutter SDK was fixed to match:\n * `email` and `traits` come from the input alone, so setting a new user\n * never inherits the previous person's contact details.\n */\n setUser(user: UserInput): void {\n if (user === null) {\n this.user = null;\n return;\n }\n this.user = {\n id: user.id === null || user.id === undefined ? null : String(user.id),\n email: user.email ?? null,\n traits: user.traits ?? {},\n };\n }\n\n /** The user context for an envelope. Never null — defaults to an empty user. */\n getUser(): UserContext {\n return this.user ? { ...this.user, traits: { ...this.user.traits } } : emptyUser();\n }\n\n /** True when an identifiable user has been set. */\n hasUser(): boolean {\n return this.user !== null;\n }\n\n setTag(key: string, value: string): void {\n this.tags[key] = value;\n }\n\n /** Merge a batch of tags into the scope (last-write-wins per key). */\n setTags(tags: Record<string, string>): void {\n Object.assign(this.tags, tags);\n }\n\n /** Set (replace) a named context block on the scope. */\n setContext(name: string, block: Record<string, unknown>): void {\n this.contexts[name] = block;\n }\n\n /** Set a single freeform extra value on the scope. */\n setExtra(key: string, value: unknown): void {\n this.extra[key] = value;\n }\n\n addBreadcrumb(breadcrumb: Breadcrumb): void {\n if (this.maxBreadcrumbs <= 0) return;\n this.breadcrumbs.push(breadcrumb);\n this.trim();\n }\n\n /** A defensive copy of the current breadcrumb trail. */\n getBreadcrumbs(): Breadcrumb[] {\n return this.breadcrumbs.slice();\n }\n\n clearBreadcrumbs(): void {\n this.breadcrumbs = [];\n }\n\n private trim(): void {\n const overflow = this.breadcrumbs.length - this.maxBreadcrumbs;\n if (overflow > 0) {\n this.breadcrumbs.splice(0, overflow);\n }\n }\n}\n","/**\n * Current-workflow state. The SDK stamps `workflow_id`/`workflow_name` on\n * every event/error/transaction while a workflow is active, and emits the\n * reserved `$workflow_start` / `$workflow_end` / `$workflow_cancel` analytics\n * events around its lifecycle (see api/product.ts).\n */\nimport type { ActiveWorkflow } from './types.js';\n\n/** Cap on a workflow name, after trimming. */\nexport const WORKFLOW_NAME_MAX = 120;\n/** Cap on a cancel reason. */\nexport const WORKFLOW_REASON_MAX = 120;\n\nlet current: ActiveWorkflow | null = null;\n\n/** The active workflow, or null if none. */\nexport function getWorkflow(): ActiveWorkflow | null {\n return current;\n}\n\n/** Set (or clear, with `null`) the active workflow. */\nexport function setWorkflowState(workflow: ActiveWorkflow | null): void {\n current = workflow;\n}\n\n/** Drop the in-memory value (tests + teardown). */\nexport function resetWorkflow(): void {\n current = null;\n}\n\n/** Returns the trimmed name, or null when invalid (empty or over the cap). */\nexport function normalizeWorkflowName(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > WORKFLOW_NAME_MAX) return null;\n return trimmed;\n}\n\n/** Normalize a cancel reason: default to `'user'`, else trim and cap. */\nexport function normalizeReason(reason: unknown): string {\n if (typeof reason !== 'string' || reason.trim().length === 0) return 'user';\n return reason.trim().slice(0, WORKFLOW_REASON_MAX);\n}\n","import { getClient } from '../client.js';\nimport { getSessionId } from '../identity.js';\nimport { getScreen, setScreenState } from '../screen.js';\nimport { mergeMeta } from '../scope.js';\nimport type {\n ActiveWorkflow,\n EventItem,\n IdentifyItem,\n TrackOptions,\n TransactionItem,\n TransactionOp,\n WorkflowResult,\n} from '../types.js';\nimport { capTransactionExtra, makeLogger, nowIso, uuidv4 } from '../utils.js';\nimport {\n getWorkflow,\n normalizeReason,\n normalizeWorkflowName,\n resetWorkflow,\n setWorkflowState,\n} from '../workflow.js';\n\n/**\n * Record a product-analytics event (PostHog-style). The `distinct_id` is the\n * current user id when identified, otherwise a stable anonymous id.\n */\nexport function track(\n name: string,\n properties: Record<string, unknown> = {},\n options: TrackOptions = {},\n): void {\n const client = getClient();\n if (!client) return;\n const scope = client.getScope();\n const item: EventItem = {\n type: 'event',\n name,\n distinct_id: client.getDistinctId(),\n session_id: getSessionId(),\n screen: options.screen ?? getScreen(),\n timestamp: nowIso(),\n properties: properties ?? {},\n };\n const tags = mergeMeta(scope.tags, options.tags);\n if (Object.keys(tags).length > 0) item.tags = tags;\n const contexts = mergeMeta(scope.contexts, options.contexts);\n if (Object.keys(contexts).length > 0) item.contexts = contexts;\n const extra = mergeMeta(scope.extra, options.extra);\n if (Object.keys(extra).length > 0) item.extra = extra;\n client.captureItem(item);\n}\n\n/**\n * Set the current screen. On an actual change, emits a `$screen` view event\n * (carrying the new screen) so dwell can be computed server-side.\n */\nexport function setScreen(name: string): void {\n if (!setScreenState(name)) return;\n track('$screen', { screen: name });\n}\n\n/**\n * Associate the current session with a known user. Emits an identify item that\n * links the prior anonymous id (if any) to the new distinct id.\n */\nexport function identify(id: string, traits: Record<string, unknown> = {}): void {\n const client = getClient();\n if (!client) return;\n // Coerce ONCE, use everywhere below. `IdentifyItem.distinct_id` is a\n // non-`Option` Rust `String` on the wire (`envelope.rs`), so a plain-JS\n // caller passing a number (`Sauron.identify(user.id)`, entirely possible —\n // nothing at runtime enforces the TS `id: string` signature) would send a\n // JSON number there. That fails to deserialize and rejects the WHOLE\n // envelope (`400 invalid_envelope`), taking every other item batched\n // alongside it — the identical failure class `CHANGELOG.md` 1.4.0 documents\n // for `captureMessage`'s `exception.type: null`.\n const distinctId = String(id);\n // `null` unless the anon id was actually used as a distinct_id in this\n // browser session, or when it belonged to a different person than the last\n // one who identified on this device (`prepareIdentify` mints a fresh anon id\n // first in that case, since the old one is already burned server-side).\n // `process_identify` inserts a permanent `identities(app_id, alias_id,\n // distinct_id)` row for any non-empty anonymous_id, and that row is now a\n // LIVE signal (the 000038 backfill reads it), so a speculative or\n // cross-user alias is a durable server-side mis-merge.\n const anonymousId = client.prepareIdentify(distinctId);\n client.getScope().setUser({ id: distinctId, traits });\n const item: IdentifyItem = {\n type: 'identify',\n distinct_id: distinctId,\n anonymous_id: anonymousId,\n traits: traits ?? {},\n };\n client.captureItem(item);\n}\n\n/** Loose (camelCase) input accepted by {@link trackTransaction}. */\nexport interface TransactionInput {\n name: string;\n op?: string;\n durationMs: number;\n status?: string | null;\n httpMethod?: string | null;\n httpStatus?: number | null;\n url?: string | null;\n /**\n * Flat string tags for this transaction.\n *\n * **Per-call only — the scope is NOT merged in**, which is the one place\n * transactions differ from `track()` and `captureException()`. Those two\n * merge `setTag`/`setExtra` defaults; a transaction carries only what its own\n * call site attached. Transactions are the highest-volume signal (one per\n * navigation and per HTTP call), so inheriting a global blob would write it\n * onto every row.\n */\n tags?: Record<string, string>;\n /**\n * Freeform JSON for this transaction — the request body, the response body,\n * an order id, a retry count.\n *\n * Per-call only, for the reason on {@link TransactionInput.tags}. Serialized\n * and capped at {@link MAX_TRANSACTION_EXTRA_BYTES}; past that the whole map\n * is replaced with `{ _truncated: true, _bytes: N }` so one large body cannot\n * take a batched envelope over the ingest limit and drop every span in it.\n *\n * Nothing here is scrubbed. `beforeSend` is the redaction seam.\n */\n extra?: Record<string, unknown>;\n}\n\nconst TRANSACTION_OPS: readonly TransactionOp[] = [\n 'navigation',\n 'http',\n 'resource',\n 'screen_load',\n 'custom',\n];\n\n/** Coerce a free-form op string to a known {@link TransactionOp}, else `custom`. */\nfunction normalizeOp(op: string | undefined): TransactionOp {\n return op && (TRANSACTION_OPS as readonly string[]).includes(op)\n ? (op as TransactionOp)\n : 'custom';\n}\n\n/**\n * Build a wire-shaped transaction item from camelCase input. Pure — the caller\n * supplies the current identity so this stays testable without a client.\n */\nexport function buildTransactionItem(\n input: TransactionInput,\n distinctId: string | null,\n sessionId: string | null,\n): TransactionItem {\n const item: TransactionItem = {\n type: 'transaction',\n name: input.name,\n op: normalizeOp(input.op),\n duration_ms: input.durationMs,\n status: input.status ?? null,\n http_method: input.httpMethod ?? null,\n http_status: input.httpStatus ?? null,\n url: input.url ?? null,\n distinct_id: distinctId,\n session_id: sessionId,\n timestamp: nowIso(),\n };\n // Per-call only — no `mergeMeta(scope.tags, …)` here, unlike `track()` above.\n // Omitted when empty so an app that never sets them is byte-identical on the\n // wire to before these fields existed.\n if (input.tags && Object.keys(input.tags).length > 0) item.tags = { ...input.tags };\n if (input.extra && Object.keys(input.extra).length > 0) {\n item.extra = capTransactionExtra({ ...input.extra });\n }\n return item;\n}\n\n/** Enqueue a performance transaction item. */\nexport function trackTransaction(input: TransactionInput): void {\n const client = getClient();\n if (!client) return;\n const item = buildTransactionItem(input, client.getDistinctId(), getSessionId());\n client.captureItem(item);\n}\n\n/* ----------------------------------------------------------------- workflow */\n\n/**\n * Discards everything. Used as the logger until a real one can be built from\n * the client, so the `catch` blocks below can log unconditionally even when\n * the failure happened while acquiring the client itself.\n */\nconst NOOP_LOGGER = makeLogger(false);\n\n/**\n * Emit the closing lifecycle event (`$workflow_end`/`$workflow_cancel`) for\n * `active` while it is STILL the active workflow (so it is stamped with the\n * workflow it closes), then clear the state.\n *\n * NEVER THROWS, and clears the state in a `finally`. That pairing is the whole\n * contract: callers report `ok` on the strength of it, and `ok` must mean the\n * workflow really is closed locally. If the emit could throw past this\n * function, the state would stay set while the caller was told the workflow\n * ended — every later signal would then be stamped with a workflow the app\n * considers finished, and it would never leave `active` server-side. A lost\n * lifecycle event is recoverable (the server materializes the rollup row from\n * whatever stamped events it does receive); a permanently desynced local state\n * is not.\n */\nfunction emitWorkflowClose(\n active: ActiveWorkflow,\n eventName: '$workflow_end' | '$workflow_cancel',\n reason: string | undefined,\n logger: { warn: (...args: unknown[]) => void },\n): void {\n const properties: Record<string, unknown> = {\n workflow_id: active.workflowId,\n workflow_name: active.name,\n duration_ms: Math.max(0, Date.now() - Date.parse(active.startedAt)),\n };\n if (eventName === '$workflow_cancel') {\n properties.reason = normalizeReason(reason);\n }\n try {\n track(eventName, properties);\n } catch (err) {\n logger.warn(`${eventName}: failed to emit the lifecycle event`, err);\n } finally {\n resetWorkflow();\n }\n}\n\n/**\n * Start a named workflow. `force: true` supersedes an already-active workflow\n * (emitting `$workflow_cancel` with `reason: 'superseded'` for it first);\n * otherwise an active workflow makes this a no-op returning `already_active`.\n *\n * The workflow id is a fresh client-generated UUID — the server rolls counters\n * up on `(app_id, workflow_id)` app-wide, so a deterministic or reused id would\n * merge counts from unrelated environments/sessions into one row.\n */\nexport function startWorkflow(name: string, options?: { force?: boolean }): WorkflowResult {\n let logger = NOOP_LOGGER;\n try {\n const client = getClient();\n if (!client || !client.isEnabled()) return { status: 'disabled' };\n logger = makeLogger(client.options.debug);\n\n const normalized = normalizeWorkflowName(name);\n if (!normalized) {\n logger.warn('startWorkflow: invalid name', name);\n return { status: 'invalid_name' };\n }\n\n const active = getWorkflow();\n if (active && !options?.force) {\n logger.warn(\n `startWorkflow(\"${normalized}\"): \"${active.name}\" is already active; pass { force: true } to replace it`,\n );\n return { status: 'already_active' };\n }\n\n // Mint the replacement BEFORE superseding the old one, so nothing that\n // could throw sits between closing the old workflow and setting the new\n // one — otherwise the `catch` below could report `disabled` (\"nothing\n // changed\") having already closed the previous workflow.\n const workflow: ActiveWorkflow = {\n workflowId: uuidv4(),\n name: normalized,\n startedAt: nowIso(),\n };\n if (active) emitWorkflowClose(active, '$workflow_cancel', 'superseded', logger);\n\n // Set the state BEFORE emitting, so $workflow_start is itself stamped.\n setWorkflowState(workflow);\n try {\n track('$workflow_start', { workflow_id: workflow.workflowId, workflow_name: workflow.name });\n } catch (err) {\n // The workflow IS live and stamping IS active — reporting `disabled`\n // here would tell the caller nothing started and hand back no id, which\n // is the one thing that cannot be recovered. The server materializes the\n // rollup row from the first stamped event regardless, so a lost\n // `$workflow_start` costs only its own properties.\n logger.warn('startWorkflow: failed to emit $workflow_start', err);\n }\n return { status: 'ok', workflowId: workflow.workflowId };\n } catch (err) {\n // Only reachable before any state was touched, so `disabled` — documented\n // as \"nothing changed\" — is honest here.\n logger.warn('startWorkflow failed', err);\n return { status: 'disabled' };\n }\n}\n\n/** Shared precondition + close logic for `endWorkflow`/`cancelWorkflow`. */\nfunction closeWorkflow(\n eventName: '$workflow_end' | '$workflow_cancel',\n name?: string,\n reason?: string,\n): WorkflowResult {\n let logger = NOOP_LOGGER;\n try {\n const client = getClient();\n if (!client || !client.isEnabled()) return { status: 'disabled' };\n logger = makeLogger(client.options.debug);\n\n const active = getWorkflow();\n if (!active) return { status: 'not_active' };\n // A malformed explicit `name` normalizes to null, which never equals an\n // active name — so it reports `name_mismatch`, not `invalid_name`. That is\n // deliberate: the caller named a workflow that is not the active one.\n if (name !== undefined && normalizeWorkflowName(name) !== active.name) {\n logger.warn(`${eventName}: \"${name}\" does not match active workflow \"${active.name}\"`);\n return { status: 'name_mismatch' };\n }\n const workflowId = active.workflowId;\n // Cannot throw, and always clears the state — so `ok` below is truthful.\n emitWorkflowClose(active, eventName, reason, logger);\n return { status: 'ok', workflowId };\n } catch (err) {\n // As in startWorkflow: only reachable before any state was touched.\n logger.warn(`${eventName} failed`, err);\n return { status: 'disabled' };\n }\n}\n\n/**\n * End the active workflow (or the one named `name`, if given). Emits\n * `$workflow_end` with `duration_ms` and clears the state. A no-op returning\n * `not_active`/`name_mismatch` when the precondition fails.\n */\nexport function endWorkflow(name?: string): WorkflowResult {\n return closeWorkflow('$workflow_end', name);\n}\n\n/**\n * Cancel the active workflow (or the one named `name`, if given). Emits\n * `$workflow_cancel` with `duration_ms` and `reason` (default `'user'`, capped\n * at 120 chars) and clears the state.\n */\nexport function cancelWorkflow(name?: string, options?: { reason?: string }): WorkflowResult {\n return closeWorkflow('$workflow_cancel', name, options?.reason);\n}\n","/**\n * Performance auto-instrumentation. In a browser this captures:\n *\n * - one `navigation` transaction for the initial page load (navigation timing),\n * - one `http` transaction per instrumented `fetch` call,\n * - a `navigation` transaction on each SPA route change (History API).\n *\n * Everything here is strictly best-effort: instrumentation errors are swallowed\n * so an app `fetch` never breaks, and the original fetch rejection is re-thrown\n * unchanged to the caller. Opt in with `init({ performance: true })`.\n */\n\nimport { trackTransaction } from '../api/product.js';\nimport { isDsnRequest, isInternal, registerPatch } from './instrument.js';\n\n/** Dedicated markers so we layer on top of the breadcrumb integrations without\n * colliding with their generic \"wrapped\" tag. */\nconst PERF_FETCH = '__sauron_perf_fetch__';\nconst PERF_HISTORY = '__sauron_perf_history__';\n\ninterface GlobalLike {\n fetch?: typeof fetch;\n history?: History;\n location?: Location;\n document?: Document;\n performance?: Performance;\n requestAnimationFrame?: (cb: () => void) => number;\n addEventListener?: (type: string, handler: () => void) => void;\n removeEventListener?: (type: string, handler: () => void) => void;\n}\n\nfunction g(): GlobalLike {\n return globalThis as GlobalLike;\n}\n\n/** Tag a wrapper function with a marker so we never wrap it twice. */\nfunction mark(fn: object, key: string): void {\n (fn as unknown as Record<string, unknown>)[key] = true;\n}\n\n/** True when `fn` was tagged with {@link mark}. */\nfunction isMarked(fn: unknown, key: string): boolean {\n return typeof fn === 'function' && (fn as unknown as Record<string, unknown>)[key] === true;\n}\n\n/** High-resolution clock, degrading to `Date.now()` when `performance` is absent. */\nfunction clock(): () => number {\n const perf = g().performance;\n if (perf && typeof perf.now === 'function') return () => perf.now();\n return () => Date.now();\n}\n\nfunction resolveUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const withUrl = input as { url?: string; href?: string };\n if (typeof withUrl.url === 'string') return withUrl.url;\n if (typeof withUrl.href === 'string') return withUrl.href;\n }\n return String(input);\n}\n\nfunction resolveMethod(input: unknown, init: unknown): string {\n const fromInit = (init as { method?: string } | undefined)?.method;\n const fromReq = (input as { method?: string } | null)?.method;\n return String(fromInit ?? fromReq ?? 'GET').toUpperCase();\n}\n\n/** Reduce a URL to its path portion (relative to the current origin). */\nfunction pathOf(url: string | null | undefined): string {\n if (!url) return '/';\n try {\n const base = g().location?.href;\n return new URL(url, base).pathname;\n } catch {\n return url;\n }\n}\n\n/* ------------------------------------------------------- navigation timing */\n\n/** Prefer the modern `PerformanceNavigationTiming.duration`, else the legacy\n * `timing.loadEventEnd - navigationStart`. Returns `null` when unavailable. */\nfunction navigationDuration(perf: Performance): number | null {\n try {\n const entries = perf.getEntriesByType?.('navigation') as\n | PerformanceNavigationTiming[]\n | undefined;\n if (entries && entries.length > 0) {\n const d = entries[0].duration;\n if (typeof d === 'number' && d > 0) return d;\n }\n } catch {\n /* getEntriesByType unsupported — fall through */\n }\n const timing = (perf as { timing?: PerformanceTiming }).timing;\n if (timing && timing.loadEventEnd && timing.navigationStart) {\n const d = timing.loadEventEnd - timing.navigationStart;\n if (d > 0) return d;\n }\n return null;\n}\n\nfunction installNavigationTiming(): void {\n const perf = g().performance;\n if (!perf) return;\n\n const capture = (): void => {\n try {\n const durationMs = navigationDuration(perf);\n if (durationMs === null) return;\n trackTransaction({ name: pathOf(g().location?.pathname), op: 'navigation', durationMs });\n } catch {\n /* swallow */\n }\n };\n\n // Timing is only final once `load` has fired; capture now if it already has.\n const doc = g().document;\n if (doc && doc.readyState === 'complete') {\n capture();\n } else if (typeof g().addEventListener === 'function') {\n const onLoad = (): void => {\n capture();\n g().removeEventListener?.('load', onLoad);\n };\n g().addEventListener?.('load', onLoad);\n registerPatch('perf.load', () => g().removeEventListener?.('load', onLoad));\n } else {\n capture();\n }\n}\n\n/* -------------------------------------------------------------- fetch timing */\n\nfunction emitHttp(\n method: string,\n url: string,\n start: number,\n end: number,\n status: number | null,\n ok: boolean,\n): void {\n try {\n trackTransaction({\n name: `${method} ${pathOf(url)}`,\n op: 'http',\n durationMs: Math.max(0, end - start),\n status: ok ? 'ok' : 'error',\n httpMethod: method,\n httpStatus: status ?? undefined,\n url,\n });\n } catch {\n /* never throw into user code */\n }\n}\n\nfunction installFetchTiming(): void {\n const original = g().fetch;\n if (typeof original !== 'function') return;\n if (isMarked(original, PERF_FETCH)) return;\n\n const now = clock();\n\n const wrapped = function sauronPerfFetch(\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n let url = '';\n let method = 'GET';\n let record = false;\n try {\n url = resolveUrl(input);\n method = resolveMethod(input, init);\n record = !isInternal() && !isDsnRequest(url);\n } catch {\n record = false;\n }\n\n const start = record ? now() : 0;\n // Return the ORIGINAL promise so the caller sees the untouched result and\n // any rejection propagates unchanged.\n const promise = original.call(this, input as RequestInfo, init);\n\n if (record) {\n promise.then(\n (res) => emitHttp(method, url, start, now(), res?.status ?? null, res?.ok ?? false),\n () => emitHttp(method, url, start, now(), null, false),\n );\n }\n return promise;\n };\n\n mark(wrapped, PERF_FETCH);\n g().fetch = wrapped as typeof fetch;\n registerPatch('perf.fetch', () => {\n g().fetch = original;\n });\n}\n\n/* ------------------------------------------------------------ history timing */\n\nfunction installHistoryTiming(): void {\n const hist = g().history;\n if (!hist) return;\n const now = clock();\n\n const emit = (): void => {\n try {\n const path = pathOf(g().location?.pathname);\n const start = now();\n const finish = (): void => {\n try {\n trackTransaction({ name: path, op: 'navigation', durationMs: Math.max(0, now() - start) });\n } catch {\n /* swallow */\n }\n };\n // Approximate the client-side render span with a single animation frame.\n const raf = g().requestAnimationFrame;\n if (typeof raf === 'function') raf(finish);\n else finish();\n } catch {\n /* swallow */\n }\n };\n\n const wrap = (name: 'pushState' | 'replaceState'): void => {\n const original = hist[name];\n if (typeof original !== 'function') return;\n if (isMarked(original, PERF_HISTORY)) return;\n\n const patched = function sauronPerfHistory(this: History, ...args: unknown[]) {\n const result = (original as (...a: unknown[]) => unknown).apply(this, args);\n if (!isInternal()) emit();\n return result;\n };\n mark(patched, PERF_HISTORY);\n hist[name] = patched as History[typeof name];\n registerPatch(`perf.history.${name}`, () => {\n hist[name] = original;\n });\n };\n\n wrap('pushState');\n wrap('replaceState');\n\n if (typeof g().addEventListener === 'function') {\n const onPopState = (): void => {\n if (!isInternal()) emit();\n };\n g().addEventListener?.('popstate', onPopState);\n registerPatch('perf.popstate', () => g().removeEventListener?.('popstate', onPopState));\n }\n}\n\n/* --------------------------------------------------------------------- entry */\n\n/** Install performance auto-capture. No-op outside a browser-like environment. */\nexport function installPerformance(): void {\n if (typeof g().document === 'undefined') return;\n installNavigationTiming();\n installFetchTiming();\n installHistoryTiming();\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { nowIso } from '../utils.js';\nimport { isDsnRequest, isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\ninterface XhrMeta {\n method: string;\n url: string;\n startedAt: string;\n}\n\ntype PatchedXhr = XMLHttpRequest & { __sauron_xhr__?: XhrMeta };\n\nfunction addXhrBreadcrumb(meta: XhrMeta, status: number): void {\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'xhr',\n level: status >= 400 ? 'warning' : 'info',\n message: `${meta.method} ${meta.url}`,\n timestamp: meta.startedAt,\n data: { method: meta.method, url: meta.url, status_code: status || null },\n });\n });\n}\n\n/** Wrap `XMLHttpRequest.open`/`send` to leave a breadcrumb per request. */\nexport function installXhr(): void {\n const XHR = (globalThis as { XMLHttpRequest?: typeof XMLHttpRequest }).XMLHttpRequest;\n if (typeof XHR !== 'function' || !XHR.prototype) return;\n\n const proto = XHR.prototype;\n const originalOpen = proto.open;\n const originalSend = proto.send;\n if (isWrapped(originalOpen) || isWrapped(originalSend)) return;\n\n proto.open = markWrapped(function sauronXhrOpen(\n this: PatchedXhr,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this.__sauron_xhr__ = {\n method: String(method ?? 'GET').toUpperCase(),\n url: String(url),\n startedAt: nowIso(),\n };\n return (originalOpen as (...a: unknown[]) => unknown).apply(this, [method, url, ...rest]);\n }) as typeof proto.open;\n\n proto.send = markWrapped(function sauronXhrSend(this: PatchedXhr, ...args: unknown[]) {\n const meta = this.__sauron_xhr__;\n if (meta && !isInternal() && !isDsnRequest(meta.url)) {\n const onLoadEnd = (): void => {\n try {\n addXhrBreadcrumb(meta, this.status);\n } catch {\n /* ignore */\n } finally {\n try {\n this.removeEventListener('loadend', onLoadEnd);\n } catch {\n /* ignore */\n }\n }\n };\n try {\n this.addEventListener('loadend', onLoadEnd);\n } catch {\n /* ignore */\n }\n }\n return (originalSend as (...a: unknown[]) => unknown).apply(this, args);\n }) as typeof proto.send;\n\n registerPatch('xhr', () => {\n proto.open = originalOpen;\n proto.send = originalSend;\n });\n}\n","import type { Transport } from './transport.js';\n\n/**\n * Wire up the page-unload flush path. When the page is hidden or unloaded there\n * is no time for an async `fetch` round-trip, so we hand the pending batch to\n * `navigator.sendBeacon` (see {@link Transport.flushToBeacon}).\n *\n * Returns a cleanup function that removes the listeners.\n */\nexport function installBeacon(transport: Transport): () => void {\n const win = globalThis as {\n addEventListener?: (t: string, h: () => void) => void;\n removeEventListener?: (t: string, h: () => void) => void;\n };\n const doc = (globalThis as { document?: Document }).document;\n\n const flush = (): void => {\n try {\n transport.flushToBeacon();\n } catch {\n /* never throw from an unload handler */\n }\n };\n\n const onVisibility = (): void => {\n if (doc && doc.visibilityState === 'hidden') flush();\n };\n\n if (doc && typeof doc.addEventListener === 'function') {\n doc.addEventListener('visibilitychange', onVisibility);\n }\n if (typeof win.addEventListener === 'function') {\n win.addEventListener('pagehide', flush);\n }\n\n return () => {\n if (doc && typeof doc.removeEventListener === 'function') {\n doc.removeEventListener('visibilitychange', onVisibility);\n }\n if (typeof win.removeEventListener === 'function') {\n win.removeEventListener('pagehide', flush);\n }\n };\n}\n","/**\n * Payload compression.\n *\n * Prefers the native `CompressionStream('gzip')`; lazily imports `fflate` only\n * as a fallback. Payloads under {@link MIN_COMPRESS_BYTES} are left as plain\n * strings so the caller omits the `Content-Encoding` header entirely.\n */\n\n/** Below this size, compression overhead isn't worth it. */\nexport const MIN_COMPRESS_BYTES = 1024;\n\nexport interface CompressResult {\n body: Uint8Array | string;\n /** `'gzip'` only when the body was actually compressed. */\n encoding: 'gzip' | null;\n}\n\ninterface CompressionStreamCtor {\n new (format: string): {\n readable: ReadableStream<Uint8Array>;\n writable: WritableStream<Uint8Array>;\n };\n}\n\nfunction getCompressionStream(): CompressionStreamCtor | undefined {\n const g = globalThis as { CompressionStream?: CompressionStreamCtor };\n return typeof g.CompressionStream === 'function' ? g.CompressionStream : undefined;\n}\n\nasync function gzipViaStream(bytes: Uint8Array, CS: CompressionStreamCtor): Promise<Uint8Array> {\n const cs = new CS('gzip');\n const writer = cs.writable.getWriter();\n void writer.write(bytes);\n void writer.close();\n\n const reader = cs.readable.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) {\n chunks.push(value);\n total += value.length;\n }\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/** Compress a JSON string to gzip when large enough; otherwise pass it through. */\nexport async function maybeCompress(json: string): Promise<CompressResult> {\n const raw = new TextEncoder().encode(json);\n if (raw.length < MIN_COMPRESS_BYTES) {\n return { body: json, encoding: null };\n }\n\n const CS = getCompressionStream();\n if (CS) {\n try {\n const gz = await gzipViaStream(raw, CS);\n return { body: gz, encoding: 'gzip' };\n } catch {\n /* fall through to fflate */\n }\n }\n\n try {\n const { gzipSync } = await import('fflate');\n return { body: gzipSync(raw), encoding: 'gzip' };\n } catch {\n // No compression available — send uncompressed rather than drop the event.\n return { body: json, encoding: null };\n }\n}\n","import { byteLength } from '../utils.js';\n\n/** The minimal storage surface we need (a subset of `Storage`). */\nexport interface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nconst QUEUE_KEY = 'sauron:queue:v1';\n\n/** Return `localStorage` if it is present and writable, else `null`. */\nexport function defaultStorage(): StorageLike | null {\n try {\n const ls = (globalThis as { localStorage?: StorageLike }).localStorage;\n if (!ls) return null;\n const probe = '__sauron_probe__';\n ls.setItem(probe, '1');\n ls.removeItem(probe);\n return ls;\n } catch {\n // Storage disabled (private mode, blocked cookies, SSR, ...).\n return null;\n }\n}\n\n/**\n * A FIFO offline queue backed by a single `localStorage` key. Each entry is a\n * serialized envelope JSON string. The queue is byte-capped: when enqueuing\n * would exceed `maxBytes`, the OLDEST entries are evicted first.\n */\nexport class OfflineQueue {\n private readonly maxBytes: number;\n private readonly storage: StorageLike | null;\n private readonly key: string;\n\n constructor(maxBytes: number, storage: StorageLike | null, key: string = QUEUE_KEY) {\n this.maxBytes = Math.max(0, maxBytes);\n this.storage = storage;\n this.key = key;\n }\n\n /** True when a real backing store is available. */\n get available(): boolean {\n return this.storage !== null;\n }\n\n private read(): string[] {\n if (!this.storage) return [];\n try {\n const raw = this.storage.getItem(this.key);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === 'string');\n } catch {\n return [];\n }\n }\n\n private write(entries: string[]): void {\n if (!this.storage) return;\n try {\n if (entries.length === 0) {\n this.storage.removeItem(this.key);\n } else {\n this.storage.setItem(this.key, JSON.stringify(entries));\n }\n } catch {\n // Quota exceeded or storage vanished — drop silently.\n }\n }\n\n /** Drop oldest entries until the total fits under `maxBytes`. Keeps >= 1. */\n private evict(entries: string[]): void {\n let total = 0;\n for (const e of entries) total += byteLength(e);\n while (entries.length > 1 && total > this.maxBytes) {\n const removed = entries.shift();\n if (removed === undefined) break;\n total -= byteLength(removed);\n }\n }\n\n /** Append a payload to the tail (newest), evicting from the head if needed. */\n enqueue(payload: string): void {\n if (!this.storage) return;\n const entries = this.read();\n entries.push(payload);\n this.evict(entries);\n this.write(entries);\n }\n\n /** Remove and return every entry, oldest first. */\n drain(): string[] {\n const entries = this.read();\n if (entries.length) this.write([]);\n return entries;\n }\n\n /**\n * Put drained payloads BACK at the head, keeping their relative order.\n *\n * The counterpart to {@link drain}: a drain empties the store immediately, so\n * whatever the caller could not deliver only exists in its local array and is\n * lost the moment the caller returns. Re-parking at the head (rather than via\n * {@link enqueue}) keeps the queue oldest-first, which is what the byte-cap\n * eviction policy assumes — the oldest entry must stay the first one evicted.\n */\n requeueFront(payloads: string[]): void {\n if (!this.storage || payloads.length === 0) return;\n const entries = [...payloads, ...this.read()];\n this.evict(entries);\n this.write(entries);\n }\n\n /** Non-destructive read of the current entries, oldest first. */\n peek(): string[] {\n return this.read();\n }\n\n /** Number of queued entries. */\n size(): number {\n return this.read().length;\n }\n\n /** Total UTF-8 byte size of the queue. */\n byteSize(): number {\n let total = 0;\n for (const e of this.read()) total += byteLength(e);\n return total;\n }\n\n clear(): void {\n this.write([]);\n }\n}\n","import type { Dsn } from '../dsn.js';\nimport { beginInternal, endInternal } from '../integrations/instrument.js';\nimport type { Envelope, EnvelopeItem } from '../types.js';\nimport { byteLength, computeBackoff, safeStringify } from '../utils.js';\nimport { maybeCompress } from './compress.js';\nimport { defaultStorage, OfflineQueue } from './queue.js';\n\n/** `sendBeacon` / `keepalive` payloads are capped near 64 KiB by browsers. */\nexport const BEACON_MAX_BYTES = 64 * 1024;\n\n/**\n * Hard ceiling on items in one envelope, matching the server's own limit.\n * Exceeding it is a non-retryable 400, so the batch would simply be lost.\n */\nexport const MAX_ITEMS_PER_ENVELOPE = 1000;\n\n/** Max delivery attempts before a batch is parked in the offline queue. */\nconst MAX_RETRIES = 5;\n\n/** Retry-After is honored but clamped so `flush()`/`close()` can't hang forever. */\nconst RETRY_AFTER_CAP_MS = 30_000;\n\ntype SendAction = 'drop' | 'disable' | 'split' | 'retry_after' | 'retry_backoff';\n\ninterface SendOutcome {\n action: SendAction;\n retryAfterMs?: number;\n}\n\ninterface HttpResult {\n status: number;\n retryAfter: string | null;\n}\n\ninterface Logger {\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport interface TransportConfig {\n dsn: Dsn;\n options: { flushIntervalMs: number; maxBatch: number; maxQueueBytes: number };\n makeEnvelope: (items: EnvelopeItem[]) => Envelope;\n fetchImpl?: typeof fetch;\n logger: Logger;\n onDisable: () => void;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\nfunction parseRetryAfter(header: string | null): number {\n if (!header) return 1000;\n const seconds = Number(header);\n if (!Number.isNaN(seconds)) {\n return Math.min(RETRY_AFTER_CAP_MS, Math.max(0, seconds * 1000));\n }\n const date = Date.parse(header);\n if (!Number.isNaN(date)) {\n return Math.min(RETRY_AFTER_CAP_MS, Math.max(0, date - Date.now()));\n }\n return 1000;\n}\n\n/** Map an HTTP status onto the locked response-handling table. */\nfunction classifyStatus(status: number, retryAfter: string | null): SendOutcome {\n if (status === 200 || status === 202) return { action: 'drop' };\n if (status === 400) return { action: 'drop' };\n if (status === 401 || status === 403) return { action: 'disable' };\n if (status === 408) return { action: 'retry_backoff' };\n if (status === 413) return { action: 'split' };\n if (status === 429) return { action: 'retry_after', retryAfterMs: parseRetryAfter(retryAfter) };\n if (status >= 500) return { action: 'retry_backoff' };\n if (status >= 400) return { action: 'drop' }; // other 4xx: client error, no retry\n return { action: 'drop' };\n}\n\n/**\n * Batching transport with retry/backoff, an offline queue and a beacon path.\n *\n * All outbound requests go through `fetchImpl` (the NATIVE fetch captured before\n * integrations wrapped it) or an XHR fallback, so the transport never triggers\n * its own instrumentation.\n */\nexport class Transport {\n private readonly dsn: Dsn;\n private readonly makeEnvelope: (items: EnvelopeItem[]) => Envelope;\n private readonly fetchImpl?: typeof fetch;\n private readonly logger: Logger;\n private readonly onDisable: () => void;\n private readonly flushIntervalMs: number;\n private readonly maxBatch: number;\n private readonly offline: OfflineQueue;\n\n private pending: EnvelopeItem[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private onlineHandler: (() => void) | null = null;\n /** Permanent auto-disable latch, flipped by this transport itself the moment\n * it classifies a response as 401/403 — it is the source of truth for\n * {@link isEnabled}, not merely a mirror of something the client decided. */\n private disabled = false;\n\n constructor(config: TransportConfig) {\n this.dsn = config.dsn;\n this.makeEnvelope = config.makeEnvelope;\n this.fetchImpl = config.fetchImpl;\n this.logger = config.logger;\n this.onDisable = config.onDisable;\n this.flushIntervalMs = config.options.flushIntervalMs;\n // Clamped to the server's per-envelope limit: a configured `maxBatch`\n // above it would produce envelopes that are rejected outright.\n this.maxBatch = Math.min(\n MAX_ITEMS_PER_ENVELOPE,\n Math.max(1, config.options.maxBatch),\n );\n this.offline = new OfflineQueue(config.options.maxQueueBytes, defaultStorage());\n }\n\n /** Begin periodic flushing and listen for connectivity restoration. */\n start(): void {\n if (this.timer === null && this.flushIntervalMs > 0) {\n this.timer = setInterval(() => {\n void this.flush();\n }, this.flushIntervalMs);\n // Don't hold the Node event loop open (harmless/no-op in browsers).\n (this.timer as { unref?: () => void }).unref?.();\n }\n const g = globalThis as { addEventListener?: (t: string, h: () => void) => void };\n if (typeof g.addEventListener === 'function' && !this.onlineHandler) {\n this.onlineHandler = () => {\n void this.drainOfflineQueue();\n };\n g.addEventListener('online', this.onlineHandler);\n }\n }\n\n /** Stop timers and listeners (does not flush). */\n stop(): void {\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n const g = globalThis as { removeEventListener?: (t: string, h: () => void) => void };\n if (this.onlineHandler && typeof g.removeEventListener === 'function') {\n g.removeEventListener('online', this.onlineHandler);\n this.onlineHandler = null;\n }\n }\n\n /** Permanently disable the transport (401/403). Drops pending work. */\n disable(): void {\n this.disabled = true;\n this.pending = [];\n this.stop();\n }\n\n /** Whether the transport still accepts items (false once auth-disabled by a 401/403). */\n isEnabled(): boolean {\n return !this.disabled;\n }\n\n /** Queue an item for the next batch; flush eagerly once the batch is full. */\n send(item: EnvelopeItem): void {\n if (this.disabled) return;\n this.pending.push(item);\n if (this.pending.length >= this.maxBatch) {\n void this.flush();\n }\n }\n\n /**\n * Flush all pending items (plus a drain of the offline queue). Resolves to\n * `true` on completion, or `false` if `timeoutMs` elapsed first.\n */\n async flush(timeoutMs?: number): Promise<boolean> {\n if (this.disabled) return true;\n const items = this.pending.splice(0, this.pending.length);\n\n const work = (async (): Promise<boolean> => {\n await this.drainOfflineQueue();\n for (let i = 0; i < items.length; i += this.maxBatch) {\n await this.deliver(items.slice(i, i + this.maxBatch));\n }\n return true;\n })();\n\n if (typeof timeoutMs === 'number' && timeoutMs >= 0) {\n return Promise.race([work, delay(timeoutMs).then(() => false)]);\n }\n return work;\n }\n\n /** Send an already-serialized batch, applying the retry/backoff policy. */\n private async deliver(items: EnvelopeItem[], attempt = 0): Promise<void> {\n if (this.disabled || items.length === 0) return;\n\n const json = safeStringify(this.makeEnvelope(items));\n let outcome: SendOutcome;\n try {\n outcome = await this.post(json);\n } catch {\n outcome = { action: 'retry_backoff' }; // network error\n }\n\n switch (outcome.action) {\n case 'drop':\n return;\n case 'disable':\n this.logger.warn('server rejected credentials; disabling client');\n // Flip our own latch FIRST — `disabled` (and therefore `isEnabled()`)\n // must already be true by the time the client hears about it, so a\n // client whose enabled predicate is computed from us (not pushed to)\n // can never observe a stale \"still enabled\" in between.\n this.disable();\n this.onDisable();\n return;\n case 'split': {\n if (items.length <= 1) {\n this.logger.warn('single item too large (413); parking offline');\n this.offline.enqueue(json);\n return;\n }\n const mid = Math.ceil(items.length / 2);\n await this.deliver(items.slice(0, mid), attempt);\n await this.deliver(items.slice(mid), attempt);\n return;\n }\n case 'retry_after':\n case 'retry_backoff': {\n if (attempt >= MAX_RETRIES) {\n this.offline.enqueue(json);\n return;\n }\n const wait =\n outcome.action === 'retry_after'\n ? (outcome.retryAfterMs ?? 1000)\n : computeBackoff(attempt);\n await delay(wait);\n return this.deliver(items, attempt + 1);\n }\n }\n }\n\n /**\n * Re-attempt any envelopes that were parked while offline.\n *\n * `drain()` empties `localStorage` in one shot, so from here on the ONLY copy\n * of the backlog is the local `payloads` array. Every early return therefore\n * has to re-park the whole untried remainder, not just the payload that\n * failed: this used to re-park the failing one and return, which silently\n * deleted every payload behind it — the exact reconnect-then-one-500 case the\n * queue exists for.\n */\n async drainOfflineQueue(): Promise<void> {\n if (this.disabled || !this.offline.available) return;\n const payloads = this.offline.drain();\n for (let i = 0; i < payloads.length; i++) {\n const json = payloads[i];\n let outcome: SendOutcome;\n try {\n outcome = await this.post(json);\n } catch {\n outcome = { action: 'retry_backoff' };\n }\n if (outcome.action === 'disable') {\n this.logger.warn('server rejected credentials while draining; disabling client');\n this.disable();\n this.onDisable();\n // The credentials may be fixed and the client re-inited; keep the\n // backlog rather than throwing it away on the way out.\n this.offline.requeueFront(payloads.slice(i));\n return;\n }\n if (outcome.action === 'retry_after' || outcome.action === 'retry_backoff') {\n // Still failing — re-park this payload AND everything after it, then\n // stop draining to avoid a tight loop.\n this.offline.requeueFront(payloads.slice(i));\n return;\n }\n // drop / split: treat as handled.\n }\n }\n\n /** Best-effort synchronous-ish flush for page unload via `sendBeacon`. */\n flushToBeacon(): void {\n if (this.disabled) return;\n const all = this.pending.splice(0, this.pending.length);\n if (all.length === 0) return;\n\n // Chunk like the normal path already does. This one sent everything\n // buffered as a single envelope, so unloading after a busy session could\n // exceed the server's per-envelope item limit — a non-retryable 400, and\n // there is no page left to retry from.\n for (let i = 0; i < all.length; i += MAX_ITEMS_PER_ENVELOPE) {\n this.beaconChunk(all.slice(i, i + MAX_ITEMS_PER_ENVELOPE));\n }\n }\n\n private beaconChunk(items: EnvelopeItem[]): void {\n const json = safeStringify(this.makeEnvelope(items));\n const nav = (globalThis as { navigator?: Navigator }).navigator;\n const size = byteLength(json);\n\n if (nav && typeof nav.sendBeacon === 'function' && size <= BEACON_MAX_BYTES) {\n try {\n const blob = new Blob([json], { type: 'application/json' });\n if (nav.sendBeacon(this.dsn.beaconUrl, blob)) return;\n } catch {\n /* fall through to offline queue */\n }\n }\n // Beacon unavailable or oversized: persist for the next page load.\n this.offline.enqueue(json);\n }\n\n /** Compress (when large) and POST one serialized envelope. */\n private async post(json: string): Promise<SendOutcome> {\n const { body, encoding } = await maybeCompress(json);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Sauron-Key': this.dsn.publicKey,\n };\n if (encoding) headers['Content-Encoding'] = encoding;\n\n const size = typeof body === 'string' ? byteLength(body) : body.byteLength;\n const result = await this.doRequest(headers, body, size <= BEACON_MAX_BYTES);\n return classifyStatus(result.status, result.retryAfter);\n }\n\n private async doRequest(\n headers: Record<string, string>,\n body: Uint8Array | string,\n keepalive: boolean,\n ): Promise<HttpResult> {\n if (this.fetchImpl) {\n beginInternal();\n let promise: Promise<Response>;\n try {\n promise = this.fetchImpl(this.dsn.envelopeUrl, {\n method: 'POST',\n headers,\n body: body as BodyInit,\n keepalive,\n });\n } finally {\n endInternal();\n }\n const res = await promise;\n return { status: res.status, retryAfter: res.headers?.get?.('Retry-After') ?? null };\n }\n return this.xhrRequest(headers, body);\n }\n\n private xhrRequest(\n headers: Record<string, string>,\n body: Uint8Array | string,\n ): Promise<HttpResult> {\n return new Promise<HttpResult>((resolve, reject) => {\n const XHR = (globalThis as { XMLHttpRequest?: typeof XMLHttpRequest }).XMLHttpRequest;\n if (typeof XHR !== 'function') {\n reject(new Error('no transport available'));\n return;\n }\n beginInternal();\n try {\n const xhr = new XHR();\n xhr.open('POST', this.dsn.envelopeUrl, true);\n for (const key of Object.keys(headers)) {\n try {\n xhr.setRequestHeader(key, headers[key]);\n } catch {\n /* forbidden header — skip */\n }\n }\n xhr.onload = () =>\n resolve({ status: xhr.status, retryAfter: safeHeader(xhr, 'Retry-After') });\n xhr.onerror = () => reject(new Error('xhr network error'));\n xhr.ontimeout = () => reject(new Error('xhr timeout'));\n xhr.send(body as XMLHttpRequestBodyInit);\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n } finally {\n endInternal();\n }\n });\n }\n\n /** Offline queue accessor (used by tests / diagnostics). */\n get offlineQueue(): OfflineQueue {\n return this.offline;\n }\n}\n\nfunction safeHeader(xhr: XMLHttpRequest, name: string): string | null {\n try {\n return xhr.getResponseHeader(name);\n } catch {\n return null;\n }\n}\n","import { buildContext } from './context.js';\nimport { parseDsn, type Dsn } from './dsn.js';\nimport { buildEnvelope } from './envelope.js';\nimport {\n clearLastIdentified,\n getAnonymousId,\n getDeviceId,\n getLastIdentified,\n getSessionId,\n hashIdentity,\n resetAnonymousId,\n rotateSessionId,\n setLastIdentified,\n} from './identity.js';\nimport { installConsole } from './integrations/console.js';\nimport { installDom } from './integrations/dom.js';\nimport { installFetch } from './integrations/fetch.js';\nimport { installGlobalHandlers } from './integrations/globalHandlers.js';\nimport { installHistory, onNavigation } from './integrations/history.js';\nimport * as instrument from './integrations/instrument.js';\nimport { installPerformance } from './integrations/performance.js';\nimport { installXhr } from './integrations/xhr.js';\nimport { setScreen } from './api/product.js';\nimport { Scope, mergeMeta } from './scope.js';\nimport { resetScreen, setScreenState } from './screen.js';\nimport { getWorkflow, resetWorkflow } from './workflow.js';\nimport { installBeacon } from './transport/beacon.js';\nimport { Transport } from './transport/transport.js';\nimport type {\n Breadcrumb,\n Envelope,\n EnvelopeItem,\n ErrorItem,\n Hint,\n InitOptions,\n ResolvedOptions,\n} from './types.js';\nimport { clamp, makeLogger, nowIso, SDK_NAME, SDK_VERSION, uuidv4 } from './utils.js';\n\ntype Logger = ReturnType<typeof makeLogger>;\n\n/**\n * The Sauron client singleton. Owns the resolved options, the scope\n * (user + breadcrumbs), the transport, and the installed integrations.\n */\nexport class SauronClient {\n readonly options: ResolvedOptions;\n readonly dsn: Dsn;\n\n private readonly scope: Scope;\n private readonly transport: Transport;\n private readonly logger: Logger;\n private readonly nativeFetch?: typeof fetch;\n\n private enabled = true;\n private installed = false;\n private beaconCleanup: (() => void) | null = null;\n\n constructor(options: ResolvedOptions) {\n this.options = options;\n this.dsn = parseDsn(options.dsn);\n this.logger = makeLogger(options.debug);\n this.scope = new Scope(options.maxBreadcrumbs);\n // Seed init-default metadata into the global scope so every later signal\n // inherits it; runtime setters still last-write-win over these.\n this.scope.setTags(options.tags);\n for (const [name, block] of Object.entries(options.contexts)) {\n this.scope.setContext(name, block);\n }\n for (const [key, value] of Object.entries(options.extra)) {\n this.scope.setExtra(key, value);\n }\n\n // Capture the NATIVE fetch before any integration wraps it, so the\n // transport's own requests never hit our instrumentation.\n const g = globalThis as { fetch?: typeof fetch };\n this.nativeFetch = typeof g.fetch === 'function' ? g.fetch.bind(globalThis) : undefined;\n\n instrument.setDsnHost(this.dsn.host);\n\n this.transport = new Transport({\n dsn: this.dsn,\n options: options.transport,\n makeEnvelope: (items) => this.makeEnvelope(items),\n fetchImpl: this.nativeFetch,\n logger: this.logger,\n onDisable: () => this.disable(),\n });\n }\n\n /** Install global handlers + auto-instrumentation and start the transport. */\n install(): void {\n if (this.installed) return;\n this.installed = true;\n\n // Establish the durable device id and the current session id at init.\n getDeviceId();\n getSessionId();\n\n installGlobalHandlers();\n installConsole();\n installDom();\n installHistory();\n installFetch();\n installXhr();\n if (this.options.performance) installPerformance();\n\n // Screen tracking: seed the initial screen, then follow SPA navigations.\n if (this.options.screen) setScreenState(this.options.screen);\n if (this.options.screenTracking) {\n onNavigation((path) => setScreen(path));\n }\n\n this.beaconCleanup = installBeacon(this.transport);\n\n this.transport.start();\n void this.transport.drainOfflineQueue();\n this.logger.log('initialized', { dsn: this.dsn.host, project: this.dsn.projectId });\n }\n\n getScope(): Scope {\n return this.scope;\n }\n\n /**\n * False once this client was explicitly disabled/closed, OR once the\n * transport has auto-disabled itself on a 401/403 (revoked/invalid DSN\n * key) — computed from the transport's own state on every call, not a\n * separately mirrored flag, so a propagation regression there cannot leave\n * this predicate stale. `this.transport` always exists once a client\n * exists (it is constructed synchronously in the constructor); the\n * \"nothing installed yet\" case is instead handled one layer up, by every\n * module-level API (`startWorkflow`, `track`, ...) treating `getClient() ===\n * null` as the no-op/disabled case before it ever reaches here.\n */\n isEnabled(): boolean {\n return this.enabled && this.transport.isEnabled();\n }\n\n /**\n * Whether the anonymous id has actually been USED as a `distinct_id` in this\n * browser session.\n *\n * A persisted id that has never been observed anonymously must not create a\n * permanent `identities` alias row on the server: aliasing is a durable\n * server-side binding of this browser profile to a named user, and an\n * identify() on a first-ever page load has no anonymous history to link.\n */\n private anonUsed = false;\n\n /** The current distinct id: the user id when identified, else an anon id. */\n getDistinctId(): string | null {\n const user = this.scope.getUser();\n if (user.id) return user.id;\n this.anonUsed = true;\n return getAnonymousId();\n }\n\n /** The anonymous id, or null when it was never actually used as an identity. */\n getAnonymousId(): string | null {\n return this.anonUsed ? getAnonymousId() : null;\n }\n\n /**\n * Forget the current person: clear the scope user, mint a fresh anonymous\n * id, forget the last identified user, and rotate the session id.\n *\n * MUST BE CALLED ON LOGOUT. Without it, the next anonymous visitor on this\n * browser reuses the persisted anon id, and a later identify() aliases their\n * activity to the previous account server-side, permanently. Rotating the\n * session id matters too: the server's `bump_session` is last-write-wins on\n * `distinct_id`, so without rotation one `sessions` row could otherwise\n * serially represent two different people and record only whichever wrote\n * last.\n */\n reset(): void {\n this.scope.setUser(null);\n resetAnonymousId();\n clearLastIdentified();\n rotateSessionId();\n this.anonUsed = false;\n }\n\n /**\n * Prepare for an `identify()`; returns the `anonymous_id` to send.\n *\n * When a DIFFERENT user identifies than last time, the current anon id\n * belongs to the previous person and is already burned server-side, so it is\n * replaced before anything else happens and `null` is sent instead of a\n * cross-user alias. This cannot repair events already sent under the burned\n * alias — nothing can — but it bounds a forgotten `reset()` to one guest\n * window instead of every future one.\n *\n * `id` is coerced with `String()` before comparing/persisting: a plain-JS\n * caller can pass a number (`Sauron.identify(user.id)`), and `Storage`\n * itself applies `ToString` on write — so comparing an un-coerced `id`\n * against a value that already round-tripped through storage would treat\n * the SAME numeric user as a switch on every single call. The comparison\n * against `last` is an explicit `!== null` (not a truthiness check) so an\n * app that (unusually) identifies with `''` still has a later, different id\n * correctly detected as a real switch — a falsy string is not \"no identity\n * yet\". `last`/the persisted value are digests, not the raw id — see\n * `hashIdentity`.\n */\n prepareIdentify(id: string): string | null {\n const digest = hashIdentity(String(id));\n const last = getLastIdentified();\n if (last !== null && last !== digest) {\n resetAnonymousId();\n rotateSessionId();\n this.anonUsed = false;\n }\n setLastIdentified(digest);\n return this.getAnonymousId();\n }\n\n /** Stamp a fresh envelope (new `sent_at`, current context) around `items`. */\n makeEnvelope(items: EnvelopeItem[]): Envelope {\n const header = {\n dsn: this.dsn.raw,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n sent_at: nowIso(),\n release: this.options.release,\n };\n const context = buildContext(this.options.release, this.scope.getUser());\n return buildEnvelope(header, context, items);\n }\n\n /** Add a breadcrumb, running it through `beforeBreadcrumb` first. */\n addBreadcrumb(breadcrumb: Breadcrumb, hint?: Hint): void {\n if (!this.enabled) return;\n let processed: Breadcrumb | null = breadcrumb;\n if (this.options.beforeBreadcrumb) {\n try {\n processed = this.options.beforeBreadcrumb(breadcrumb, hint);\n } catch (err) {\n this.logger.warn('beforeBreadcrumb threw', err);\n processed = breadcrumb;\n }\n }\n if (!processed) return;\n this.scope.addBreadcrumb(processed);\n }\n\n /**\n * Reconcile an error item to the shared wire shape by filling the optional\n * `event_id`/`message`/`tags`/`user` fields from the current scope and hint.\n * Each field is left untouched when the item already sets it, and omitted\n * entirely when there is nothing to attach (the backend defaults it) — only\n * `event_id` is always minted so callers can correlate the report.\n */\n private enrichErrorItem(item: ErrorItem, hint?: Hint): void {\n if (item.event_id === undefined) {\n const hinted = hint?.event_id;\n item.event_id = typeof hinted === 'string' ? hinted : uuidv4();\n }\n if (item.message === undefined && typeof hint?.message === 'string') {\n item.message = hint.message;\n }\n const tags = mergeMeta(this.scope.tags, item.tags);\n if (Object.keys(tags).length > 0) item.tags = tags;\n const contexts = mergeMeta(this.scope.contexts, item.contexts);\n if (Object.keys(contexts).length > 0) item.contexts = contexts;\n const extra = mergeMeta(this.scope.extra, item.extra);\n if (Object.keys(extra).length > 0) item.extra = extra;\n if (item.user === undefined && this.scope.hasUser()) {\n item.user = this.scope.getUser();\n }\n }\n\n /**\n * Stamp the active workflow (if any) onto a signal item.\n *\n * Done HERE — the single choke point every capture path funnels through —\n * rather than at each item-construction site, so a capture path added later\n * is stamped by construction instead of by remembering to. The keys are\n * ASSIGNED ONLY when a workflow is active: an item with no workflow keeps\n * them absent entirely (not present-as-`undefined`), which is what makes\n * `JSON.stringify` omit them and keeps the no-workflow wire bytes identical\n * to pre-1.3.0.\n *\n * Only error/event/transaction carry `workflow_id`/`workflow_name` columns\n * server-side — identify and breadcrumb_batch items are deliberately left\n * alone. An item that already carries an explicit `workflow_id` is left\n * untouched, matching how `enrichErrorItem` defers to caller-set fields.\n */\n private stampWorkflow(item: EnvelopeItem): void {\n if (item.type !== 'error' && item.type !== 'event' && item.type !== 'transaction') return;\n\n // `captureItem` is a public escape hatch, so an item can arrive already\n // attributed. Caller-set wins — same rule `enrichErrorItem` applies to\n // `event_id`/`message`/`user`.\n //\n // But the two fields are a PAIR, not two independent options: the server\n // guards on `if let (Some(id), Some(name))`, so an item carrying only one\n // of them is silently dropped from every workflow query. That failure is\n // invisible, so warn rather than let it through quietly — and still leave\n // the item alone, because overwriting a caller's deliberate (if partial)\n // attribution with a different workflow would be worse than not stamping.\n const hasId = item.workflow_id !== undefined;\n const hasName = item.workflow_name !== undefined;\n if (hasId || hasName) {\n if (hasId !== hasName) {\n this.logger.warn(\n 'item sets only one of workflow_id/workflow_name; the server treats them as a ' +\n 'pair and will drop this attribution. Set both, or neither.',\n );\n }\n return;\n }\n\n const workflow = getWorkflow();\n if (!workflow) return;\n item.workflow_id = workflow.workflowId;\n item.workflow_name = workflow.name;\n }\n\n /**\n * Run an item through sampling (errors only) and `beforeSend`, then hand it to\n * the transport. Returns silently when dropped.\n */\n captureItem(item: EnvelopeItem, hint?: Hint): void {\n if (!this.enabled) return;\n\n if (item.type === 'error') {\n if (Math.random() >= this.options.sampleRate) {\n this.logger.log('dropped error by sampleRate');\n return;\n }\n this.enrichErrorItem(item, hint);\n }\n\n // Before `beforeSend`, so a consumer's hook sees the workflow fields.\n this.stampWorkflow(item);\n\n let processed: EnvelopeItem | null = item;\n if (this.options.beforeSend) {\n try {\n processed = this.options.beforeSend(item, hint);\n } catch (err) {\n this.logger.warn('beforeSend threw', err);\n processed = item;\n }\n }\n if (!processed) {\n this.logger.log('dropped by beforeSend');\n return;\n }\n\n this.transport.send(processed);\n }\n\n /** Flush pending events. Resolves false if `timeoutMs` elapses first. */\n flush(timeoutMs?: number): Promise<boolean> {\n return this.transport.flush(timeoutMs);\n }\n\n /** Disable the client (called on 401/403). Stops accepting/sending events. */\n disable(): void {\n if (!this.enabled) return;\n this.enabled = false;\n this.transport.disable();\n this.logger.warn('client disabled');\n }\n\n /** Restore all patched globals and stop timers/listeners. */\n teardown(): void {\n this.enabled = false;\n this.transport.stop();\n if (this.beaconCleanup) {\n this.beaconCleanup();\n this.beaconCleanup = null;\n }\n onNavigation(null);\n resetScreen();\n resetWorkflow();\n instrument.unpatchAll();\n instrument.setDsnHost(null);\n this.installed = false;\n }\n\n /** Flush then tear down. Resolves to the flush result. */\n async close(timeoutMs?: number): Promise<boolean> {\n const flushed = await this.transport.flush(timeoutMs);\n this.teardown();\n return flushed;\n }\n}\n\n/* ---------------------------------------------------------------- singleton */\n\nlet currentClient: SauronClient | null = null;\n\n/** The active client, or null before `init`. */\nexport function getClient(): SauronClient | null {\n return currentClient;\n}\n\nfunction resolveOptions(options: InitOptions): ResolvedOptions {\n if (!options || typeof options.dsn !== 'string' || options.dsn.length === 0) {\n throw new Error('[sauron] init() requires a `dsn`');\n }\n const t = options.transport ?? {};\n return {\n dsn: options.dsn,\n release: options.release ?? null,\n sampleRate: clamp(options.sampleRate ?? 1, 0, 1),\n maxBreadcrumbs: options.maxBreadcrumbs ?? 50,\n tags: options.tags ?? {},\n contexts: options.contexts ?? {},\n extra: options.extra ?? {},\n beforeSend: options.beforeSend,\n beforeBreadcrumb: options.beforeBreadcrumb,\n transport: {\n flushIntervalMs: t.flushIntervalMs ?? 5000,\n maxBatch: t.maxBatch ?? 30,\n maxQueueBytes: t.maxQueueBytes ?? 1048576,\n },\n performance: options.performance ?? false,\n screen: options.screen,\n screenTracking: options.screenTracking ?? false,\n debug: options.debug ?? false,\n };\n}\n\n/**\n * Initialize the SDK. Idempotent: a second call tears down the previous client\n * (restoring patched globals) before installing a fresh one.\n */\nexport function init(options: InitOptions): SauronClient {\n if (currentClient) {\n try {\n currentClient.teardown();\n } catch {\n /* ignore teardown failures */\n }\n }\n const resolved = resolveOptions(options);\n const client = new SauronClient(resolved);\n currentClient = client;\n client.install();\n return client;\n}\n","import { getClient } from '../client.js';\nimport type { Breadcrumb, Hint, Level } from '../types.js';\nimport { nowIso } from '../utils.js';\n\n/** Partial breadcrumb — missing fields are filled with sensible defaults. */\nexport interface BreadcrumbInput {\n type?: string;\n category?: string;\n message?: string | null;\n level?: Level;\n timestamp?: string;\n data?: Record<string, unknown> | null;\n}\n\n/** Normalize a partial breadcrumb into the full wire shape. */\nexport function normalizeBreadcrumb(input: BreadcrumbInput): Breadcrumb {\n return {\n type: input.type ?? 'default',\n category: input.category ?? 'default',\n message: input.message ?? null,\n level: input.level ?? 'info',\n timestamp: input.timestamp ?? nowIso(),\n data: input.data ?? null,\n };\n}\n\n/**\n * Record a breadcrumb. Runs through `beforeBreadcrumb` (the PII escape hatch)\n * and is stored in the ring buffer — nothing is sent until an error is captured.\n */\nexport function addBreadcrumb(input: BreadcrumbInput, hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n client.addBreadcrumb(normalizeBreadcrumb(input), hint);\n}\n\n/** Convenience helper for navigation breadcrumbs. */\nexport function addNavigationBreadcrumb(from: string | null, to: string | null): void {\n addBreadcrumb({\n type: 'navigation',\n category: 'history',\n level: 'info',\n message: null,\n data: { from, to },\n });\n}\n","/**\n * `@edraj/sauron-browser` — public API surface.\n *\n * Error reporting + product analytics for the browser. Import the named\n * functions, or the `Sauron` facade / default export.\n *\n * ```ts\n * import { Sauron } from '@edraj/sauron-browser';\n * Sauron.init({ dsn: 'https://pk_test@localhost:8081/1', release: 'web@1.4.2' });\n * Sauron.track('checkout_completed', { cart_value: 42.5 });\n * ```\n */\n\nimport { addBreadcrumb as addBreadcrumbApi, type BreadcrumbInput } from './api/breadcrumbs.js';\nimport { captureException as captureExceptionApi, captureMessage as captureMessageApi } from './api/capture.js';\nimport {\n cancelWorkflow as cancelWorkflowApi,\n endWorkflow as endWorkflowApi,\n identify as identifyApi,\n setScreen as setScreenApi,\n startWorkflow as startWorkflowApi,\n track as trackApi,\n trackTransaction as trackTransactionApi,\n type TransactionInput,\n} from './api/product.js';\nimport { getClient, init as initClient, SauronClient } from './client.js';\nimport { getScreen as getScreenApi } from './screen.js';\nimport type {\n ActiveWorkflow,\n Hint,\n InitOptions,\n Level,\n TrackOptions,\n UserInput,\n WorkflowResult,\n} from './types.js';\nimport { getWorkflow as getWorkflowApi } from './workflow.js';\n\n/** Initialize the SDK. See {@link InitOptions}. */\nexport function init(options: InitOptions): SauronClient {\n return initClient(options);\n}\n\n/** Capture an exception (or any thrown value). */\nexport function captureException(err: unknown, hint?: Hint): void {\n captureExceptionApi(err, hint);\n}\n\n/** Capture a plain message at the given `level` (default `info`). */\nexport function captureMessage(message: string, level: Level = 'info', hint?: Hint): void {\n captureMessageApi(message, level, hint);\n}\n\n/** Record a product-analytics event, optionally with per-call tags/contexts/extra. */\nexport function track(\n name: string,\n properties?: Record<string, unknown>,\n options?: TrackOptions,\n): void {\n trackApi(name, properties, options);\n}\n\n/**\n * Associate the session with a known user.\n *\n * The `anonymous_id` sent with the identify item is the current anon id — but\n * only when it was actually used as a `distinct_id` this session, and never\n * when it belongs to a different person than the last one who identified on\n * this device. In that case a fresh anon id is minted first and `null` is\n * sent instead, since the old one is already permanently bound to the\n * previous person server-side (see `reset()`).\n */\nexport function identify(id: string, traits?: Record<string, unknown>): void {\n identifyApi(id, traits);\n}\n\n/** Record a performance transaction (navigation, http, screen load, ...). */\nexport function trackTransaction(input: TransactionInput): void {\n trackTransactionApi(input);\n}\n\n/** Set the current screen (emits a `$screen` view on change). */\nexport function setScreen(name: string): void {\n setScreenApi(name);\n}\n\n/** The current screen name, or null. */\nexport function getScreen(): string | null {\n return getScreenApi();\n}\n\n/**\n * Start a named, explicitly-bounded workflow. `workflow_id` is a fresh\n * client-generated UUID; the id + name are then stamped on every subsequent\n * event/error/transaction until the workflow ends or is cancelled. Optional —\n * an app that never calls this behaves exactly as before.\n */\nexport function startWorkflow(name: string, options?: { force?: boolean }): WorkflowResult {\n return startWorkflowApi(name, options);\n}\n\n/** End the active workflow (or the one named `name`, if given). */\nexport function endWorkflow(name?: string): WorkflowResult {\n return endWorkflowApi(name);\n}\n\n/** Cancel the active workflow (or the one named `name`, if given). */\nexport function cancelWorkflow(name?: string, options?: { reason?: string }): WorkflowResult {\n return cancelWorkflowApi(name, options);\n}\n\n/** The currently active workflow, or `null` when none is active. */\nexport function getWorkflow(): ActiveWorkflow | null {\n return getWorkflowApi();\n}\n\n/** Record a breadcrumb. */\nexport function addBreadcrumb(breadcrumb: BreadcrumbInput, hint?: Hint): void {\n addBreadcrumbApi(breadcrumb, hint);\n}\n\n/**\n * Set (or clear, with `null`) the current user.\n *\n * `setUser(null)` is a logout, so it also calls `reset()` for you — otherwise\n * the next anonymous visitor on this browser inherits the previous person's\n * durable id and a later identify() aliases them together server-side.\n */\nexport function setUser(user: UserInput): void {\n if (user === null) {\n getClient()?.reset();\n return;\n }\n getClient()?.getScope().setUser(user);\n}\n\n/**\n * Forget the current person: clears the scope user, mints a fresh anonymous\n * id, forgets the last identified user, and rotates the session id so a\n * single session can never span two different people. Call this on logout.\n */\nexport function reset(): void {\n getClient()?.reset();\n}\n\n/** Set a single scope tag (lifted onto later errors/events). */\nexport function setTag(key: string, value: string): void {\n getClient()?.getScope().setTag(key, value);\n}\n\n/** Merge a batch of scope tags (last-write-wins per key). */\nexport function setTags(tags: Record<string, string>): void {\n getClient()?.getScope().setTags(tags);\n}\n\n/** Set (replace) a named scope context block. */\nexport function setContext(name: string, block: Record<string, unknown>): void {\n getClient()?.getScope().setContext(name, block);\n}\n\n/** Set a single freeform scope extra value. */\nexport function setExtra(key: string, value: unknown): void {\n getClient()?.getScope().setExtra(key, value);\n}\n\n/** Flush pending events. Resolves `false` if `timeoutMs` elapses first. */\nexport function flush(timeoutMs?: number): Promise<boolean> {\n const client = getClient();\n return client ? client.flush(timeoutMs) : Promise.resolve(false);\n}\n\n/** Flush and tear down the SDK, restoring all patched globals. */\nexport function close(timeoutMs?: number): Promise<boolean> {\n const client = getClient();\n return client ? client.close(timeoutMs) : Promise.resolve(false);\n}\n\n/** The active client instance, or `null` before `init`. */\nexport { getClient, SauronClient };\n\n/** Grouped facade + default export. */\nexport const Sauron = {\n init,\n captureException,\n captureMessage,\n track,\n trackTransaction,\n identify,\n addBreadcrumb,\n setUser,\n reset,\n setTag,\n setTags,\n setContext,\n setExtra,\n setScreen,\n getScreen,\n startWorkflow,\n endWorkflow,\n cancelWorkflow,\n getWorkflow,\n flush,\n close,\n getClient,\n};\n\nexport default Sauron;\n\n/* ------------------------------------------------------------- re-exports */\n\nexport { parseDsn, DsnError } from './dsn.js';\nexport type { Dsn } from './dsn.js';\nexport { buildEnvelope } from './envelope.js';\nexport { parseStackString, parseError, isInAppFrame } from './stacktrace/parse.js';\nexport { SDK_NAME, SDK_VERSION } from './utils.js';\n// Exported so a caller can size a payload BEFORE attaching it — the cap is\n// otherwise invisible until the dashboard shows a truncation marker.\nexport { MAX_TRANSACTION_EXTRA_BYTES, capTransactionExtra } from './utils.js';\nexport type { BreadcrumbInput } from './api/breadcrumbs.js';\nexport type { TransactionInput } from './api/product.js';\n\nexport type {\n Level,\n ItemType,\n TransactionOp,\n Frame,\n Mechanism,\n ExceptionValue,\n Breadcrumb,\n ErrorItem,\n EventItem,\n IdentifyItem,\n BreadcrumbBatchItem,\n TransactionItem,\n EnvelopeItem,\n DeviceContext,\n OsContext,\n AppContext,\n RuntimeContext,\n UserContext,\n Context,\n SdkInfo,\n EnvelopeHeader,\n Envelope,\n Hint,\n UserInput,\n BeforeSend,\n BeforeBreadcrumb,\n TransportOptions,\n InitOptions,\n CaptureOptions,\n TrackOptions,\n ResolvedOptions,\n WorkflowStatus,\n WorkflowResult,\n ActiveWorkflow,\n} from './types.js';\n"]}
1
+ {"version":3,"sources":["../src/utils.ts","../src/identity.ts","../src/context.ts","../src/dsn.ts","../src/envelope.ts","../src/integrations/instrument.ts","../src/integrations/console.ts","../src/integrations/dom.ts","../src/integrations/fetch.ts","../src/screen.ts","../src/stacktrace/parse.ts","../src/api/capture.ts","../src/integrations/globalHandlers.ts","../src/integrations/history.ts","../src/scope.ts","../src/workflow.ts","../src/api/product.ts","../src/integrations/performance.ts","../src/integrations/xhr.ts","../src/transport/beacon.ts","../src/transport/compress.ts","../src/transport/queue.ts","../src/transport/transport.ts","../src/client.ts","../src/api/breadcrumbs.ts","../src/index.ts"],"names":["g","init","anonymousId","sessionId","resolveUrl","resolveMethod","flush","captureException","captureMessage","track","identify","trackTransaction","setScreen","getScreen","startWorkflow","endWorkflow","cancelWorkflow","getWorkflow","addBreadcrumb"],"mappings":";;;;;;;;;AAGO,IAAM,QAAA,GAAW;AACjB,IAAM,WAAA,GAAc;AAGpB,SAAS,SAAA,GAA+B;AAC7C,EAAA,OAAO,UAAA;AACT;AAOA,SAAS,SAAA,GAAoC;AAC3C,EAAA,MAAMA,KAAI,SAAA,EAAU;AACpB,EAAA,OAAOA,EAAAA,CAAE,MAAA;AACX;AAGO,SAAS,MAAA,GAAiB;AAC/B,EAAA,MAAM,I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A,EAAS,CAAE,QAAA,CAAS,KAAK,KAAK,CAAA;AAC7C;AAGO,SAAS,MAAM,SAAA,EAAsC;AAC1D,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,OAAO,SAAS,MAAA,CAAO,KAAA,CAAM,SAAS,CAAA,GAAI,OAAA,CAAQ,QAAQ,KAAK,CAAA;AACjE;AAGO,SAAS,MAAM,SAAA,EAAsC;AAC1D,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,OAAO,SAAS,MAAA,CAAO,KAAA,CAAM,SAAS,CAAA,GAAI,OAAA,CAAQ,QAAQ,KAAK,CAAA;AACjE;AAMO,IAAM,MAAA,GAAS;AAAA,EACpB,IAAA,EAAAjB,KAAAA;AAAA,EACA,gBAAA,EAAAM,iBAAAA;AAAA,EACA,cAAA,EAAAC,eAAAA;AAAA,EACA,KAAA,EAAAC,MAAAA;AAAA,EACA,gBAAA,EAAAE,iBAAAA;AAAA,EACA,QAAA,EAAAD,SAAAA;AAAA,EACA,aAAA,EAAAQ,cAAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA,EAAAN,UAAAA;AAAA,EACA,SAAA,EAAAC,UAAAA;AAAA,EACA,aAAA,EAAAC,cAAAA;AAAA,EACA,WAAA,EAAAC,YAAAA;AAAA,EACA,cAAA,EAAAC,eAAAA;AAAA,EACA,WAAA,EAAAC,YAAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF;AAEA,IAAO,aAAA,GAAQ","file":"index.cjs","sourcesContent":["/** Small dependency-free helpers shared across the SDK. */\n\n/** SDK identity, embedded in every envelope header. */\nexport const SDK_NAME = 'sauron.javascript';\nexport const SDK_VERSION = '1.6.0';\n\n/** The ambient global, regardless of environment (window / self / global). */\nexport function getGlobal(): typeof globalThis {\n return globalThis;\n}\n\ninterface CryptoLike {\n randomUUID?: () => string;\n getRandomValues?: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nfunction getCrypto(): CryptoLike | undefined {\n const g = getGlobal() as { crypto?: CryptoLike };\n return g.crypto;\n}\n\n/** RFC-4122 v4 UUID, using Web Crypto when available. */\nexport function uuidv4(): string {\n const c = getCrypto();\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n // Set version (4) and variant (10xx) bits.\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex: string[] = [];\n for (let i = 0; i < 16; i++) hex.push(bytes[i].toString(16).padStart(2, '0'));\n const s = hex.join('');\n return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;\n}\n\n/** Current time as an ISO-8601 UTC string, e.g. `2026-07-12T10:30:00.123Z`. */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\n/**\n * `JSON.stringify` that never throws: strips circular references, functions and\n * coerces bigint to string. Returns `\"{}\"` on catastrophic failure.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>();\n try {\n return JSON.stringify(value, (_key, val) => {\n if (typeof val === 'bigint') return val.toString();\n if (typeof val === 'function') return undefined;\n if (typeof val === 'object' && val !== null) {\n if (seen.has(val)) return '[Circular]';\n seen.add(val);\n }\n return val;\n });\n } catch {\n return '{}';\n }\n}\n\n/** UTF-8 byte length of a string. */\nexport function byteLength(s: string): number {\n if (typeof TextEncoder !== 'undefined') {\n return new TextEncoder().encode(s).length;\n }\n let len = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) len += 1;\n else if (c < 0x800) len += 2;\n else if (c >= 0xd800 && c <= 0xdbff) {\n len += 4;\n i++; // surrogate pair\n } else len += 3;\n }\n return len;\n}\n\n/**\n * Full-jitter exponential backoff, capped. Attempt 0 => up to `baseMs`,\n * attempt n => up to `min(capMs, baseMs * 2^n)`, then a uniform random point\n * in `[0, that]`.\n */\nexport function computeBackoff(attempt: number, baseMs = 1000, capMs = 30000): number {\n const ceiling = Math.min(capMs, baseMs * Math.pow(2, Math.max(0, attempt)));\n return Math.round(Math.random() * ceiling);\n}\n\n/** Clamp a number into `[min, max]`. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\n/** A tiny logger gated on `debug`. */\nexport function makeLogger(debug: boolean): {\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n} {\n const noop = (): void => {};\n if (!debug || typeof console === 'undefined') {\n return { log: noop, warn: noop };\n }\n return {\n log: (...args: unknown[]) => console.log('[sauron]', ...args),\n warn: (...args: unknown[]) => console.warn('[sauron]', ...args),\n };\n}\n\n/**\n * Largest serialized `extra` a single transaction may carry, in bytes.\n *\n * Transactions are the highest-volume signal and they ship in BATCHED\n * envelopes, so one oversized payload does not fail alone — ingest rejects the\n * whole envelope past `INGEST_MAX_BODY_BYTES` (1 MiB by default) and every\n * unrelated span batched with it is lost. Since the motivating use of\n * transaction `extra` is request and response bodies, that is not a remote\n * hazard.\n */\nexport const MAX_TRANSACTION_EXTRA_BYTES = 16 * 1024;\n\n/**\n * Cap a transaction's `extra`, substituting a marker when it is too large.\n *\n * Replaces the WHOLE map rather than trimming keys: a half-written JSON value\n * is worse than an honest marker, and per-key trimming would make the result\n * depend on key iteration order, which differs across the five SDKs. The\n * marker is deliberately readable on the dashboard — `_truncated` says data\n * was dropped rather than silently serving a short object that looks complete.\n *\n * Returns the input unchanged when it fits. A value that cannot be serialized\n * at all (a cycle, a BigInt) is replaced by the same marker with `_bytes: -1`,\n * because the alternative is throwing from inside `trackTransaction` — and an\n * SDK that crashes the app it is measuring is worse than one that drops a\n * payload.\n */\nexport function capTransactionExtra(\n extra: Record<string, unknown>,\n maxBytes = MAX_TRANSACTION_EXTRA_BYTES,\n): Record<string, unknown> {\n let bytes: number;\n try {\n const json = JSON.stringify(extra);\n if (json === undefined) return { _truncated: true, _bytes: -1 };\n // `Blob`/`Buffer` are not available everywhere this SDK runs; UTF-8 byte\n // length is what the wire actually costs, so it is computed rather than\n // approximated by `json.length` (which undercounts every non-ASCII byte —\n // exactly what a response body full of user text contains).\n bytes = utf8Length(json);\n } catch {\n return { _truncated: true, _bytes: -1 };\n }\n if (bytes <= maxBytes) return extra;\n return { _truncated: true, _bytes: bytes };\n}\n\n/** UTF-8 byte length of a string, without depending on `TextEncoder`. */\nfunction utf8Length(s: string): number {\n let n = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) n += 1;\n else if (c < 0x800) n += 2;\n else if (c >= 0xd800 && c <= 0xdbff) {\n // A surrogate PAIR is one 4-byte code point; advance past its low half\n // so it is not counted twice.\n n += 4;\n i++;\n } else n += 3;\n }\n return n;\n}\n","/**\n * Stable device + session identity.\n *\n * - `device_id` is persisted in `localStorage` (`sauron.device_id`) so it\n * survives reloads and tabs — the backend uses it as the durable device\n * identity (`context.device.device_id`).\n * - `session_id` is persisted in `sessionStorage` (`sauron.session_id`) so it is\n * shared across a tab's page loads but starts fresh for a new browsing\n * session. It is attached to every event, error and transaction item.\n * - `last_identified` is persisted in `localStorage` (`sauron.last_identified`)\n * as a short one-way digest (`hashIdentity`) of the id passed to\n * `identify()` — never the identifier itself — so a login by a DIFFERENT\n * user than last time can be detected even when the app never wired\n * `reset()` on logout — see `SauronClient.prepareIdentify`.\n *\n * All degrade gracefully: with no writable Web Storage (SSR, private mode,\n * blocked cookies) we fall back to a per-process id generated once in memory.\n */\n\nimport { uuidv4 } from './utils.js';\n\n/** localStorage key holding the durable device id. */\nexport const DEVICE_ID_KEY = 'sauron.device_id';\n/** sessionStorage key holding the per-session id. */\nexport const SESSION_ID_KEY = 'sauron.session_id';\n/**\n * localStorage key holding the durable anonymous id.\n *\n * It used to live in a field on the client, re-minted on every page load, so\n * `track()` sent a new `distinct_id` each time and active users for any web app\n * counted PAGE LOADS, not people — a systematic 5-10x inflation, all of it\n * landing in the guest half of the report.\n *\n * Persisting it is a retention and consent consequence, not just an\n * implementation detail: the anon id becomes a durable first-party identifier\n * stored on the user's terminal. It is also why `reset()` exists — see\n * `SauronClient.reset`.\n */\nexport const ANON_ID_KEY = 'sauron.anon_id';\n/**\n * localStorage key holding a short one-way digest (`hashIdentity`) of the id\n * of the last user who called `identify()` — never the identifier itself,\n * which is very often personally identifying (an email, a username) and would\n * otherwise become a second, durable, plaintext copy of it.\n *\n * Exists so a login by a DIFFERENT user can be detected on a device where the\n * app never wired `reset()` on logout. Without it, person B's anonymous\n * activity keeps flowing under person A's already-burned alias, and the server\n * resolves it to A — permanently, and with no client-side symptom.\n */\nexport const LAST_IDENTIFIED_KEY = 'sauron.last_identified';\n\n/**\n * Format tag prefixed to the stored `sauron.last_identified` value, as\n * `<tag>:<digest>`.\n *\n * `hashIdentity`'s output has already changed shape once (8 hex digits → 16),\n * and an untagged store cannot tell \"a digest in a format I no longer\n * produce\" from \"a digest of a different person\". Both read as a SWITCH, so a\n * widening would mint a fresh anonymous id and rotate the session for every\n * returning user on their next `identify()` — once, silently, with no error\n * and nothing in the data saying why guest counts moved.\n *\n * With the tag, an unrecognised (or absent) prefix reads as **no previous\n * identity**, which is the safe reading: the first identify on a device is\n * never a switch, so nothing is rotated and the next write re-tags the entry\n * in the current format. The cost of guessing wrong that way is one missed\n * switch on one device — the same exposure as before anything was persisted\n * at all — instead of a fleet-wide rotation.\n *\n * Byte-compatible with the Flutter SDK, which writes the identical\n * `<tag>:<digest>` string under the same key (see\n * `LastIdentifiedStore` in `sdks/flutter/lib/src/context/last_identified_store.dart`).\n * The tag is on the STORED VALUE, not on `hashIdentity` itself, so the\n * cross-SDK digest golden is unaffected by it.\n */\nexport const LAST_IDENTIFIED_FORMAT = 'v1';\n\n/** Wrap a digest in the current storage format. */\nfunction encodeLastIdentified(digest: string): string {\n return `${LAST_IDENTIFIED_FORMAT}:${digest}`;\n}\n\n/**\n * Unwrap a stored value, or `null` if it is not in a format this build\n * understands — which callers must treat as \"nobody has identified here yet\".\n */\nfunction decodeLastIdentified(raw: string | null): string | null {\n if (raw === null) return null;\n const sep = raw.indexOf(':');\n // No separator at all is the pre-tag format; a different tag is a newer (or\n // older) build's. Both are unreadable here, and both fail to \"no previous\n // identity\" rather than to a false switch.\n if (sep < 0 || raw.slice(0, sep) !== LAST_IDENTIFIED_FORMAT) return null;\n const digest = raw.slice(sep + 1);\n return digest === '' ? null : digest;\n}\n\n/** One 32-bit FNV-1a pass, returned as an 8-hex-digit string. */\nfunction fnv1a32(s: string): string {\n let h = 0x811c9dc5; // FNV-1a 32-bit offset basis\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193); // FNV-1a 32-bit prime\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Two decorrelated 32-bit FNV-1a passes concatenated into a 16-hex-digit\n * (64-bit) digest.\n *\n * `last_identified` only ever needs an EQUALITY check (\"is this the same\n * person as last time\"), comparing exactly one previous digest against one\n * current digest — never a set lookup — so the birthday bound doesn't apply\n * here: a collision is ~2^-64 for one consecutive-login pair, and it fails\n * OPEN to the pre-task behaviour for that one pair (a missed switch), never\n * worse.\n *\n * The second pass is decorrelated by INPUT — a `'\\x01'`-prefixed copy — not\n * by a different offset basis/prime: two FNV-1a passes over identical bytes\n * with the same constants are structurally correlated, so changing only the\n * basis buys far less independence than it looks like it does.\n *\n * NOT a security boundary, and widening this does not change that: this is\n * an UNKEYED hash over what can be a low-entropy space (an email address),\n * so it is a confirmation oracle, not a secret — anyone with local read\n * access and a guess can verify it instantly by hashing the guess and\n * comparing. It exists only so `sauron.last_identified` isn't a second\n * plaintext copy of the app's user id, not to keep that id confidential.\n * `crypto.subtle` would be equally an oracle here (still unkeyed) and is\n * async, so it wouldn't buy anything worth the API becoming asynchronous.\n */\nexport function hashIdentity(id: string): string {\n return fnv1a32(id) + fnv1a32('\\x01' + id);\n}\n\n/** The minimal Web Storage surface we need (a subset of `Storage`). */\ninterface WebStorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** Return a named Web Storage area if present and writable, else `null`. */\nfunction webStorage(name: 'localStorage' | 'sessionStorage'): WebStorageLike | null {\n try {\n const s = (globalThis as Record<string, unknown>)[name] as WebStorageLike | undefined;\n if (!s) return null;\n const probe = '__sauron_probe__';\n s.setItem(probe, '1');\n s.removeItem(probe);\n return s;\n } catch {\n // Storage disabled (private mode, blocked cookies, SSR, ...).\n return null;\n }\n}\n\n/**\n * Return the persisted id under `key`, generating and persisting a fresh v4\n * uuid when absent. `cached` short-circuits repeated lookups and doubles as the\n * in-memory fallback when no storage is available.\n */\nfunction persistentId(cached: string | null, storage: WebStorageLike | null, key: string): string {\n if (cached) return cached;\n if (storage) {\n try {\n const existing = storage.getItem(key);\n if (existing) return existing;\n } catch {\n /* fall through and generate */\n }\n }\n const fresh = uuidv4();\n if (storage) {\n try {\n storage.setItem(key, fresh);\n } catch {\n /* best effort — degrade to the in-memory value returned below */\n }\n }\n return fresh;\n}\n\nlet deviceId: string | null = null;\nlet sessionId: string | null = null;\nlet anonymousId: string | null = null;\nlet lastIdentified: string | null = null;\n\n/** The stable device id (persisted in localStorage; per-process fallback). */\nexport function getDeviceId(): string {\n deviceId = persistentId(deviceId, webStorage('localStorage'), DEVICE_ID_KEY);\n return deviceId;\n}\n\n/** The current session id (persisted in sessionStorage; in-memory fallback). */\nexport function getSessionId(): string {\n sessionId = persistentId(sessionId, webStorage('sessionStorage'), SESSION_ID_KEY);\n return sessionId;\n}\n\n/**\n * Mint and persist a fresh session id.\n *\n * `reset()` calls this so a `sessions` row never spans two people. The server's\n * `bump_session` sets `distinct_id = COALESCE(EXCLUDED.distinct_id, …)`, i.e.\n * last-write-wins, so without rotation one session row records only whichever\n * of two consecutive users wrote last.\n */\nexport function rotateSessionId(): string {\n sessionId = null;\n const storage = webStorage('sessionStorage');\n if (storage) {\n try {\n storage.removeItem(SESSION_ID_KEY);\n } catch {\n /* best effort */\n }\n }\n return getSessionId();\n}\n\n/** The stable anonymous id (persisted in localStorage; per-process fallback). */\nexport function getAnonymousId(): string {\n if (anonymousId) return anonymousId;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n const existing = storage.getItem(ANON_ID_KEY);\n if (existing) {\n anonymousId = existing;\n return anonymousId;\n }\n } catch {\n /* fall through and generate */\n }\n }\n const fresh = `anon_${uuidv4()}`;\n if (storage) {\n try {\n storage.setItem(ANON_ID_KEY, fresh);\n } catch {\n /* best effort — degrade to the in-memory value */\n }\n }\n anonymousId = fresh;\n return anonymousId;\n}\n\n/**\n * Mint and persist a fresh anonymous id.\n *\n * MUST be reachable from application code. A persisted anon id plus\n * `process_identify`'s `identities(app_id, alias_id, distinct_id)` insert means\n * one `identify()` permanently binds this browser profile to a named user\n * server-side — so on a kiosk or a shared machine, person B's anonymous\n * activity would be aliased to person A's account, forever, with no escape\n * hatch.\n */\nexport function resetAnonymousId(): string {\n anonymousId = null;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.removeItem(ANON_ID_KEY);\n } catch {\n /* best effort */\n }\n }\n return getAnonymousId();\n}\n\n/**\n * The digest of the last user who identified on this device, or null.\n *\n * Falls back to the in-memory value not only when storage is absent/throws,\n * but also when storage IS present and simply has nothing under the key —\n * that also covers the case where `setLastIdentified`'s own write silently\n * failed (e.g. quota), so the value it set in memory is still the only place\n * this identify() is recorded at all.\n *\n * Returns the bare DIGEST: the `<tag>:` prefix is a storage concern and never\n * reaches the comparison in `SauronClient.prepareIdentify`. A value whose tag\n * this build does not recognise comes back `null` — see\n * `LAST_IDENTIFIED_FORMAT`.\n */\nexport function getLastIdentified(): string | null {\n const storage = webStorage('localStorage');\n if (!storage) return decodeLastIdentified(lastIdentified);\n try {\n const stored = storage.getItem(LAST_IDENTIFIED_KEY);\n return decodeLastIdentified(stored ?? lastIdentified);\n } catch {\n return decodeLastIdentified(lastIdentified);\n }\n}\n\n/**\n * Record the digest of the user who just identified.\n *\n * The in-memory copy holds the ENCODED value, not the bare digest, so the\n * storage-absent path and the storage-present path decode through exactly the\n * same function — a memory fallback that skipped the tag would be a second\n * format, and the two would drift.\n */\nexport function setLastIdentified(id: string): void {\n const encoded = encodeLastIdentified(id);\n lastIdentified = encoded;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.setItem(LAST_IDENTIFIED_KEY, encoded);\n } catch {\n /* best effort — the in-memory value above still applies this session */\n }\n }\n}\n\n/** Forget the last identified digest (called by `reset()`). */\nexport function clearLastIdentified(): void {\n lastIdentified = null;\n const storage = webStorage('localStorage');\n if (storage) {\n try {\n storage.removeItem(LAST_IDENTIFIED_KEY);\n } catch {\n /* best effort */\n }\n }\n}\n\n/** Drop the in-memory memoization (used by tests and teardown). */\nexport function resetIdentity(): void {\n deviceId = null;\n sessionId = null;\n anonymousId = null;\n lastIdentified = null;\n}\n","import { getDeviceId } from './identity.js';\nimport type { AppContext, Context, DeviceContext, OsContext, RuntimeContext, UserContext } from './types.js';\n\n/**\n * Best-effort environment detection from `navigator`. All of this is fuzzy by\n * nature (UA freezing, spoofing, non-browser hosts) so every field degrades to\n * `null` rather than guessing wrong in a way that breaks the wire contract.\n */\n\ninterface NavigatorLike {\n userAgent?: string;\n platform?: string;\n userAgentData?: { platform?: string };\n}\n\nfunction getNavigator(): NavigatorLike | undefined {\n const g = globalThis as { navigator?: NavigatorLike };\n return g.navigator;\n}\n\nfunction detectOs(ua: string): OsContext {\n // Windows\n let m = ua.match(/Windows NT ([\\d.]+)/);\n if (m) return { name: 'Windows', version: m[1] };\n // iOS (before macOS, since iPad UAs can contain \"Mac OS X\")\n m = ua.match(/iPhone OS (\\d+[_\\d]*)/) || ua.match(/CPU OS (\\d+[_\\d]*) like Mac/);\n if (m) return { name: 'iOS', version: m[1].replace(/_/g, '.') };\n // macOS\n m = ua.match(/Mac OS X (\\d+[_\\d]*)/);\n if (m) return { name: 'macOS', version: m[1].replace(/_/g, '.') };\n // Android\n m = ua.match(/Android ([\\d.]+)/);\n if (m) return { name: 'Android', version: m[1] };\n if (/Linux/.test(ua)) return { name: 'Linux', version: null };\n if (/CrOS/.test(ua)) return { name: 'Chrome OS', version: null };\n return { name: null, version: null };\n}\n\nfunction detectRuntime(ua: string): RuntimeContext {\n // Order matters: Edge/Opera masquerade as Chrome; Chrome masquerades as Safari.\n let m = ua.match(/Edg(?:e|A|iOS)?\\/([\\d.]+)/);\n if (m) return { name: 'Edge', version: major(m[1]) };\n m = ua.match(/OPR\\/([\\d.]+)/) || ua.match(/Opera\\/([\\d.]+)/);\n if (m) return { name: 'Opera', version: major(m[1]) };\n m = ua.match(/Firefox\\/([\\d.]+)/);\n if (m) return { name: 'Firefox', version: major(m[1]) };\n m = ua.match(/Chrome\\/([\\d.]+)/);\n if (m) return { name: 'Chrome', version: major(m[1]) };\n m = ua.match(/Version\\/([\\d.]+).*Safari/);\n if (m) return { name: 'Safari', version: major(m[1]) };\n if (/Safari/.test(ua)) return { name: 'Safari', version: null };\n return { name: null, version: null };\n}\n\nfunction detectDevice(nav: NavigatorLike | undefined, ua: string): DeviceContext {\n const platform = nav?.userAgentData?.platform ?? nav?.platform ?? '';\n let family: string | null = null;\n if (/Mac|iPhone|iPad|iPod/.test(platform) || /iPhone|iPad|Macintosh/.test(ua)) {\n family = 'Apple';\n } else if (/Win/.test(platform) || /Windows/.test(ua)) {\n family = 'Microsoft';\n } else if (/Android/.test(ua)) {\n family = 'Google';\n } else if (/Linux/.test(platform) || /Linux/.test(ua)) {\n family = 'Linux';\n }\n return { device_id: getDeviceId(), family, model: null, arch: null };\n}\n\n/** Take the leading major version component of a dotted version string. */\nfunction major(version: string): string {\n const dot = version.indexOf('.');\n return dot === -1 ? version : version.slice(0, dot);\n}\n\n/** Derive `app.version` from a `name@version` release string. */\nfunction appFromRelease(release: string | null): AppContext {\n if (!release) return { version: null, build: null };\n const at = release.lastIndexOf('@');\n const version = at === -1 ? release : release.slice(at + 1);\n return { version: version || null, build: null };\n}\n\n/**\n * Build the environment portion of the context (everything except the user).\n * The user is merged in by the client from its `Scope`.\n */\nexport function detectContext(release: string | null): Omit<Context, 'user'> {\n const nav = getNavigator();\n const ua = nav?.userAgent ?? '';\n return {\n device: detectDevice(nav, ua),\n os: detectOs(ua),\n app: appFromRelease(release),\n runtime: detectRuntime(ua),\n };\n}\n\n/** Combine the detected environment context with the current user. */\nexport function buildContext(release: string | null, user: UserContext): Context {\n return { ...detectContext(release), user };\n}\n","/**\n * DSN parsing.\n *\n * A DSN looks like `https://<public_key>@<host>/<project_id>`. The public key\n * is a non-secret, write-only credential — it is safe to ship in client code.\n */\n\nexport interface Dsn {\n /** The raw DSN string (embedded verbatim into the envelope header). */\n raw: string;\n publicKey: string;\n /** `host:port` — used for the infinite-loop denylist. */\n host: string;\n /** Hostname without port. */\n hostname: string;\n /** `https` or `http` (no trailing colon). */\n protocol: string;\n projectId: string;\n /** `POST` target for the primary transport. */\n envelopeUrl: string;\n /** `POST` target for the `sendBeacon` fallback (key in query string). */\n beaconUrl: string;\n}\n\nexport class DsnError extends Error {\n constructor(message: string) {\n super(`[sauron] invalid DSN: ${message}`);\n this.name = 'DsnError';\n }\n}\n\n/** Parse and validate a DSN, deriving the transport URLs. */\nexport function parseDsn(dsn: string): Dsn {\n if (typeof dsn !== 'string' || dsn.length === 0) {\n throw new DsnError('DSN must be a non-empty string');\n }\n\n let url: URL;\n try {\n url = new URL(dsn);\n } catch {\n throw new DsnError(`could not parse \"${dsn}\"`);\n }\n\n const protocol = url.protocol.replace(/:$/, '');\n if (protocol !== 'http' && protocol !== 'https') {\n throw new DsnError(`unsupported protocol \"${protocol}\"`);\n }\n\n const publicKey = url.username;\n if (!publicKey) {\n throw new DsnError('missing public key (the \"user\" part of the URL)');\n }\n if (url.password) {\n throw new DsnError('DSN must not contain a secret (password component)');\n }\n\n const host = url.host; // includes port when present\n const hostname = url.hostname;\n if (!host) {\n throw new DsnError('missing host');\n }\n\n const projectId = url.pathname.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (!projectId) {\n throw new DsnError('missing project id (the path segment)');\n }\n\n const base = `${protocol}://${host}/api/${projectId}/envelope`;\n const beaconUrl = `${base}?k=${encodeURIComponent(publicKey)}`;\n\n return {\n raw: dsn,\n publicKey,\n host,\n hostname,\n protocol,\n projectId,\n envelopeUrl: base,\n beaconUrl,\n };\n}\n","import type { Context, Envelope, EnvelopeHeader, EnvelopeItem } from './types.js';\n\n/**\n * Assemble a canonical envelope. This is intentionally trivial — the shape is\n * the contract, so keep it a pure, side-effect-free constructor that mirrors\n * the golden JSON exactly (header, context, items, in that order).\n */\nexport function buildEnvelope(\n header: EnvelopeHeader,\n context: Context,\n items: EnvelopeItem[],\n): Envelope {\n return {\n header,\n context,\n items,\n };\n}\n","/**\n * Instrumentation primitives shared by every integration:\n *\n * - a reentrancy guard so SDK-internal work never triggers its own breadcrumbs\n * (e.g. the transport's own `fetch` must not create a \"fetch\" breadcrumb that\n * schedules another send — an infinite loop),\n * - a DSN-host denylist (belt-and-suspenders alongside the guard),\n * - an idempotent \"already wrapped\" tag so double-`init` doesn't stack wrappers,\n * - a patch registry so `close()` can restore every original.\n */\n\nconst WRAPPED = '__sauron_wrapped__';\n\nlet internalDepth = 0;\n\n/** Enter SDK-internal execution (breadcrumb capture is suppressed while > 0). */\nexport function beginInternal(): void {\n internalDepth++;\n}\n\n/** Leave SDK-internal execution. */\nexport function endInternal(): void {\n internalDepth = Math.max(0, internalDepth - 1);\n}\n\n/** Run `fn` with the reentrancy guard held (synchronous scope only). */\nexport function withInternal<T>(fn: () => T): T {\n beginInternal();\n try {\n return fn();\n } finally {\n endInternal();\n }\n}\n\n/** True while SDK-internal code is running. */\nexport function isInternal(): boolean {\n return internalDepth > 0;\n}\n\nlet dsnHost: string | null = null;\n\n/** Register the DSN host (`host:port`) used for the request denylist. */\nexport function setDsnHost(host: string | null): void {\n dsnHost = host;\n}\n\n/** True when `rawUrl` targets the DSN host — such requests must be ignored. */\nexport function isDsnRequest(rawUrl: string): boolean {\n if (!dsnHost || !rawUrl) return false;\n try {\n const base = (globalThis as { location?: { href?: string } }).location?.href;\n const u = new URL(rawUrl, base);\n return u.host === dsnHost;\n } catch {\n return false;\n }\n}\n\n/** Tag a wrapper function so we never wrap it twice. */\nexport function markWrapped<T>(fn: T): T {\n try {\n (fn as Record<string, unknown>)[WRAPPED] = true;\n } catch {\n /* frozen function — best effort */\n }\n return fn;\n}\n\n/** True when `fn` was produced by {@link markWrapped}. */\nexport function isWrapped(fn: unknown): boolean {\n if (fn === null || (typeof fn !== 'function' && typeof fn !== 'object')) return false;\n return (fn as Record<string, unknown>)[WRAPPED] === true;\n}\n\ntype Unpatch = () => void;\n\nconst patches: Array<{ name: string; unpatch: Unpatch }> = [];\n\n/** Register an undo function to be run by {@link unpatchAll}. */\nexport function registerPatch(name: string, unpatch: Unpatch): void {\n patches.push({ name, unpatch });\n}\n\n/** Restore every patched global to its original, in reverse order. */\nexport function unpatchAll(): void {\n while (patches.length) {\n const p = patches.pop();\n try {\n p?.unpatch();\n } catch {\n /* ignore restore failures */\n }\n }\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport type { Level } from '../types.js';\nimport { isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\ntype ConsoleMethod = 'log' | 'info' | 'warn' | 'error' | 'debug';\nconst METHODS: ConsoleMethod[] = ['log', 'info', 'warn', 'error', 'debug'];\n\nfunction toLevel(method: ConsoleMethod): Level {\n switch (method) {\n case 'warn':\n return 'warning';\n case 'error':\n return 'error';\n case 'debug':\n return 'debug';\n default:\n return 'info';\n }\n}\n\nfunction argToString(arg: unknown): string {\n if (typeof arg === 'string') return arg;\n if (arg instanceof Error) return `${arg.name}: ${arg.message}`;\n try {\n return JSON.stringify(arg);\n } catch {\n return String(arg);\n }\n}\n\n/** Record a breadcrumb for each `console.*` call while leaving output intact. */\nexport function installConsole(): void {\n const consoleObj = (globalThis as { console?: Console }).console;\n if (!consoleObj) return;\n const c = consoleObj as unknown as Record<string, unknown>;\n\n for (const method of METHODS) {\n const original = c[method];\n if (typeof original !== 'function' || isWrapped(original)) continue;\n const originalFn = original as (...args: unknown[]) => unknown;\n\n const wrapped = markWrapped(function sauronConsole(this: unknown, ...args: unknown[]): unknown {\n if (!isInternal()) {\n withInternal(() => {\n try {\n addBreadcrumb({\n type: 'default',\n category: 'console',\n level: toLevel(method),\n message: args.map(argToString).join(' ').slice(0, 512),\n data: { arguments: args.length },\n });\n } catch {\n /* never break the app's console */\n }\n });\n }\n return originalFn.apply(this, args);\n });\n\n c[method] = wrapped;\n registerPatch(`console.${method}`, () => {\n c[method] = originalFn;\n });\n }\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { isInternal, registerPatch, withInternal } from './instrument.js';\n\n/**\n * Build a stable CSS-ish selector `tag#id.class` for a clicked element.\n * NEVER serializes `innerText`/attribute values — that would leak PII.\n */\nexport function domSelector(el: unknown): string | null {\n try {\n const node = el as { tagName?: string; id?: string; className?: unknown } | null;\n if (!node || typeof node.tagName !== 'string') return null;\n\n let selector = node.tagName.toLowerCase();\n if (node.id && typeof node.id === 'string') {\n selector += `#${node.id}`;\n }\n if (typeof node.className === 'string' && node.className.trim()) {\n const classes = node.className.trim().split(/\\s+/).slice(0, 3);\n if (classes.length) selector += `.${classes.join('.')}`;\n }\n return selector;\n } catch {\n return null;\n }\n}\n\n/** Record a `ui.click` breadcrumb (selector only, never text) for each click. */\nexport function installDom(): void {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc || typeof doc.addEventListener !== 'function') return;\n\n const handler = (event: Event): void => {\n if (isInternal()) return;\n const selector = domSelector(event.target);\n if (!selector) return;\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'ui.click',\n level: 'info',\n message: selector,\n data: null,\n });\n });\n };\n\n const options = { capture: true, passive: true } as AddEventListenerOptions;\n doc.addEventListener('click', handler, options);\n registerPatch('dom.click', () => {\n try {\n doc.removeEventListener('click', handler, options);\n } catch {\n /* ignore */\n }\n });\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { nowIso } from '../utils.js';\nimport { isDsnRequest, isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\nfunction resolveUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const withUrl = input as { url?: string; href?: string };\n if (typeof withUrl.url === 'string') return withUrl.url;\n if (typeof withUrl.href === 'string') return withUrl.href;\n }\n return String(input);\n}\n\nfunction resolveMethod(input: unknown, init: unknown): string {\n const fromInit = (init as { method?: string } | undefined)?.method;\n const fromReq = (input as { method?: string } | null)?.method;\n return String(fromInit ?? fromReq ?? 'GET').toUpperCase();\n}\n\nfunction addFetchBreadcrumb(\n method: string,\n url: string,\n status: number | null,\n startedAt: string,\n): void {\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'fetch',\n level: status !== null && status >= 400 ? 'warning' : 'info',\n message: `${method} ${url}`,\n timestamp: startedAt,\n data: { method, url, status_code: status },\n });\n });\n}\n\n/**\n * Wrap `fetch` to leave a breadcrumb per request. Requests to the DSN host (our\n * own ingest traffic) and requests made while SDK code runs are skipped — this\n * is what prevents an infinite send→breadcrumb→send loop.\n */\nexport function installFetch(): void {\n const g = globalThis as { fetch?: typeof fetch };\n const original = g.fetch;\n if (typeof original !== 'function' || isWrapped(original)) return;\n\n const wrapped = markWrapped(function sauronFetch(\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n const url = resolveUrl(input);\n const shouldRecord = !isInternal() && !isDsnRequest(url);\n const method = resolveMethod(input, init);\n const startedAt = nowIso();\n\n const promise = original.call(this, input as RequestInfo, init);\n\n if (shouldRecord) {\n promise.then(\n (res) => addFetchBreadcrumb(method, url, res?.status ?? null, startedAt),\n () => addFetchBreadcrumb(method, url, null, startedAt),\n );\n }\n return promise;\n });\n\n g.fetch = wrapped;\n registerPatch('fetch', () => {\n g.fetch = original;\n });\n}\n","/**\n * Current-screen state. The SDK stamps this on every event/exception and\n * auto-emits a `$screen` view event when it changes (see api/product.ts).\n */\nlet currentScreen: string | null = null;\n\n/** The current screen name, or null if none set. */\nexport function getScreen(): string | null {\n return currentScreen;\n}\n\n/** Set the current screen. Returns true iff the value actually changed. */\nexport function setScreenState(name: string | null): boolean {\n if (name === currentScreen) return false;\n currentScreen = name;\n return true;\n}\n\n/** Drop the in-memory value (tests + teardown). */\nexport function resetScreen(): void {\n currentScreen = null;\n}\n","import type { Frame } from '../types.js';\n\n/**\n * Cross-browser `Error.stack` parser.\n *\n * Produces neutral frames with the CRASHING FRAME LAST (raw stacks list the\n * crash site first, so the parsed list is reversed). Depth is capped at\n * {@link MAX_FRAMES}, keeping the frames nearest the crash. No symbolication is\n * performed — line/column/filename are passed through verbatim.\n */\n\nexport const MAX_FRAMES = 50;\n\n/** V8 / Chrome / Node / Edge: ` at fn (file:line:col)` or ` at file:line:col`. */\nconst V8_RE =\n /^\\s*at (?:(.+?) )?\\(?((?:[a-z][\\w.+-]*:\\/\\/)?[^\\s()]+?):(\\d+):(\\d+)\\)?\\s*$/i;\n\n/**\n * Firefox / Safari: `fn@file:line:col`, `@file:line:col`, `fn/<@file:line:col`.\n * The function name may contain spaces (Safari's `global code`, `module code`).\n */\nconst GECKO_RE =\n /^\\s*(?:([^@]*?)@)?((?:[a-z][\\w.+-]*:\\/\\/)?[^@\\s]+?):(\\d+):(\\d+)\\s*$/i;\n\nfunction cleanFunction(fn: string | undefined): string | null {\n if (!fn) return null;\n let name = fn.trim();\n // V8 async / constructor prefixes and Safari's trailing markers.\n name = name.replace(/^async\\s+/, '').replace(/^new\\s+/, 'new ');\n name = name.replace(/\\s+\\[as .+\\]$/, '');\n if (name === '<anonymous>' || name === '') return null;\n return name;\n}\n\n/**\n * Heuristic for whether a frame belongs to first-party (\"in app\") code:\n * same-origin URLs and bare/relative paths are in-app; cross-origin URLs\n * (typically CDN or third-party scripts) and internal frames are not.\n */\nexport function isInAppFrame(filename: string | null): boolean {\n if (!filename) return false;\n if (filename === '<anonymous>' || filename.startsWith('node:') || filename.startsWith('internal/')) {\n return false;\n }\n const hasProtocol = /^[a-z][\\w.+-]*:\\/\\//i.test(filename);\n if (!hasProtocol) {\n // A bare or relative path (e.g. \"app.js\", \"/static/app.js\").\n return true;\n }\n const origin = getOrigin();\n if (origin && filename.startsWith(origin)) {\n return true;\n }\n // Cross-origin absolute URL — treat as third-party / vendor.\n return false;\n}\n\nfunction getOrigin(): string {\n const loc = (globalThis as { location?: { origin?: string } }).location;\n return loc?.origin ?? '';\n}\n\nfunction parseLine(line: string): Frame | null {\n let m = V8_RE.exec(line);\n if (!m) m = GECKO_RE.exec(line);\n if (!m) return null;\n\n const filename = m[2] || null;\n const lineno = m[3] ? parseInt(m[3], 10) : null;\n const colno = m[4] ? parseInt(m[4], 10) : null;\n\n return {\n function: cleanFunction(m[1]),\n filename,\n lineno: Number.isNaN(lineno) ? null : lineno,\n colno: Number.isNaN(colno) ? null : colno,\n in_app: isInAppFrame(filename),\n };\n}\n\n/**\n * Parse a raw `Error.stack` string into normalized frames (crash frame last).\n * Non-frame lines (the `Error: message` header, `[native code]`, etc.) are\n * skipped.\n */\nexport function parseStackString(stack: string | undefined | null): Frame[] {\n if (!stack) return [];\n const frames: Frame[] = [];\n const lines = stack.split('\\n');\n for (const raw of lines) {\n const line = raw.replace(/\\r$/, '');\n if (!line.trim()) continue;\n const frame = parseLine(line);\n if (frame) {\n frames.push(frame);\n if (frames.length >= MAX_FRAMES) break; // keep the frames nearest the crash\n }\n }\n // Raw stacks are crash-first; the wire contract wants crash-last.\n frames.reverse();\n return frames;\n}\n\n/** Parse an `Error`-like object's `.stack`. */\nexport function parseError(err: unknown): Frame[] {\n if (err && typeof err === 'object' && 'stack' in err) {\n const stack = (err as { stack?: unknown }).stack;\n if (typeof stack === 'string') return parseStackString(stack);\n }\n return [];\n}\n","import { getClient } from '../client.js';\nimport { getSessionId } from '../identity.js';\nimport { getScreen } from '../screen.js';\nimport { parseError } from '../stacktrace/parse.js';\nimport type { Breadcrumb, ErrorItem, ExceptionValue, Frame, Hint, Level, Mechanism } from '../types.js';\nimport { nowIso, safeStringify } from '../utils.js';\n\nconst DEFAULT_MECHANISM: Mechanism = { type: 'generic', handled: true };\n\n/** Copy any NON-EMPTY per-call tags/contexts/extra off the hint onto the item. */\nfunction attachCallMeta(item: ErrorItem, hint?: Hint): void {\n if (hint?.tags && Object.keys(hint.tags).length > 0) item.tags = { ...hint.tags };\n if (hint?.contexts && Object.keys(hint.contexts).length > 0) item.contexts = { ...hint.contexts };\n if (hint?.extra && Object.keys(hint.extra).length > 0) item.extra = { ...hint.extra };\n}\n\ninterface ExtractedError {\n type: string;\n value: string | null;\n stacktrace: Frame[];\n}\n\nfunction isErrorLike(err: unknown): err is Error {\n return (\n err instanceof Error ||\n (typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n 'message' in err &&\n typeof (err as { message?: unknown }).message === 'string')\n );\n}\n\n/** Reduce any thrown value into `{type, value, stacktrace}`. */\nfunction extractError(err: unknown): ExtractedError {\n if (isErrorLike(err)) {\n const e = err as Error;\n return {\n type: e.name || 'Error',\n value: e.message ?? '',\n stacktrace: parseError(e),\n };\n }\n if (typeof err === 'string') {\n return { type: 'Error', value: err, stacktrace: [] };\n }\n if (typeof err === 'object' && err !== null) {\n const ctor = (err as { constructor?: { name?: string } }).constructor;\n return {\n type: ctor?.name ?? 'Object',\n value: safeStringify(err),\n stacktrace: [],\n };\n }\n return { type: typeof err, value: String(err), stacktrace: [] };\n}\n\n/** Build an error item from a thrown value plus the current breadcrumb trail. */\nexport function buildErrorItem(err: unknown, breadcrumbs: Breadcrumb[], hint?: Hint): ErrorItem {\n const extracted = extractError(err);\n const mechanism = (hint?.mechanism as Mechanism | undefined) ?? DEFAULT_MECHANISM;\n const level = (hint?.level as Level | undefined) ?? 'error';\n const fingerprint = (hint?.fingerprint as string[] | null | undefined) ?? null;\n\n const exception: ExceptionValue = {\n type: extracted.type,\n value: extracted.value,\n mechanism,\n stacktrace: extracted.stacktrace,\n };\n\n const item: ErrorItem = {\n type: 'error',\n timestamp: nowIso(),\n level,\n exception,\n breadcrumbs,\n fingerprint,\n session_id: getSessionId(),\n screen: (hint?.screen as string | undefined) ?? getScreen(),\n };\n attachCallMeta(item, hint);\n return item;\n}\n\n/** Capture an exception (or any thrown value) as an error item. */\nexport function captureException(err: unknown, hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n const breadcrumbs = client.getScope().getBreadcrumbs();\n const fullHint: Hint = { ...hint, originalException: err };\n const item = buildErrorItem(err, breadcrumbs, fullHint);\n client.captureItem(item, fullHint);\n}\n\n/**\n * Capture a plain message as an error item at the given `level` (default info).\n *\n * The item carries NO `exception` block — a message is not an exception, and the\n * backend's `ExceptionInfo.ty` is a non-`Option` `String` with no serde default,\n * so the `{ type: null }` placeholder this used to send failed to deserialize\n * and 400'd the WHOLE envelope (`invalid_envelope`), taking every unrelated\n * error and event in the batch with it — silently, because every SDK treats a\n * 400 as a non-retryable drop.\n *\n * Omitting `exception` and setting `message` is python's shape. It also routes\n * server-side onto the `message\\n<normalized message>` fingerprint branch, so\n * messages group by their text instead of piling into one bucket keyed by a\n * synthetic exception type.\n */\nexport function captureMessage(message: string, level: Level = 'info', hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n const breadcrumbs = client.getScope().getBreadcrumbs();\n const item: ErrorItem = {\n type: 'error',\n timestamp: nowIso(),\n level,\n message,\n breadcrumbs,\n fingerprint: (hint?.fingerprint as string[] | null | undefined) ?? null,\n session_id: getSessionId(),\n screen: getScreen(),\n };\n attachCallMeta(item, hint);\n client.captureItem(item, hint);\n}\n","import { captureException } from '../api/capture.js';\nimport { getClient } from '../client.js';\nimport { isWrapped, markWrapped, registerPatch } from './instrument.js';\n\n/**\n * Install `window.onerror` and `window.onunhandledrejection`, chaining any\n * previously-registered handler so we never clobber the host app's own logging.\n */\nexport function installGlobalHandlers(): void {\n const win = globalThis as typeof globalThis & {\n onerror?: OnErrorEventHandler;\n onunhandledrejection?: ((event: PromiseRejectionEvent) => unknown) | null;\n };\n\n installOnError(win);\n installOnUnhandledRejection(win);\n}\n\nfunction installOnError(win: typeof globalThis & { onerror?: OnErrorEventHandler }): void {\n const previous = win.onerror;\n if (isWrapped(previous)) return;\n\n const handler = markWrapped(function sauronOnError(\n this: unknown,\n message: Event | string,\n source?: string,\n lineno?: number,\n colno?: number,\n error?: unknown,\n ): boolean {\n if (getClient()) {\n const err = error ?? syntheticError(message, source, lineno, colno);\n captureException(err, { mechanism: { type: 'onerror', handled: false }, level: 'error' });\n }\n if (typeof previous === 'function') {\n return Boolean(\n previous.call(this, message, source, lineno, colno, error as Error | undefined),\n );\n }\n return false;\n });\n\n win.onerror = handler as OnErrorEventHandler;\n registerPatch('onerror', () => {\n win.onerror = (previous ?? null) as OnErrorEventHandler;\n });\n}\n\nfunction installOnUnhandledRejection(\n win: typeof globalThis & {\n onunhandledrejection?: ((event: PromiseRejectionEvent) => unknown) | null;\n },\n): void {\n const previous = win.onunhandledrejection;\n if (isWrapped(previous)) return;\n\n const handler = markWrapped(function sauronOnRejection(\n this: unknown,\n event: PromiseRejectionEvent,\n ): unknown {\n if (getClient()) {\n const reason =\n event && typeof event === 'object' && 'reason' in event ? event.reason : event;\n captureException(reason, {\n mechanism: { type: 'onunhandledrejection', handled: false },\n level: 'error',\n });\n }\n if (typeof previous === 'function') {\n return previous.call(this, event);\n }\n return undefined;\n });\n\n win.onunhandledrejection = handler as (event: PromiseRejectionEvent) => unknown;\n registerPatch('onunhandledrejection', () => {\n win.onunhandledrejection = previous ?? null;\n });\n}\n\n/** Build an Error carrying a best-effort stack from `onerror` positional args. */\nfunction syntheticError(\n message: Event | string,\n source?: string,\n lineno?: number,\n colno?: number,\n): Error {\n const msg = typeof message === 'string' ? message : 'Unknown error';\n const err = new Error(msg);\n if (source) {\n err.stack = `Error: ${msg}\\n at ${source}:${lineno ?? 0}:${colno ?? 0}`;\n }\n return err;\n}\n","import { addNavigationBreadcrumb, type NavigationOperation } from '../api/breadcrumbs.js';\nimport { isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\nlet navHandler: ((path: string) => void) | null = null;\n\n/** Register (or clear) a callback fired with the new path on each SPA navigation. */\nexport function onNavigation(cb: ((path: string) => void) | null): void {\n navHandler = cb;\n}\n\n/** Reduce a URL to its path portion (relative to the current origin). */\nfunction toPath(url: string | null, base: string | undefined): string | null {\n if (url === null || url === undefined) return url;\n try {\n const parsed = new URL(url, base);\n return parsed.pathname + parsed.search + parsed.hash;\n } catch {\n return url;\n }\n}\n\n/**\n * Patch `history.pushState`/`replaceState` and listen for `popstate` to emit\n * `{from, to}` navigation breadcrumbs for SPA route changes.\n */\nexport function installHistory(): void {\n const g = globalThis as typeof globalThis & {\n history?: History;\n location?: Location;\n addEventListener?: (t: string, h: () => void) => void;\n removeEventListener?: (t: string, h: () => void) => void;\n };\n const hist = g.history;\n const loc = g.location;\n if (!hist) return;\n\n let lastPath = toPath(loc?.href ?? null, loc?.href);\n\n const emit = (toHref: string | null, operation: NavigationOperation): void => {\n const to = toPath(toHref, loc?.href);\n const from = lastPath;\n lastPath = to;\n if (from === to) return;\n withInternal(() => addNavigationBreadcrumb(from, to, operation));\n if (to && navHandler) {\n try {\n navHandler(to);\n } catch {\n /* never let screen tracking break navigation */\n }\n }\n };\n\n const wrap = (name: 'pushState' | 'replaceState'): void => {\n const original = hist[name];\n if (typeof original !== 'function' || isWrapped(original)) return;\n const operation: NavigationOperation = name === 'pushState' ? 'push' : 'replace';\n\n hist[name] = markWrapped(function sauronHistory(this: History, ...args: unknown[]) {\n const result = (original as (...a: unknown[]) => unknown).apply(this, args);\n if (!isInternal()) {\n const urlArg = args[2];\n emit(urlArg != null ? String(urlArg) : (loc?.href ?? null), operation);\n }\n return result;\n }) as History[typeof name];\n\n registerPatch(`history.${name}`, () => {\n hist[name] = original;\n });\n };\n\n wrap('pushState');\n wrap('replaceState');\n\n if (typeof g.addEventListener === 'function') {\n // Both `history.back()` and `history.forward()` land here; the event carries\n // nothing to separate them, so a forward step is recorded as a pop too.\n const onPopState = (): void => {\n if (!isInternal()) emit(loc?.href ?? null, 'pop');\n };\n g.addEventListener('popstate', onPopState);\n registerPatch('popstate', () => {\n g.removeEventListener?.('popstate', onPopState);\n });\n }\n}\n","import type { Breadcrumb, UserContext, UserInput } from './types.js';\n\n/** An empty user context (all fields null, no traits). */\nexport function emptyUser(): UserContext {\n return { id: null, email: null, traits: {} };\n}\n\n/**\n * Shallow-merge a per-call override map over a base map. The override wins per\n * top-level key — tags/extra merge by key, contexts merge by block name (a\n * per-call block replaces the same-named base block). Returns a fresh object;\n * callers OMIT the field entirely when the result is empty (emit convention).\n */\nexport function mergeMeta(\n base: Record<string, unknown>,\n override?: Record<string, unknown>,\n): Record<string, unknown> {\n return override ? { ...base, ...override } : { ...base };\n}\n\n/**\n * Mutable per-client state: the current user, a ring buffer of breadcrumbs and\n * free-form tags. The breadcrumb buffer is capped at `maxBreadcrumbs`; the\n * oldest entries fall off the front (FIFO).\n */\nexport class Scope {\n private user: UserContext | null = null;\n private breadcrumbs: Breadcrumb[] = [];\n private maxBreadcrumbs: number;\n readonly tags: Record<string, string> = {};\n readonly contexts: Record<string, unknown> = {};\n readonly extra: Record<string, unknown> = {};\n\n constructor(maxBreadcrumbs = 50) {\n this.maxBreadcrumbs = Math.max(0, maxBreadcrumbs);\n }\n\n setMaxBreadcrumbs(max: number): void {\n this.maxBreadcrumbs = Math.max(0, max);\n this.trim();\n }\n\n /**\n * Replace the scope user.\n *\n * `id` is coerced with `String()` for the same reason `SauronClient.\n * prepareIdentify` coerces its own — a plain-JS caller can (and does) pass\n * `setUser({ id: user.id })` where `user.id` is a number, and TypeScript\n * cannot stop them. This path is the one that BYPASSES `identify()`'s\n * coercion entirely, and the consequence is not cosmetic: the scope user\n * lands in the envelope context, where the server's `distinct_id` is a\n * non-`Option` Rust `String`. A JSON number there fails deserialization of\n * the ENVELOPE, not of the one field — so the whole batch 400s, and a 400\n * is non-retryable, so every event in it is dropped for good.\n *\n * Rebuilding the whole object (rather than merging into the existing one)\n * is deliberate and is the behaviour the Flutter SDK was fixed to match:\n * `email` and `traits` come from the input alone, so setting a new user\n * never inherits the previous person's contact details.\n */\n setUser(user: UserInput): void {\n if (user === null) {\n this.user = null;\n return;\n }\n this.user = {\n id: user.id === null || user.id === undefined ? null : String(user.id),\n email: user.email ?? null,\n traits: user.traits ?? {},\n };\n }\n\n /** The user context for an envelope. Never null — defaults to an empty user. */\n getUser(): UserContext {\n return this.user ? { ...this.user, traits: { ...this.user.traits } } : emptyUser();\n }\n\n /** True when an identifiable user has been set. */\n hasUser(): boolean {\n return this.user !== null;\n }\n\n setTag(key: string, value: string): void {\n this.tags[key] = value;\n }\n\n /** Merge a batch of tags into the scope (last-write-wins per key). */\n setTags(tags: Record<string, string>): void {\n Object.assign(this.tags, tags);\n }\n\n /** Set (replace) a named context block on the scope. */\n setContext(name: string, block: Record<string, unknown>): void {\n this.contexts[name] = block;\n }\n\n /** Set a single freeform extra value on the scope. */\n setExtra(key: string, value: unknown): void {\n this.extra[key] = value;\n }\n\n addBreadcrumb(breadcrumb: Breadcrumb): void {\n if (this.maxBreadcrumbs <= 0) return;\n this.breadcrumbs.push(breadcrumb);\n this.trim();\n }\n\n /** A defensive copy of the current breadcrumb trail. */\n getBreadcrumbs(): Breadcrumb[] {\n return this.breadcrumbs.slice();\n }\n\n clearBreadcrumbs(): void {\n this.breadcrumbs = [];\n }\n\n private trim(): void {\n const overflow = this.breadcrumbs.length - this.maxBreadcrumbs;\n if (overflow > 0) {\n this.breadcrumbs.splice(0, overflow);\n }\n }\n}\n","/**\n * Current-workflow state. The SDK stamps `workflow_id`/`workflow_name` on\n * every event/error/transaction while a workflow is active, and emits the\n * reserved `$workflow_start` / `$workflow_end` / `$workflow_cancel` analytics\n * events around its lifecycle (see api/product.ts).\n */\nimport type { ActiveWorkflow } from './types.js';\n\n/** Cap on a workflow name, after trimming. */\nexport const WORKFLOW_NAME_MAX = 120;\n/** Cap on a cancel reason. */\nexport const WORKFLOW_REASON_MAX = 120;\n\nlet current: ActiveWorkflow | null = null;\n\n/** The active workflow, or null if none. */\nexport function getWorkflow(): ActiveWorkflow | null {\n return current;\n}\n\n/** Set (or clear, with `null`) the active workflow. */\nexport function setWorkflowState(workflow: ActiveWorkflow | null): void {\n current = workflow;\n}\n\n/** Drop the in-memory value (tests + teardown). */\nexport function resetWorkflow(): void {\n current = null;\n}\n\n/** Returns the trimmed name, or null when invalid (empty or over the cap). */\nexport function normalizeWorkflowName(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > WORKFLOW_NAME_MAX) return null;\n return trimmed;\n}\n\n/** Normalize a cancel reason: default to `'user'`, else trim and cap. */\nexport function normalizeReason(reason: unknown): string {\n if (typeof reason !== 'string' || reason.trim().length === 0) return 'user';\n return reason.trim().slice(0, WORKFLOW_REASON_MAX);\n}\n","import { getClient } from '../client.js';\nimport { getSessionId } from '../identity.js';\nimport { getScreen, setScreenState } from '../screen.js';\nimport { mergeMeta } from '../scope.js';\nimport type {\n ActiveWorkflow,\n EventItem,\n IdentifyItem,\n TrackOptions,\n TransactionItem,\n TransactionOp,\n WorkflowResult,\n} from '../types.js';\nimport { capTransactionExtra, makeLogger, nowIso, uuidv4 } from '../utils.js';\nimport {\n getWorkflow,\n normalizeReason,\n normalizeWorkflowName,\n resetWorkflow,\n setWorkflowState,\n} from '../workflow.js';\n\n/**\n * Record a product-analytics event (PostHog-style). The `distinct_id` is the\n * current user id when identified, otherwise a stable anonymous id.\n */\nexport function track(\n name: string,\n properties: Record<string, unknown> = {},\n options: TrackOptions = {},\n): void {\n const client = getClient();\n if (!client) return;\n const scope = client.getScope();\n const item: EventItem = {\n type: 'event',\n name,\n distinct_id: client.getDistinctId(),\n session_id: getSessionId(),\n screen: options.screen ?? getScreen(),\n timestamp: nowIso(),\n properties: properties ?? {},\n };\n const tags = mergeMeta(scope.tags, options.tags);\n if (Object.keys(tags).length > 0) item.tags = tags;\n const contexts = mergeMeta(scope.contexts, options.contexts);\n if (Object.keys(contexts).length > 0) item.contexts = contexts;\n const extra = mergeMeta(scope.extra, options.extra);\n if (Object.keys(extra).length > 0) item.extra = extra;\n client.captureItem(item);\n}\n\n/**\n * Set the current screen. On an actual change, emits a `$screen` view event\n * (carrying the new screen) so dwell can be computed server-side.\n */\nexport function setScreen(name: string): void {\n if (!setScreenState(name)) return;\n track('$screen', { screen: name });\n}\n\n/**\n * Associate the current session with a known user. Emits an identify item that\n * links the prior anonymous id (if any) to the new distinct id.\n */\nexport function identify(id: string, traits: Record<string, unknown> = {}): void {\n const client = getClient();\n if (!client) return;\n // Coerce ONCE, use everywhere below. `IdentifyItem.distinct_id` is a\n // non-`Option` Rust `String` on the wire (`envelope.rs`), so a plain-JS\n // caller passing a number (`Sauron.identify(user.id)`, entirely possible —\n // nothing at runtime enforces the TS `id: string` signature) would send a\n // JSON number there. That fails to deserialize and rejects the WHOLE\n // envelope (`400 invalid_envelope`), taking every other item batched\n // alongside it — the identical failure class `CHANGELOG.md` 1.4.0 documents\n // for `captureMessage`'s `exception.type: null`.\n const distinctId = String(id);\n // `null` unless the anon id was actually used as a distinct_id in this\n // browser session, or when it belonged to a different person than the last\n // one who identified on this device (`prepareIdentify` mints a fresh anon id\n // first in that case, since the old one is already burned server-side).\n // `process_identify` inserts a permanent `identities(app_id, alias_id,\n // distinct_id)` row for any non-empty anonymous_id, and that row is now a\n // LIVE signal (the 000038 backfill reads it), so a speculative or\n // cross-user alias is a durable server-side mis-merge.\n const anonymousId = client.prepareIdentify(distinctId);\n client.getScope().setUser({ id: distinctId, traits });\n const item: IdentifyItem = {\n type: 'identify',\n distinct_id: distinctId,\n anonymous_id: anonymousId,\n traits: traits ?? {},\n };\n client.captureItem(item);\n}\n\n/** Loose (camelCase) input accepted by {@link trackTransaction}. */\nexport interface TransactionInput {\n name: string;\n op?: string;\n durationMs: number;\n status?: string | null;\n httpMethod?: string | null;\n httpStatus?: number | null;\n url?: string | null;\n /**\n * Flat string tags for this transaction.\n *\n * **Per-call only — the scope is NOT merged in**, which is the one place\n * transactions differ from `track()` and `captureException()`. Those two\n * merge `setTag`/`setExtra` defaults; a transaction carries only what its own\n * call site attached. Transactions are the highest-volume signal (one per\n * navigation and per HTTP call), so inheriting a global blob would write it\n * onto every row.\n */\n tags?: Record<string, string>;\n /**\n * Freeform JSON for this transaction — the request body, the response body,\n * an order id, a retry count.\n *\n * Per-call only, for the reason on {@link TransactionInput.tags}. Serialized\n * and capped at {@link MAX_TRANSACTION_EXTRA_BYTES}; past that the whole map\n * is replaced with `{ _truncated: true, _bytes: N }` so one large body cannot\n * take a batched envelope over the ingest limit and drop every span in it.\n *\n * Nothing here is scrubbed. `beforeSend` is the redaction seam.\n */\n extra?: Record<string, unknown>;\n}\n\nconst TRANSACTION_OPS: readonly TransactionOp[] = [\n 'navigation',\n 'http',\n 'resource',\n 'screen_load',\n 'custom',\n];\n\n/** Coerce a free-form op string to a known {@link TransactionOp}, else `custom`. */\nfunction normalizeOp(op: string | undefined): TransactionOp {\n return op && (TRANSACTION_OPS as readonly string[]).includes(op)\n ? (op as TransactionOp)\n : 'custom';\n}\n\n/**\n * Build a wire-shaped transaction item from camelCase input. Pure — the caller\n * supplies the current identity so this stays testable without a client.\n */\nexport function buildTransactionItem(\n input: TransactionInput,\n distinctId: string | null,\n sessionId: string | null,\n): TransactionItem {\n const item: TransactionItem = {\n type: 'transaction',\n name: input.name,\n op: normalizeOp(input.op),\n duration_ms: input.durationMs,\n status: input.status ?? null,\n http_method: input.httpMethod ?? null,\n http_status: input.httpStatus ?? null,\n url: input.url ?? null,\n distinct_id: distinctId,\n session_id: sessionId,\n timestamp: nowIso(),\n };\n // Per-call only — no `mergeMeta(scope.tags, …)` here, unlike `track()` above.\n // Omitted when empty so an app that never sets them is byte-identical on the\n // wire to before these fields existed.\n if (input.tags && Object.keys(input.tags).length > 0) item.tags = { ...input.tags };\n if (input.extra && Object.keys(input.extra).length > 0) {\n item.extra = capTransactionExtra({ ...input.extra });\n }\n return item;\n}\n\n/** Enqueue a performance transaction item. */\nexport function trackTransaction(input: TransactionInput): void {\n const client = getClient();\n if (!client) return;\n const item = buildTransactionItem(input, client.getDistinctId(), getSessionId());\n client.captureItem(item);\n}\n\n/* ----------------------------------------------------------------- workflow */\n\n/**\n * Discards everything. Used as the logger until a real one can be built from\n * the client, so the `catch` blocks below can log unconditionally even when\n * the failure happened while acquiring the client itself.\n */\nconst NOOP_LOGGER = makeLogger(false);\n\n/**\n * Emit the closing lifecycle event (`$workflow_end`/`$workflow_cancel`) for\n * `active` while it is STILL the active workflow (so it is stamped with the\n * workflow it closes), then clear the state.\n *\n * NEVER THROWS, and clears the state in a `finally`. That pairing is the whole\n * contract: callers report `ok` on the strength of it, and `ok` must mean the\n * workflow really is closed locally. If the emit could throw past this\n * function, the state would stay set while the caller was told the workflow\n * ended — every later signal would then be stamped with a workflow the app\n * considers finished, and it would never leave `active` server-side. A lost\n * lifecycle event is recoverable (the server materializes the rollup row from\n * whatever stamped events it does receive); a permanently desynced local state\n * is not.\n */\nfunction emitWorkflowClose(\n active: ActiveWorkflow,\n eventName: '$workflow_end' | '$workflow_cancel',\n reason: string | undefined,\n logger: { warn: (...args: unknown[]) => void },\n): void {\n const properties: Record<string, unknown> = {\n workflow_id: active.workflowId,\n workflow_name: active.name,\n duration_ms: Math.max(0, Date.now() - Date.parse(active.startedAt)),\n };\n if (eventName === '$workflow_cancel') {\n properties.reason = normalizeReason(reason);\n }\n try {\n track(eventName, properties);\n } catch (err) {\n logger.warn(`${eventName}: failed to emit the lifecycle event`, err);\n } finally {\n resetWorkflow();\n }\n}\n\n/**\n * Start a named workflow. `force: true` supersedes an already-active workflow\n * (emitting `$workflow_cancel` with `reason: 'superseded'` for it first);\n * otherwise an active workflow makes this a no-op returning `already_active`.\n *\n * The workflow id is a fresh client-generated UUID — the server rolls counters\n * up on `(app_id, workflow_id)` app-wide, so a deterministic or reused id would\n * merge counts from unrelated environments/sessions into one row.\n */\nexport function startWorkflow(name: string, options?: { force?: boolean }): WorkflowResult {\n let logger = NOOP_LOGGER;\n try {\n const client = getClient();\n if (!client || !client.isEnabled()) return { status: 'disabled' };\n logger = makeLogger(client.options.debug);\n\n const normalized = normalizeWorkflowName(name);\n if (!normalized) {\n logger.warn('startWorkflow: invalid name', name);\n return { status: 'invalid_name' };\n }\n\n const active = getWorkflow();\n if (active && !options?.force) {\n logger.warn(\n `startWorkflow(\"${normalized}\"): \"${active.name}\" is already active; pass { force: true } to replace it`,\n );\n return { status: 'already_active' };\n }\n\n // Mint the replacement BEFORE superseding the old one, so nothing that\n // could throw sits between closing the old workflow and setting the new\n // one — otherwise the `catch` below could report `disabled` (\"nothing\n // changed\") having already closed the previous workflow.\n const workflow: ActiveWorkflow = {\n workflowId: uuidv4(),\n name: normalized,\n startedAt: nowIso(),\n };\n if (active) emitWorkflowClose(active, '$workflow_cancel', 'superseded', logger);\n\n // Set the state BEFORE emitting, so $workflow_start is itself stamped.\n setWorkflowState(workflow);\n try {\n track('$workflow_start', { workflow_id: workflow.workflowId, workflow_name: workflow.name });\n } catch (err) {\n // The workflow IS live and stamping IS active — reporting `disabled`\n // here would tell the caller nothing started and hand back no id, which\n // is the one thing that cannot be recovered. The server materializes the\n // rollup row from the first stamped event regardless, so a lost\n // `$workflow_start` costs only its own properties.\n logger.warn('startWorkflow: failed to emit $workflow_start', err);\n }\n return { status: 'ok', workflowId: workflow.workflowId };\n } catch (err) {\n // Only reachable before any state was touched, so `disabled` — documented\n // as \"nothing changed\" — is honest here.\n logger.warn('startWorkflow failed', err);\n return { status: 'disabled' };\n }\n}\n\n/** Shared precondition + close logic for `endWorkflow`/`cancelWorkflow`. */\nfunction closeWorkflow(\n eventName: '$workflow_end' | '$workflow_cancel',\n name?: string,\n reason?: string,\n): WorkflowResult {\n let logger = NOOP_LOGGER;\n try {\n const client = getClient();\n if (!client || !client.isEnabled()) return { status: 'disabled' };\n logger = makeLogger(client.options.debug);\n\n const active = getWorkflow();\n if (!active) return { status: 'not_active' };\n // A malformed explicit `name` normalizes to null, which never equals an\n // active name — so it reports `name_mismatch`, not `invalid_name`. That is\n // deliberate: the caller named a workflow that is not the active one.\n if (name !== undefined && normalizeWorkflowName(name) !== active.name) {\n logger.warn(`${eventName}: \"${name}\" does not match active workflow \"${active.name}\"`);\n return { status: 'name_mismatch' };\n }\n const workflowId = active.workflowId;\n // Cannot throw, and always clears the state — so `ok` below is truthful.\n emitWorkflowClose(active, eventName, reason, logger);\n return { status: 'ok', workflowId };\n } catch (err) {\n // As in startWorkflow: only reachable before any state was touched.\n logger.warn(`${eventName} failed`, err);\n return { status: 'disabled' };\n }\n}\n\n/**\n * End the active workflow (or the one named `name`, if given). Emits\n * `$workflow_end` with `duration_ms` and clears the state. A no-op returning\n * `not_active`/`name_mismatch` when the precondition fails.\n */\nexport function endWorkflow(name?: string): WorkflowResult {\n return closeWorkflow('$workflow_end', name);\n}\n\n/**\n * Cancel the active workflow (or the one named `name`, if given). Emits\n * `$workflow_cancel` with `duration_ms` and `reason` (default `'user'`, capped\n * at 120 chars) and clears the state.\n */\nexport function cancelWorkflow(name?: string, options?: { reason?: string }): WorkflowResult {\n return closeWorkflow('$workflow_cancel', name, options?.reason);\n}\n","/**\n * Performance auto-instrumentation. In a browser this captures:\n *\n * - one `navigation` transaction for the initial page load (navigation timing),\n * - one `http` transaction per instrumented `fetch` call,\n * - a `navigation` transaction on each SPA route change (History API).\n *\n * Everything here is strictly best-effort: instrumentation errors are swallowed\n * so an app `fetch` never breaks, and the original fetch rejection is re-thrown\n * unchanged to the caller. Opt in with `init({ performance: true })`.\n */\n\nimport { trackTransaction } from '../api/product.js';\nimport { isDsnRequest, isInternal, registerPatch } from './instrument.js';\n\n/** Dedicated markers so we layer on top of the breadcrumb integrations without\n * colliding with their generic \"wrapped\" tag. */\nconst PERF_FETCH = '__sauron_perf_fetch__';\nconst PERF_HISTORY = '__sauron_perf_history__';\n\ninterface GlobalLike {\n fetch?: typeof fetch;\n history?: History;\n location?: Location;\n document?: Document;\n performance?: Performance;\n requestAnimationFrame?: (cb: () => void) => number;\n addEventListener?: (type: string, handler: () => void) => void;\n removeEventListener?: (type: string, handler: () => void) => void;\n}\n\nfunction g(): GlobalLike {\n return globalThis as GlobalLike;\n}\n\n/** Tag a wrapper function with a marker so we never wrap it twice. */\nfunction mark(fn: object, key: string): void {\n (fn as unknown as Record<string, unknown>)[key] = true;\n}\n\n/** True when `fn` was tagged with {@link mark}. */\nfunction isMarked(fn: unknown, key: string): boolean {\n return typeof fn === 'function' && (fn as unknown as Record<string, unknown>)[key] === true;\n}\n\n/** High-resolution clock, degrading to `Date.now()` when `performance` is absent. */\nfunction clock(): () => number {\n const perf = g().performance;\n if (perf && typeof perf.now === 'function') return () => perf.now();\n return () => Date.now();\n}\n\nfunction resolveUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const withUrl = input as { url?: string; href?: string };\n if (typeof withUrl.url === 'string') return withUrl.url;\n if (typeof withUrl.href === 'string') return withUrl.href;\n }\n return String(input);\n}\n\nfunction resolveMethod(input: unknown, init: unknown): string {\n const fromInit = (init as { method?: string } | undefined)?.method;\n const fromReq = (input as { method?: string } | null)?.method;\n return String(fromInit ?? fromReq ?? 'GET').toUpperCase();\n}\n\n/** Reduce a URL to its path portion (relative to the current origin). */\nfunction pathOf(url: string | null | undefined): string {\n if (!url) return '/';\n try {\n const base = g().location?.href;\n return new URL(url, base).pathname;\n } catch {\n return url;\n }\n}\n\n/* ------------------------------------------------------- navigation timing */\n\n/** Prefer the modern `PerformanceNavigationTiming.duration`, else the legacy\n * `timing.loadEventEnd - navigationStart`. Returns `null` when unavailable. */\nfunction navigationDuration(perf: Performance): number | null {\n try {\n const entries = perf.getEntriesByType?.('navigation') as\n | PerformanceNavigationTiming[]\n | undefined;\n if (entries && entries.length > 0) {\n const d = entries[0].duration;\n if (typeof d === 'number' && d > 0) return d;\n }\n } catch {\n /* getEntriesByType unsupported — fall through */\n }\n const timing = (perf as { timing?: PerformanceTiming }).timing;\n if (timing && timing.loadEventEnd && timing.navigationStart) {\n const d = timing.loadEventEnd - timing.navigationStart;\n if (d > 0) return d;\n }\n return null;\n}\n\nfunction installNavigationTiming(): void {\n const perf = g().performance;\n if (!perf) return;\n\n const capture = (): void => {\n try {\n const durationMs = navigationDuration(perf);\n if (durationMs === null) return;\n trackTransaction({ name: pathOf(g().location?.pathname), op: 'navigation', durationMs });\n } catch {\n /* swallow */\n }\n };\n\n // Timing is only final once `load` has fired; capture now if it already has.\n const doc = g().document;\n if (doc && doc.readyState === 'complete') {\n capture();\n } else if (typeof g().addEventListener === 'function') {\n const onLoad = (): void => {\n capture();\n g().removeEventListener?.('load', onLoad);\n };\n g().addEventListener?.('load', onLoad);\n registerPatch('perf.load', () => g().removeEventListener?.('load', onLoad));\n } else {\n capture();\n }\n}\n\n/* -------------------------------------------------------------- fetch timing */\n\nfunction emitHttp(\n method: string,\n url: string,\n start: number,\n end: number,\n status: number | null,\n ok: boolean,\n): void {\n try {\n trackTransaction({\n name: `${method} ${pathOf(url)}`,\n op: 'http',\n durationMs: Math.max(0, end - start),\n status: ok ? 'ok' : 'error',\n httpMethod: method,\n httpStatus: status ?? undefined,\n url,\n });\n } catch {\n /* never throw into user code */\n }\n}\n\nfunction installFetchTiming(): void {\n const original = g().fetch;\n if (typeof original !== 'function') return;\n if (isMarked(original, PERF_FETCH)) return;\n\n const now = clock();\n\n const wrapped = function sauronPerfFetch(\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n let url = '';\n let method = 'GET';\n let record = false;\n try {\n url = resolveUrl(input);\n method = resolveMethod(input, init);\n record = !isInternal() && !isDsnRequest(url);\n } catch {\n record = false;\n }\n\n const start = record ? now() : 0;\n // Return the ORIGINAL promise so the caller sees the untouched result and\n // any rejection propagates unchanged.\n const promise = original.call(this, input as RequestInfo, init);\n\n if (record) {\n promise.then(\n (res) => emitHttp(method, url, start, now(), res?.status ?? null, res?.ok ?? false),\n () => emitHttp(method, url, start, now(), null, false),\n );\n }\n return promise;\n };\n\n mark(wrapped, PERF_FETCH);\n g().fetch = wrapped as typeof fetch;\n registerPatch('perf.fetch', () => {\n g().fetch = original;\n });\n}\n\n/* ------------------------------------------------------------ history timing */\n\nfunction installHistoryTiming(): void {\n const hist = g().history;\n if (!hist) return;\n const now = clock();\n\n const emit = (): void => {\n try {\n const path = pathOf(g().location?.pathname);\n const start = now();\n const finish = (): void => {\n try {\n trackTransaction({ name: path, op: 'navigation', durationMs: Math.max(0, now() - start) });\n } catch {\n /* swallow */\n }\n };\n // Approximate the client-side render span with a single animation frame.\n const raf = g().requestAnimationFrame;\n if (typeof raf === 'function') raf(finish);\n else finish();\n } catch {\n /* swallow */\n }\n };\n\n const wrap = (name: 'pushState' | 'replaceState'): void => {\n const original = hist[name];\n if (typeof original !== 'function') return;\n if (isMarked(original, PERF_HISTORY)) return;\n\n const patched = function sauronPerfHistory(this: History, ...args: unknown[]) {\n const result = (original as (...a: unknown[]) => unknown).apply(this, args);\n if (!isInternal()) emit();\n return result;\n };\n mark(patched, PERF_HISTORY);\n hist[name] = patched as History[typeof name];\n registerPatch(`perf.history.${name}`, () => {\n hist[name] = original;\n });\n };\n\n wrap('pushState');\n wrap('replaceState');\n\n if (typeof g().addEventListener === 'function') {\n const onPopState = (): void => {\n if (!isInternal()) emit();\n };\n g().addEventListener?.('popstate', onPopState);\n registerPatch('perf.popstate', () => g().removeEventListener?.('popstate', onPopState));\n }\n}\n\n/* --------------------------------------------------------------------- entry */\n\n/** Install performance auto-capture. No-op outside a browser-like environment. */\nexport function installPerformance(): void {\n if (typeof g().document === 'undefined') return;\n installNavigationTiming();\n installFetchTiming();\n installHistoryTiming();\n}\n","import { addBreadcrumb } from '../api/breadcrumbs.js';\nimport { nowIso } from '../utils.js';\nimport { isDsnRequest, isInternal, isWrapped, markWrapped, registerPatch, withInternal } from './instrument.js';\n\ninterface XhrMeta {\n method: string;\n url: string;\n startedAt: string;\n}\n\ntype PatchedXhr = XMLHttpRequest & { __sauron_xhr__?: XhrMeta };\n\nfunction addXhrBreadcrumb(meta: XhrMeta, status: number): void {\n withInternal(() => {\n addBreadcrumb({\n type: 'default',\n category: 'xhr',\n level: status >= 400 ? 'warning' : 'info',\n message: `${meta.method} ${meta.url}`,\n timestamp: meta.startedAt,\n data: { method: meta.method, url: meta.url, status_code: status || null },\n });\n });\n}\n\n/** Wrap `XMLHttpRequest.open`/`send` to leave a breadcrumb per request. */\nexport function installXhr(): void {\n const XHR = (globalThis as { XMLHttpRequest?: typeof XMLHttpRequest }).XMLHttpRequest;\n if (typeof XHR !== 'function' || !XHR.prototype) return;\n\n const proto = XHR.prototype;\n const originalOpen = proto.open;\n const originalSend = proto.send;\n if (isWrapped(originalOpen) || isWrapped(originalSend)) return;\n\n proto.open = markWrapped(function sauronXhrOpen(\n this: PatchedXhr,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this.__sauron_xhr__ = {\n method: String(method ?? 'GET').toUpperCase(),\n url: String(url),\n startedAt: nowIso(),\n };\n return (originalOpen as (...a: unknown[]) => unknown).apply(this, [method, url, ...rest]);\n }) as typeof proto.open;\n\n proto.send = markWrapped(function sauronXhrSend(this: PatchedXhr, ...args: unknown[]) {\n const meta = this.__sauron_xhr__;\n if (meta && !isInternal() && !isDsnRequest(meta.url)) {\n const onLoadEnd = (): void => {\n try {\n addXhrBreadcrumb(meta, this.status);\n } catch {\n /* ignore */\n } finally {\n try {\n this.removeEventListener('loadend', onLoadEnd);\n } catch {\n /* ignore */\n }\n }\n };\n try {\n this.addEventListener('loadend', onLoadEnd);\n } catch {\n /* ignore */\n }\n }\n return (originalSend as (...a: unknown[]) => unknown).apply(this, args);\n }) as typeof proto.send;\n\n registerPatch('xhr', () => {\n proto.open = originalOpen;\n proto.send = originalSend;\n });\n}\n","import type { Transport } from './transport.js';\n\n/**\n * Wire up the page-unload flush path. When the page is hidden or unloaded there\n * is no time for an async `fetch` round-trip, so we hand the pending batch to\n * `navigator.sendBeacon` (see {@link Transport.flushToBeacon}).\n *\n * Returns a cleanup function that removes the listeners.\n */\nexport function installBeacon(transport: Transport): () => void {\n const win = globalThis as {\n addEventListener?: (t: string, h: () => void) => void;\n removeEventListener?: (t: string, h: () => void) => void;\n };\n const doc = (globalThis as { document?: Document }).document;\n\n const flush = (): void => {\n try {\n transport.flushToBeacon();\n } catch {\n /* never throw from an unload handler */\n }\n };\n\n const onVisibility = (): void => {\n if (doc && doc.visibilityState === 'hidden') flush();\n };\n\n if (doc && typeof doc.addEventListener === 'function') {\n doc.addEventListener('visibilitychange', onVisibility);\n }\n if (typeof win.addEventListener === 'function') {\n win.addEventListener('pagehide', flush);\n }\n\n return () => {\n if (doc && typeof doc.removeEventListener === 'function') {\n doc.removeEventListener('visibilitychange', onVisibility);\n }\n if (typeof win.removeEventListener === 'function') {\n win.removeEventListener('pagehide', flush);\n }\n };\n}\n","/**\n * Payload compression.\n *\n * Prefers the native `CompressionStream('gzip')`; lazily imports `fflate` only\n * as a fallback. Payloads under {@link MIN_COMPRESS_BYTES} are left as plain\n * strings so the caller omits the `Content-Encoding` header entirely.\n */\n\n/** Below this size, compression overhead isn't worth it. */\nexport const MIN_COMPRESS_BYTES = 1024;\n\nexport interface CompressResult {\n body: Uint8Array | string;\n /** `'gzip'` only when the body was actually compressed. */\n encoding: 'gzip' | null;\n}\n\ninterface CompressionStreamCtor {\n new (format: string): {\n readable: ReadableStream<Uint8Array>;\n writable: WritableStream<Uint8Array>;\n };\n}\n\nfunction getCompressionStream(): CompressionStreamCtor | undefined {\n const g = globalThis as { CompressionStream?: CompressionStreamCtor };\n return typeof g.CompressionStream === 'function' ? g.CompressionStream : undefined;\n}\n\nasync function gzipViaStream(bytes: Uint8Array, CS: CompressionStreamCtor): Promise<Uint8Array> {\n const cs = new CS('gzip');\n const writer = cs.writable.getWriter();\n void writer.write(bytes);\n void writer.close();\n\n const reader = cs.readable.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) {\n chunks.push(value);\n total += value.length;\n }\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/** Compress a JSON string to gzip when large enough; otherwise pass it through. */\nexport async function maybeCompress(json: string): Promise<CompressResult> {\n const raw = new TextEncoder().encode(json);\n if (raw.length < MIN_COMPRESS_BYTES) {\n return { body: json, encoding: null };\n }\n\n const CS = getCompressionStream();\n if (CS) {\n try {\n const gz = await gzipViaStream(raw, CS);\n return { body: gz, encoding: 'gzip' };\n } catch {\n /* fall through to fflate */\n }\n }\n\n try {\n const { gzipSync } = await import('fflate');\n return { body: gzipSync(raw), encoding: 'gzip' };\n } catch {\n // No compression available — send uncompressed rather than drop the event.\n return { body: json, encoding: null };\n }\n}\n","import { byteLength } from '../utils.js';\n\n/** The minimal storage surface we need (a subset of `Storage`). */\nexport interface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nconst QUEUE_KEY = 'sauron:queue:v1';\n\n/** Return `localStorage` if it is present and writable, else `null`. */\nexport function defaultStorage(): StorageLike | null {\n try {\n const ls = (globalThis as { localStorage?: StorageLike }).localStorage;\n if (!ls) return null;\n const probe = '__sauron_probe__';\n ls.setItem(probe, '1');\n ls.removeItem(probe);\n return ls;\n } catch {\n // Storage disabled (private mode, blocked cookies, SSR, ...).\n return null;\n }\n}\n\n/**\n * A FIFO offline queue backed by a single `localStorage` key. Each entry is a\n * serialized envelope JSON string. The queue is byte-capped: when enqueuing\n * would exceed `maxBytes`, the OLDEST entries are evicted first.\n */\nexport class OfflineQueue {\n private readonly maxBytes: number;\n private readonly storage: StorageLike | null;\n private readonly key: string;\n\n constructor(maxBytes: number, storage: StorageLike | null, key: string = QUEUE_KEY) {\n this.maxBytes = Math.max(0, maxBytes);\n this.storage = storage;\n this.key = key;\n }\n\n /** True when a real backing store is available. */\n get available(): boolean {\n return this.storage !== null;\n }\n\n private read(): string[] {\n if (!this.storage) return [];\n try {\n const raw = this.storage.getItem(this.key);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === 'string');\n } catch {\n return [];\n }\n }\n\n private write(entries: string[]): void {\n if (!this.storage) return;\n try {\n if (entries.length === 0) {\n this.storage.removeItem(this.key);\n } else {\n this.storage.setItem(this.key, JSON.stringify(entries));\n }\n } catch {\n // Quota exceeded or storage vanished — drop silently.\n }\n }\n\n /** Drop oldest entries until the total fits under `maxBytes`. Keeps >= 1. */\n private evict(entries: string[]): void {\n let total = 0;\n for (const e of entries) total += byteLength(e);\n while (entries.length > 1 && total > this.maxBytes) {\n const removed = entries.shift();\n if (removed === undefined) break;\n total -= byteLength(removed);\n }\n }\n\n /** Append a payload to the tail (newest), evicting from the head if needed. */\n enqueue(payload: string): void {\n if (!this.storage) return;\n const entries = this.read();\n entries.push(payload);\n this.evict(entries);\n this.write(entries);\n }\n\n /** Remove and return every entry, oldest first. */\n drain(): string[] {\n const entries = this.read();\n if (entries.length) this.write([]);\n return entries;\n }\n\n /**\n * Put drained payloads BACK at the head, keeping their relative order.\n *\n * The counterpart to {@link drain}: a drain empties the store immediately, so\n * whatever the caller could not deliver only exists in its local array and is\n * lost the moment the caller returns. Re-parking at the head (rather than via\n * {@link enqueue}) keeps the queue oldest-first, which is what the byte-cap\n * eviction policy assumes — the oldest entry must stay the first one evicted.\n */\n requeueFront(payloads: string[]): void {\n if (!this.storage || payloads.length === 0) return;\n const entries = [...payloads, ...this.read()];\n this.evict(entries);\n this.write(entries);\n }\n\n /** Non-destructive read of the current entries, oldest first. */\n peek(): string[] {\n return this.read();\n }\n\n /** Number of queued entries. */\n size(): number {\n return this.read().length;\n }\n\n /** Total UTF-8 byte size of the queue. */\n byteSize(): number {\n let total = 0;\n for (const e of this.read()) total += byteLength(e);\n return total;\n }\n\n clear(): void {\n this.write([]);\n }\n}\n","import type { Dsn } from '../dsn.js';\nimport { beginInternal, endInternal } from '../integrations/instrument.js';\nimport type { Envelope, EnvelopeItem } from '../types.js';\nimport { byteLength, computeBackoff, safeStringify } from '../utils.js';\nimport { maybeCompress } from './compress.js';\nimport { defaultStorage, OfflineQueue } from './queue.js';\n\n/** `sendBeacon` / `keepalive` payloads are capped near 64 KiB by browsers. */\nexport const BEACON_MAX_BYTES = 64 * 1024;\n\n/**\n * Hard ceiling on items in one envelope, matching the server's own limit.\n * Exceeding it is a non-retryable 400, so the batch would simply be lost.\n */\nexport const MAX_ITEMS_PER_ENVELOPE = 1000;\n\n/** Max delivery attempts before a batch is parked in the offline queue. */\nconst MAX_RETRIES = 5;\n\n/** Retry-After is honored but clamped so `flush()`/`close()` can't hang forever. */\nconst RETRY_AFTER_CAP_MS = 30_000;\n\ntype SendAction = 'drop' | 'disable' | 'split' | 'retry_after' | 'retry_backoff';\n\ninterface SendOutcome {\n action: SendAction;\n retryAfterMs?: number;\n}\n\ninterface HttpResult {\n status: number;\n retryAfter: string | null;\n}\n\ninterface Logger {\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport interface TransportConfig {\n dsn: Dsn;\n options: { flushIntervalMs: number; maxBatch: number; maxQueueBytes: number };\n makeEnvelope: (items: EnvelopeItem[]) => Envelope;\n fetchImpl?: typeof fetch;\n logger: Logger;\n onDisable: () => void;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\nfunction parseRetryAfter(header: string | null): number {\n if (!header) return 1000;\n const seconds = Number(header);\n if (!Number.isNaN(seconds)) {\n return Math.min(RETRY_AFTER_CAP_MS, Math.max(0, seconds * 1000));\n }\n const date = Date.parse(header);\n if (!Number.isNaN(date)) {\n return Math.min(RETRY_AFTER_CAP_MS, Math.max(0, date - Date.now()));\n }\n return 1000;\n}\n\n/** Map an HTTP status onto the locked response-handling table. */\nfunction classifyStatus(status: number, retryAfter: string | null): SendOutcome {\n if (status === 200 || status === 202) return { action: 'drop' };\n if (status === 400) return { action: 'drop' };\n if (status === 401 || status === 403) return { action: 'disable' };\n if (status === 408) return { action: 'retry_backoff' };\n if (status === 413) return { action: 'split' };\n if (status === 429) return { action: 'retry_after', retryAfterMs: parseRetryAfter(retryAfter) };\n if (status >= 500) return { action: 'retry_backoff' };\n if (status >= 400) return { action: 'drop' }; // other 4xx: client error, no retry\n return { action: 'drop' };\n}\n\n/**\n * Batching transport with retry/backoff, an offline queue and a beacon path.\n *\n * All outbound requests go through `fetchImpl` (the NATIVE fetch captured before\n * integrations wrapped it) or an XHR fallback, so the transport never triggers\n * its own instrumentation.\n */\nexport class Transport {\n private readonly dsn: Dsn;\n private readonly makeEnvelope: (items: EnvelopeItem[]) => Envelope;\n private readonly fetchImpl?: typeof fetch;\n private readonly logger: Logger;\n private readonly onDisable: () => void;\n private readonly flushIntervalMs: number;\n private readonly maxBatch: number;\n private readonly offline: OfflineQueue;\n\n private pending: EnvelopeItem[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private onlineHandler: (() => void) | null = null;\n /** Permanent auto-disable latch, flipped by this transport itself the moment\n * it classifies a response as 401/403 — it is the source of truth for\n * {@link isEnabled}, not merely a mirror of something the client decided. */\n private disabled = false;\n\n constructor(config: TransportConfig) {\n this.dsn = config.dsn;\n this.makeEnvelope = config.makeEnvelope;\n this.fetchImpl = config.fetchImpl;\n this.logger = config.logger;\n this.onDisable = config.onDisable;\n this.flushIntervalMs = config.options.flushIntervalMs;\n // Clamped to the server's per-envelope limit: a configured `maxBatch`\n // above it would produce envelopes that are rejected outright.\n this.maxBatch = Math.min(\n MAX_ITEMS_PER_ENVELOPE,\n Math.max(1, config.options.maxBatch),\n );\n this.offline = new OfflineQueue(config.options.maxQueueBytes, defaultStorage());\n }\n\n /** Begin periodic flushing and listen for connectivity restoration. */\n start(): void {\n if (this.timer === null && this.flushIntervalMs > 0) {\n this.timer = setInterval(() => {\n void this.flush();\n }, this.flushIntervalMs);\n // Don't hold the Node event loop open (harmless/no-op in browsers).\n (this.timer as { unref?: () => void }).unref?.();\n }\n const g = globalThis as { addEventListener?: (t: string, h: () => void) => void };\n if (typeof g.addEventListener === 'function' && !this.onlineHandler) {\n this.onlineHandler = () => {\n void this.drainOfflineQueue();\n };\n g.addEventListener('online', this.onlineHandler);\n }\n }\n\n /** Stop timers and listeners (does not flush). */\n stop(): void {\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n const g = globalThis as { removeEventListener?: (t: string, h: () => void) => void };\n if (this.onlineHandler && typeof g.removeEventListener === 'function') {\n g.removeEventListener('online', this.onlineHandler);\n this.onlineHandler = null;\n }\n }\n\n /** Permanently disable the transport (401/403). Drops pending work. */\n disable(): void {\n this.disabled = true;\n this.pending = [];\n this.stop();\n }\n\n /** Whether the transport still accepts items (false once auth-disabled by a 401/403). */\n isEnabled(): boolean {\n return !this.disabled;\n }\n\n /** Queue an item for the next batch; flush eagerly once the batch is full. */\n send(item: EnvelopeItem): void {\n if (this.disabled) return;\n this.pending.push(item);\n if (this.pending.length >= this.maxBatch) {\n void this.flush();\n }\n }\n\n /**\n * Flush all pending items (plus a drain of the offline queue). Resolves to\n * `true` on completion, or `false` if `timeoutMs` elapsed first.\n */\n async flush(timeoutMs?: number): Promise<boolean> {\n if (this.disabled) return true;\n const items = this.pending.splice(0, this.pending.length);\n\n const work = (async (): Promise<boolean> => {\n await this.drainOfflineQueue();\n for (let i = 0; i < items.length; i += this.maxBatch) {\n await this.deliver(items.slice(i, i + this.maxBatch));\n }\n return true;\n })();\n\n if (typeof timeoutMs === 'number' && timeoutMs >= 0) {\n return Promise.race([work, delay(timeoutMs).then(() => false)]);\n }\n return work;\n }\n\n /** Send an already-serialized batch, applying the retry/backoff policy. */\n private async deliver(items: EnvelopeItem[], attempt = 0): Promise<void> {\n if (this.disabled || items.length === 0) return;\n\n const json = safeStringify(this.makeEnvelope(items));\n let outcome: SendOutcome;\n try {\n outcome = await this.post(json);\n } catch {\n outcome = { action: 'retry_backoff' }; // network error\n }\n\n switch (outcome.action) {\n case 'drop':\n return;\n case 'disable':\n this.logger.warn('server rejected credentials; disabling client');\n // Flip our own latch FIRST — `disabled` (and therefore `isEnabled()`)\n // must already be true by the time the client hears about it, so a\n // client whose enabled predicate is computed from us (not pushed to)\n // can never observe a stale \"still enabled\" in between.\n this.disable();\n this.onDisable();\n return;\n case 'split': {\n if (items.length <= 1) {\n this.logger.warn('single item too large (413); parking offline');\n this.offline.enqueue(json);\n return;\n }\n const mid = Math.ceil(items.length / 2);\n await this.deliver(items.slice(0, mid), attempt);\n await this.deliver(items.slice(mid), attempt);\n return;\n }\n case 'retry_after':\n case 'retry_backoff': {\n if (attempt >= MAX_RETRIES) {\n this.offline.enqueue(json);\n return;\n }\n const wait =\n outcome.action === 'retry_after'\n ? (outcome.retryAfterMs ?? 1000)\n : computeBackoff(attempt);\n await delay(wait);\n return this.deliver(items, attempt + 1);\n }\n }\n }\n\n /**\n * Re-attempt any envelopes that were parked while offline.\n *\n * `drain()` empties `localStorage` in one shot, so from here on the ONLY copy\n * of the backlog is the local `payloads` array. Every early return therefore\n * has to re-park the whole untried remainder, not just the payload that\n * failed: this used to re-park the failing one and return, which silently\n * deleted every payload behind it — the exact reconnect-then-one-500 case the\n * queue exists for.\n */\n async drainOfflineQueue(): Promise<void> {\n if (this.disabled || !this.offline.available) return;\n const payloads = this.offline.drain();\n for (let i = 0; i < payloads.length; i++) {\n const json = payloads[i];\n let outcome: SendOutcome;\n try {\n outcome = await this.post(json);\n } catch {\n outcome = { action: 'retry_backoff' };\n }\n if (outcome.action === 'disable') {\n this.logger.warn('server rejected credentials while draining; disabling client');\n this.disable();\n this.onDisable();\n // The credentials may be fixed and the client re-inited; keep the\n // backlog rather than throwing it away on the way out.\n this.offline.requeueFront(payloads.slice(i));\n return;\n }\n if (outcome.action === 'retry_after' || outcome.action === 'retry_backoff') {\n // Still failing — re-park this payload AND everything after it, then\n // stop draining to avoid a tight loop.\n this.offline.requeueFront(payloads.slice(i));\n return;\n }\n // drop / split: treat as handled.\n }\n }\n\n /** Best-effort synchronous-ish flush for page unload via `sendBeacon`. */\n flushToBeacon(): void {\n if (this.disabled) return;\n const all = this.pending.splice(0, this.pending.length);\n if (all.length === 0) return;\n\n // Chunk like the normal path already does. This one sent everything\n // buffered as a single envelope, so unloading after a busy session could\n // exceed the server's per-envelope item limit — a non-retryable 400, and\n // there is no page left to retry from.\n for (let i = 0; i < all.length; i += MAX_ITEMS_PER_ENVELOPE) {\n this.beaconChunk(all.slice(i, i + MAX_ITEMS_PER_ENVELOPE));\n }\n }\n\n private beaconChunk(items: EnvelopeItem[]): void {\n const json = safeStringify(this.makeEnvelope(items));\n const nav = (globalThis as { navigator?: Navigator }).navigator;\n const size = byteLength(json);\n\n if (nav && typeof nav.sendBeacon === 'function' && size <= BEACON_MAX_BYTES) {\n try {\n const blob = new Blob([json], { type: 'application/json' });\n if (nav.sendBeacon(this.dsn.beaconUrl, blob)) return;\n } catch {\n /* fall through to offline queue */\n }\n }\n // Beacon unavailable or oversized: persist for the next page load.\n this.offline.enqueue(json);\n }\n\n /** Compress (when large) and POST one serialized envelope. */\n private async post(json: string): Promise<SendOutcome> {\n const { body, encoding } = await maybeCompress(json);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Sauron-Key': this.dsn.publicKey,\n };\n if (encoding) headers['Content-Encoding'] = encoding;\n\n const size = typeof body === 'string' ? byteLength(body) : body.byteLength;\n const result = await this.doRequest(headers, body, size <= BEACON_MAX_BYTES);\n return classifyStatus(result.status, result.retryAfter);\n }\n\n private async doRequest(\n headers: Record<string, string>,\n body: Uint8Array | string,\n keepalive: boolean,\n ): Promise<HttpResult> {\n if (this.fetchImpl) {\n beginInternal();\n let promise: Promise<Response>;\n try {\n promise = this.fetchImpl(this.dsn.envelopeUrl, {\n method: 'POST',\n headers,\n body: body as BodyInit,\n keepalive,\n });\n } finally {\n endInternal();\n }\n const res = await promise;\n return { status: res.status, retryAfter: res.headers?.get?.('Retry-After') ?? null };\n }\n return this.xhrRequest(headers, body);\n }\n\n private xhrRequest(\n headers: Record<string, string>,\n body: Uint8Array | string,\n ): Promise<HttpResult> {\n return new Promise<HttpResult>((resolve, reject) => {\n const XHR = (globalThis as { XMLHttpRequest?: typeof XMLHttpRequest }).XMLHttpRequest;\n if (typeof XHR !== 'function') {\n reject(new Error('no transport available'));\n return;\n }\n beginInternal();\n try {\n const xhr = new XHR();\n xhr.open('POST', this.dsn.envelopeUrl, true);\n for (const key of Object.keys(headers)) {\n try {\n xhr.setRequestHeader(key, headers[key]);\n } catch {\n /* forbidden header — skip */\n }\n }\n xhr.onload = () =>\n resolve({ status: xhr.status, retryAfter: safeHeader(xhr, 'Retry-After') });\n xhr.onerror = () => reject(new Error('xhr network error'));\n xhr.ontimeout = () => reject(new Error('xhr timeout'));\n xhr.send(body as XMLHttpRequestBodyInit);\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n } finally {\n endInternal();\n }\n });\n }\n\n /** Offline queue accessor (used by tests / diagnostics). */\n get offlineQueue(): OfflineQueue {\n return this.offline;\n }\n}\n\nfunction safeHeader(xhr: XMLHttpRequest, name: string): string | null {\n try {\n return xhr.getResponseHeader(name);\n } catch {\n return null;\n }\n}\n","import { buildContext } from './context.js';\nimport { parseDsn, type Dsn } from './dsn.js';\nimport { buildEnvelope } from './envelope.js';\nimport {\n clearLastIdentified,\n getAnonymousId,\n getDeviceId,\n getLastIdentified,\n getSessionId,\n hashIdentity,\n resetAnonymousId,\n rotateSessionId,\n setLastIdentified,\n} from './identity.js';\nimport { installConsole } from './integrations/console.js';\nimport { installDom } from './integrations/dom.js';\nimport { installFetch } from './integrations/fetch.js';\nimport { installGlobalHandlers } from './integrations/globalHandlers.js';\nimport { installHistory, onNavigation } from './integrations/history.js';\nimport * as instrument from './integrations/instrument.js';\nimport { installPerformance } from './integrations/performance.js';\nimport { installXhr } from './integrations/xhr.js';\nimport { setScreen } from './api/product.js';\nimport { Scope, mergeMeta } from './scope.js';\nimport { resetScreen, setScreenState } from './screen.js';\nimport { getWorkflow, resetWorkflow } from './workflow.js';\nimport { installBeacon } from './transport/beacon.js';\nimport { Transport } from './transport/transport.js';\nimport type {\n Breadcrumb,\n Envelope,\n EnvelopeItem,\n ErrorItem,\n Hint,\n InitOptions,\n ResolvedOptions,\n} from './types.js';\nimport { clamp, makeLogger, nowIso, SDK_NAME, SDK_VERSION, uuidv4 } from './utils.js';\n\ntype Logger = ReturnType<typeof makeLogger>;\n\n/**\n * The Sauron client singleton. Owns the resolved options, the scope\n * (user + breadcrumbs), the transport, and the installed integrations.\n */\nexport class SauronClient {\n readonly options: ResolvedOptions;\n readonly dsn: Dsn;\n\n private readonly scope: Scope;\n private readonly transport: Transport;\n private readonly logger: Logger;\n private readonly nativeFetch?: typeof fetch;\n\n private enabled = true;\n private installed = false;\n private beaconCleanup: (() => void) | null = null;\n\n constructor(options: ResolvedOptions) {\n this.options = options;\n this.dsn = parseDsn(options.dsn);\n this.logger = makeLogger(options.debug);\n this.scope = new Scope(options.maxBreadcrumbs);\n // Seed init-default metadata into the global scope so every later signal\n // inherits it; runtime setters still last-write-win over these.\n this.scope.setTags(options.tags);\n for (const [name, block] of Object.entries(options.contexts)) {\n this.scope.setContext(name, block);\n }\n for (const [key, value] of Object.entries(options.extra)) {\n this.scope.setExtra(key, value);\n }\n\n // Capture the NATIVE fetch before any integration wraps it, so the\n // transport's own requests never hit our instrumentation.\n const g = globalThis as { fetch?: typeof fetch };\n this.nativeFetch = typeof g.fetch === 'function' ? g.fetch.bind(globalThis) : undefined;\n\n instrument.setDsnHost(this.dsn.host);\n\n this.transport = new Transport({\n dsn: this.dsn,\n options: options.transport,\n makeEnvelope: (items) => this.makeEnvelope(items),\n fetchImpl: this.nativeFetch,\n logger: this.logger,\n onDisable: () => this.disable(),\n });\n }\n\n /** Install global handlers + auto-instrumentation and start the transport. */\n install(): void {\n if (this.installed) return;\n this.installed = true;\n\n // Establish the durable device id and the current session id at init.\n getDeviceId();\n getSessionId();\n\n installGlobalHandlers();\n installConsole();\n installDom();\n installHistory();\n installFetch();\n installXhr();\n if (this.options.performance) installPerformance();\n\n // Screen tracking: seed the initial screen, then follow SPA navigations.\n if (this.options.screen) setScreenState(this.options.screen);\n if (this.options.screenTracking) {\n onNavigation((path) => setScreen(path));\n }\n\n this.beaconCleanup = installBeacon(this.transport);\n\n this.transport.start();\n void this.transport.drainOfflineQueue();\n this.logger.log('initialized', { dsn: this.dsn.host, project: this.dsn.projectId });\n }\n\n getScope(): Scope {\n return this.scope;\n }\n\n /**\n * False once this client was explicitly disabled/closed, OR once the\n * transport has auto-disabled itself on a 401/403 (revoked/invalid DSN\n * key) — computed from the transport's own state on every call, not a\n * separately mirrored flag, so a propagation regression there cannot leave\n * this predicate stale. `this.transport` always exists once a client\n * exists (it is constructed synchronously in the constructor); the\n * \"nothing installed yet\" case is instead handled one layer up, by every\n * module-level API (`startWorkflow`, `track`, ...) treating `getClient() ===\n * null` as the no-op/disabled case before it ever reaches here.\n */\n isEnabled(): boolean {\n return this.enabled && this.transport.isEnabled();\n }\n\n /**\n * Whether the anonymous id has actually been USED as a `distinct_id` in this\n * browser session.\n *\n * A persisted id that has never been observed anonymously must not create a\n * permanent `identities` alias row on the server: aliasing is a durable\n * server-side binding of this browser profile to a named user, and an\n * identify() on a first-ever page load has no anonymous history to link.\n */\n private anonUsed = false;\n\n /** The current distinct id: the user id when identified, else an anon id. */\n getDistinctId(): string | null {\n const user = this.scope.getUser();\n if (user.id) return user.id;\n this.anonUsed = true;\n return getAnonymousId();\n }\n\n /** The anonymous id, or null when it was never actually used as an identity. */\n getAnonymousId(): string | null {\n return this.anonUsed ? getAnonymousId() : null;\n }\n\n /**\n * Forget the current person: clear the scope user, mint a fresh anonymous\n * id, forget the last identified user, and rotate the session id.\n *\n * MUST BE CALLED ON LOGOUT. Without it, the next anonymous visitor on this\n * browser reuses the persisted anon id, and a later identify() aliases their\n * activity to the previous account server-side, permanently. Rotating the\n * session id matters too: the server's `bump_session` is last-write-wins on\n * `distinct_id`, so without rotation one `sessions` row could otherwise\n * serially represent two different people and record only whichever wrote\n * last.\n */\n reset(): void {\n this.scope.setUser(null);\n resetAnonymousId();\n clearLastIdentified();\n rotateSessionId();\n this.anonUsed = false;\n }\n\n /**\n * Prepare for an `identify()`; returns the `anonymous_id` to send.\n *\n * When a DIFFERENT user identifies than last time, the current anon id\n * belongs to the previous person and is already burned server-side, so it is\n * replaced before anything else happens and `null` is sent instead of a\n * cross-user alias. This cannot repair events already sent under the burned\n * alias — nothing can — but it bounds a forgotten `reset()` to one guest\n * window instead of every future one.\n *\n * `id` is coerced with `String()` before comparing/persisting: a plain-JS\n * caller can pass a number (`Sauron.identify(user.id)`), and `Storage`\n * itself applies `ToString` on write — so comparing an un-coerced `id`\n * against a value that already round-tripped through storage would treat\n * the SAME numeric user as a switch on every single call. The comparison\n * against `last` is an explicit `!== null` (not a truthiness check) so an\n * app that (unusually) identifies with `''` still has a later, different id\n * correctly detected as a real switch — a falsy string is not \"no identity\n * yet\". `last`/the persisted value are digests, not the raw id — see\n * `hashIdentity`.\n */\n prepareIdentify(id: string): string | null {\n const digest = hashIdentity(String(id));\n const last = getLastIdentified();\n if (last !== null && last !== digest) {\n resetAnonymousId();\n rotateSessionId();\n this.anonUsed = false;\n }\n setLastIdentified(digest);\n return this.getAnonymousId();\n }\n\n /** Stamp a fresh envelope (new `sent_at`, current context) around `items`. */\n makeEnvelope(items: EnvelopeItem[]): Envelope {\n const header = {\n dsn: this.dsn.raw,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n sent_at: nowIso(),\n release: this.options.release,\n };\n const context = buildContext(this.options.release, this.scope.getUser());\n return buildEnvelope(header, context, items);\n }\n\n /** Add a breadcrumb, running it through `beforeBreadcrumb` first. */\n addBreadcrumb(breadcrumb: Breadcrumb, hint?: Hint): void {\n if (!this.enabled) return;\n let processed: Breadcrumb | null = breadcrumb;\n if (this.options.beforeBreadcrumb) {\n try {\n processed = this.options.beforeBreadcrumb(breadcrumb, hint);\n } catch (err) {\n this.logger.warn('beforeBreadcrumb threw', err);\n processed = breadcrumb;\n }\n }\n if (!processed) return;\n this.scope.addBreadcrumb(processed);\n }\n\n /**\n * Reconcile an error item to the shared wire shape by filling the optional\n * `event_id`/`message`/`tags`/`user` fields from the current scope and hint.\n * Each field is left untouched when the item already sets it, and omitted\n * entirely when there is nothing to attach (the backend defaults it) — only\n * `event_id` is always minted so callers can correlate the report.\n */\n private enrichErrorItem(item: ErrorItem, hint?: Hint): void {\n if (item.event_id === undefined) {\n const hinted = hint?.event_id;\n item.event_id = typeof hinted === 'string' ? hinted : uuidv4();\n }\n if (item.message === undefined && typeof hint?.message === 'string') {\n item.message = hint.message;\n }\n const tags = mergeMeta(this.scope.tags, item.tags);\n if (Object.keys(tags).length > 0) item.tags = tags;\n const contexts = mergeMeta(this.scope.contexts, item.contexts);\n if (Object.keys(contexts).length > 0) item.contexts = contexts;\n const extra = mergeMeta(this.scope.extra, item.extra);\n if (Object.keys(extra).length > 0) item.extra = extra;\n if (item.user === undefined && this.scope.hasUser()) {\n item.user = this.scope.getUser();\n }\n }\n\n /**\n * Stamp the active workflow (if any) onto a signal item.\n *\n * Done HERE — the single choke point every capture path funnels through —\n * rather than at each item-construction site, so a capture path added later\n * is stamped by construction instead of by remembering to. The keys are\n * ASSIGNED ONLY when a workflow is active: an item with no workflow keeps\n * them absent entirely (not present-as-`undefined`), which is what makes\n * `JSON.stringify` omit them and keeps the no-workflow wire bytes identical\n * to pre-1.3.0.\n *\n * Only error/event/transaction carry `workflow_id`/`workflow_name` columns\n * server-side — identify and breadcrumb_batch items are deliberately left\n * alone. An item that already carries an explicit `workflow_id` is left\n * untouched, matching how `enrichErrorItem` defers to caller-set fields.\n */\n private stampWorkflow(item: EnvelopeItem): void {\n if (item.type !== 'error' && item.type !== 'event' && item.type !== 'transaction') return;\n\n // `captureItem` is a public escape hatch, so an item can arrive already\n // attributed. Caller-set wins — same rule `enrichErrorItem` applies to\n // `event_id`/`message`/`user`.\n //\n // But the two fields are a PAIR, not two independent options: the server\n // guards on `if let (Some(id), Some(name))`, so an item carrying only one\n // of them is silently dropped from every workflow query. That failure is\n // invisible, so warn rather than let it through quietly — and still leave\n // the item alone, because overwriting a caller's deliberate (if partial)\n // attribution with a different workflow would be worse than not stamping.\n const hasId = item.workflow_id !== undefined;\n const hasName = item.workflow_name !== undefined;\n if (hasId || hasName) {\n if (hasId !== hasName) {\n this.logger.warn(\n 'item sets only one of workflow_id/workflow_name; the server treats them as a ' +\n 'pair and will drop this attribution. Set both, or neither.',\n );\n }\n return;\n }\n\n const workflow = getWorkflow();\n if (!workflow) return;\n item.workflow_id = workflow.workflowId;\n item.workflow_name = workflow.name;\n }\n\n /**\n * Run an item through sampling (errors only) and `beforeSend`, then hand it to\n * the transport. Returns silently when dropped.\n */\n captureItem(item: EnvelopeItem, hint?: Hint): void {\n if (!this.enabled) return;\n\n if (item.type === 'error') {\n if (Math.random() >= this.options.sampleRate) {\n this.logger.log('dropped error by sampleRate');\n return;\n }\n this.enrichErrorItem(item, hint);\n }\n\n // Before `beforeSend`, so a consumer's hook sees the workflow fields.\n this.stampWorkflow(item);\n\n let processed: EnvelopeItem | null = item;\n if (this.options.beforeSend) {\n try {\n processed = this.options.beforeSend(item, hint);\n } catch (err) {\n this.logger.warn('beforeSend threw', err);\n processed = item;\n }\n }\n if (!processed) {\n this.logger.log('dropped by beforeSend');\n return;\n }\n\n this.transport.send(processed);\n }\n\n /** Flush pending events. Resolves false if `timeoutMs` elapses first. */\n flush(timeoutMs?: number): Promise<boolean> {\n return this.transport.flush(timeoutMs);\n }\n\n /** Disable the client (called on 401/403). Stops accepting/sending events. */\n disable(): void {\n if (!this.enabled) return;\n this.enabled = false;\n this.transport.disable();\n this.logger.warn('client disabled');\n }\n\n /** Restore all patched globals and stop timers/listeners. */\n teardown(): void {\n this.enabled = false;\n this.transport.stop();\n if (this.beaconCleanup) {\n this.beaconCleanup();\n this.beaconCleanup = null;\n }\n onNavigation(null);\n resetScreen();\n resetWorkflow();\n instrument.unpatchAll();\n instrument.setDsnHost(null);\n this.installed = false;\n }\n\n /** Flush then tear down. Resolves to the flush result. */\n async close(timeoutMs?: number): Promise<boolean> {\n const flushed = await this.transport.flush(timeoutMs);\n this.teardown();\n return flushed;\n }\n}\n\n/* ---------------------------------------------------------------- singleton */\n\nlet currentClient: SauronClient | null = null;\n\n/** The active client, or null before `init`. */\nexport function getClient(): SauronClient | null {\n return currentClient;\n}\n\nfunction resolveOptions(options: InitOptions): ResolvedOptions {\n if (!options || typeof options.dsn !== 'string' || options.dsn.length === 0) {\n throw new Error('[sauron] init() requires a `dsn`');\n }\n const t = options.transport ?? {};\n return {\n dsn: options.dsn,\n release: options.release ?? null,\n sampleRate: clamp(options.sampleRate ?? 1, 0, 1),\n maxBreadcrumbs: options.maxBreadcrumbs ?? 50,\n tags: options.tags ?? {},\n contexts: options.contexts ?? {},\n extra: options.extra ?? {},\n beforeSend: options.beforeSend,\n beforeBreadcrumb: options.beforeBreadcrumb,\n transport: {\n flushIntervalMs: t.flushIntervalMs ?? 5000,\n maxBatch: t.maxBatch ?? 30,\n maxQueueBytes: t.maxQueueBytes ?? 1048576,\n },\n performance: options.performance ?? false,\n screen: options.screen,\n screenTracking: options.screenTracking ?? false,\n debug: options.debug ?? false,\n };\n}\n\n/**\n * Initialize the SDK. Idempotent: a second call tears down the previous client\n * (restoring patched globals) before installing a fresh one.\n */\nexport function init(options: InitOptions): SauronClient {\n if (currentClient) {\n try {\n currentClient.teardown();\n } catch {\n /* ignore teardown failures */\n }\n }\n const resolved = resolveOptions(options);\n const client = new SauronClient(resolved);\n currentClient = client;\n client.install();\n return client;\n}\n","import { getClient } from '../client.js';\nimport type { Breadcrumb, Hint, Level } from '../types.js';\nimport { nowIso } from '../utils.js';\n\n/** Partial breadcrumb — missing fields are filled with sensible defaults. */\nexport interface BreadcrumbInput {\n type?: string;\n category?: string;\n message?: string | null;\n level?: Level;\n timestamp?: string;\n data?: Record<string, unknown> | null;\n}\n\n/** Normalize a partial breadcrumb into the full wire shape. */\nexport function normalizeBreadcrumb(input: BreadcrumbInput): Breadcrumb {\n return {\n type: input.type ?? 'default',\n category: input.category ?? 'default',\n message: input.message ?? null,\n level: input.level ?? 'info',\n timestamp: input.timestamp ?? nowIso(),\n data: input.data ?? null,\n };\n}\n\n/**\n * Record a breadcrumb. Runs through `beforeBreadcrumb` (the PII escape hatch)\n * and is stored in the ring buffer — nothing is sent until an error is captured.\n */\nexport function addBreadcrumb(input: BreadcrumbInput, hint?: Hint): void {\n const client = getClient();\n if (!client) return;\n client.addBreadcrumb(normalizeBreadcrumb(input), hint);\n}\n\n/**\n * How a navigation moved the history stack. Shared vocabulary with the Flutter\n * SDK's `SauronNavigatorObserver`, so a trail reads the same whichever SDK sent\n * it. `remove` has no web equivalent and is never emitted here.\n */\nexport type NavigationOperation = 'push' | 'pop' | 'replace' | 'remove';\n\n/**\n * Convenience helper for navigation breadcrumbs.\n *\n * `operation` is what the *browser* did, which is not always what the user\n * meant: `history.forward()` fires the same `popstate` as `history.back()` and\n * carries nothing to separate them, so both arrive here as `pop`.\n */\nexport function addNavigationBreadcrumb(\n from: string | null,\n to: string | null,\n operation: NavigationOperation = 'push',\n): void {\n addBreadcrumb({\n type: 'navigation',\n category: 'history',\n level: 'info',\n message: null,\n data: { from, to, operation },\n });\n}\n","/**\n * `@edraj/sauron-browser` — public API surface.\n *\n * Error reporting + product analytics for the browser. Import the named\n * functions, or the `Sauron` facade / default export.\n *\n * ```ts\n * import { Sauron } from '@edraj/sauron-browser';\n * Sauron.init({ dsn: 'https://pk_test@localhost:8081/1', release: 'web@1.4.2' });\n * Sauron.track('checkout_completed', { cart_value: 42.5 });\n * ```\n */\n\nimport { addBreadcrumb as addBreadcrumbApi, type BreadcrumbInput } from './api/breadcrumbs.js';\nimport { captureException as captureExceptionApi, captureMessage as captureMessageApi } from './api/capture.js';\nimport {\n cancelWorkflow as cancelWorkflowApi,\n endWorkflow as endWorkflowApi,\n identify as identifyApi,\n setScreen as setScreenApi,\n startWorkflow as startWorkflowApi,\n track as trackApi,\n trackTransaction as trackTransactionApi,\n type TransactionInput,\n} from './api/product.js';\nimport { getClient, init as initClient, SauronClient } from './client.js';\nimport { getScreen as getScreenApi } from './screen.js';\nimport type {\n ActiveWorkflow,\n Hint,\n InitOptions,\n Level,\n TrackOptions,\n UserInput,\n WorkflowResult,\n} from './types.js';\nimport { getWorkflow as getWorkflowApi } from './workflow.js';\n\n/** Initialize the SDK. See {@link InitOptions}. */\nexport function init(options: InitOptions): SauronClient {\n return initClient(options);\n}\n\n/** Capture an exception (or any thrown value). */\nexport function captureException(err: unknown, hint?: Hint): void {\n captureExceptionApi(err, hint);\n}\n\n/** Capture a plain message at the given `level` (default `info`). */\nexport function captureMessage(message: string, level: Level = 'info', hint?: Hint): void {\n captureMessageApi(message, level, hint);\n}\n\n/** Record a product-analytics event, optionally with per-call tags/contexts/extra. */\nexport function track(\n name: string,\n properties?: Record<string, unknown>,\n options?: TrackOptions,\n): void {\n trackApi(name, properties, options);\n}\n\n/**\n * Associate the session with a known user.\n *\n * The `anonymous_id` sent with the identify item is the current anon id — but\n * only when it was actually used as a `distinct_id` this session, and never\n * when it belongs to a different person than the last one who identified on\n * this device. In that case a fresh anon id is minted first and `null` is\n * sent instead, since the old one is already permanently bound to the\n * previous person server-side (see `reset()`).\n */\nexport function identify(id: string, traits?: Record<string, unknown>): void {\n identifyApi(id, traits);\n}\n\n/** Record a performance transaction (navigation, http, screen load, ...). */\nexport function trackTransaction(input: TransactionInput): void {\n trackTransactionApi(input);\n}\n\n/** Set the current screen (emits a `$screen` view on change). */\nexport function setScreen(name: string): void {\n setScreenApi(name);\n}\n\n/** The current screen name, or null. */\nexport function getScreen(): string | null {\n return getScreenApi();\n}\n\n/**\n * Start a named, explicitly-bounded workflow. `workflow_id` is a fresh\n * client-generated UUID; the id + name are then stamped on every subsequent\n * event/error/transaction until the workflow ends or is cancelled. Optional —\n * an app that never calls this behaves exactly as before.\n */\nexport function startWorkflow(name: string, options?: { force?: boolean }): WorkflowResult {\n return startWorkflowApi(name, options);\n}\n\n/** End the active workflow (or the one named `name`, if given). */\nexport function endWorkflow(name?: string): WorkflowResult {\n return endWorkflowApi(name);\n}\n\n/** Cancel the active workflow (or the one named `name`, if given). */\nexport function cancelWorkflow(name?: string, options?: { reason?: string }): WorkflowResult {\n return cancelWorkflowApi(name, options);\n}\n\n/** The currently active workflow, or `null` when none is active. */\nexport function getWorkflow(): ActiveWorkflow | null {\n return getWorkflowApi();\n}\n\n/** Record a breadcrumb. */\nexport function addBreadcrumb(breadcrumb: BreadcrumbInput, hint?: Hint): void {\n addBreadcrumbApi(breadcrumb, hint);\n}\n\n/**\n * Set (or clear, with `null`) the current user.\n *\n * `setUser(null)` is a logout, so it also calls `reset()` for you — otherwise\n * the next anonymous visitor on this browser inherits the previous person's\n * durable id and a later identify() aliases them together server-side.\n */\nexport function setUser(user: UserInput): void {\n if (user === null) {\n getClient()?.reset();\n return;\n }\n getClient()?.getScope().setUser(user);\n}\n\n/**\n * Forget the current person: clears the scope user, mints a fresh anonymous\n * id, forgets the last identified user, and rotates the session id so a\n * single session can never span two different people. Call this on logout.\n */\nexport function reset(): void {\n getClient()?.reset();\n}\n\n/** Set a single scope tag (lifted onto later errors/events). */\nexport function setTag(key: string, value: string): void {\n getClient()?.getScope().setTag(key, value);\n}\n\n/** Merge a batch of scope tags (last-write-wins per key). */\nexport function setTags(tags: Record<string, string>): void {\n getClient()?.getScope().setTags(tags);\n}\n\n/** Set (replace) a named scope context block. */\nexport function setContext(name: string, block: Record<string, unknown>): void {\n getClient()?.getScope().setContext(name, block);\n}\n\n/** Set a single freeform scope extra value. */\nexport function setExtra(key: string, value: unknown): void {\n getClient()?.getScope().setExtra(key, value);\n}\n\n/** Flush pending events. Resolves `false` if `timeoutMs` elapses first. */\nexport function flush(timeoutMs?: number): Promise<boolean> {\n const client = getClient();\n return client ? client.flush(timeoutMs) : Promise.resolve(false);\n}\n\n/** Flush and tear down the SDK, restoring all patched globals. */\nexport function close(timeoutMs?: number): Promise<boolean> {\n const client = getClient();\n return client ? client.close(timeoutMs) : Promise.resolve(false);\n}\n\n/** The active client instance, or `null` before `init`. */\nexport { getClient, SauronClient };\n\n/** Grouped facade + default export. */\nexport const Sauron = {\n init,\n captureException,\n captureMessage,\n track,\n trackTransaction,\n identify,\n addBreadcrumb,\n setUser,\n reset,\n setTag,\n setTags,\n setContext,\n setExtra,\n setScreen,\n getScreen,\n startWorkflow,\n endWorkflow,\n cancelWorkflow,\n getWorkflow,\n flush,\n close,\n getClient,\n};\n\nexport default Sauron;\n\n/* ------------------------------------------------------------- re-exports */\n\nexport { parseDsn, DsnError } from './dsn.js';\nexport type { Dsn } from './dsn.js';\nexport { buildEnvelope } from './envelope.js';\nexport { parseStackString, parseError, isInAppFrame } from './stacktrace/parse.js';\nexport { SDK_NAME, SDK_VERSION } from './utils.js';\n// Exported so a caller can size a payload BEFORE attaching it — the cap is\n// otherwise invisible until the dashboard shows a truncation marker.\nexport { MAX_TRANSACTION_EXTRA_BYTES, capTransactionExtra } from './utils.js';\nexport type { BreadcrumbInput } from './api/breadcrumbs.js';\nexport type { TransactionInput } from './api/product.js';\n\nexport type {\n Level,\n ItemType,\n TransactionOp,\n Frame,\n Mechanism,\n ExceptionValue,\n Breadcrumb,\n ErrorItem,\n EventItem,\n IdentifyItem,\n BreadcrumbBatchItem,\n TransactionItem,\n EnvelopeItem,\n DeviceContext,\n OsContext,\n AppContext,\n RuntimeContext,\n UserContext,\n Context,\n SdkInfo,\n EnvelopeHeader,\n Envelope,\n Hint,\n UserInput,\n BeforeSend,\n BeforeBreadcrumb,\n TransportOptions,\n InitOptions,\n CaptureOptions,\n TrackOptions,\n ResolvedOptions,\n WorkflowStatus,\n WorkflowResult,\n ActiveWorkflow,\n} from './types.js';\n"]}