@utk09/ui-observability 0.4.0 → 0.5.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +74 -33
  3. package/dist/bus/bus.d.ts +9 -0
  4. package/dist/bus-D3OO0OcL.js +378 -0
  5. package/dist/bus-D3OO0OcL.js.map +1 -0
  6. package/dist/bus-OdRJVUzr.cjs +2 -0
  7. package/dist/bus-OdRJVUzr.cjs.map +1 -0
  8. package/dist/capture/types.d.ts +14 -0
  9. package/dist/capture/web-vitals.d.ts +9 -3
  10. package/dist/{constants-CrU3IUyy.js → constants-B6kdsCzF.js} +9 -8
  11. package/dist/constants-B6kdsCzF.js.map +1 -0
  12. package/dist/constants-DZH04585.cjs +2 -0
  13. package/dist/constants-DZH04585.cjs.map +1 -0
  14. package/dist/constants.d.ts +8 -1
  15. package/dist/core/journey.d.ts +5 -2
  16. package/dist/core/logger.d.ts +22 -3
  17. package/dist/core/pipeline.d.ts +10 -1
  18. package/dist/core/runtime.d.ts +102 -18
  19. package/dist/core/sender.d.ts +58 -0
  20. package/dist/errors-DPju_xSI.cjs +3 -0
  21. package/dist/errors-DPju_xSI.cjs.map +1 -0
  22. package/dist/errors-Dme9tz-6.js +76 -0
  23. package/dist/errors-Dme9tz-6.js.map +1 -0
  24. package/dist/index.cjs +1 -3
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.js +462 -2196
  27. package/dist/index.js.map +1 -1
  28. package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
  29. package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
  30. package/dist/{indexeddb-storage-CSaDuHGk.js → indexeddb-storage-nxs_rxGx.js} +30 -17
  31. package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
  32. package/dist/interactions-C1romMpE.js +67 -0
  33. package/dist/interactions-C1romMpE.js.map +1 -0
  34. package/dist/interactions-DP0-rIPJ.cjs +2 -0
  35. package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
  36. package/dist/models/config.d.ts +29 -11
  37. package/dist/network-DDVIJSHd.cjs +2 -0
  38. package/dist/network-DDVIJSHd.cjs.map +1 -0
  39. package/dist/network-au-Tqt1n.js +111 -0
  40. package/dist/network-au-Tqt1n.js.map +1 -0
  41. package/dist/platform-DMYo3AX3.js +48 -0
  42. package/dist/platform-DMYo3AX3.js.map +1 -0
  43. package/dist/platform-g99Kn755.cjs +2 -0
  44. package/dist/platform-g99Kn755.cjs.map +1 -0
  45. package/dist/sampling-ByI5H44E.js +248 -0
  46. package/dist/sampling-ByI5H44E.js.map +1 -0
  47. package/dist/sampling-Dui-Fp3u.cjs +2 -0
  48. package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
  49. package/dist/sender-R7lOpyNc.js +907 -0
  50. package/dist/sender-R7lOpyNc.js.map +1 -0
  51. package/dist/sender-vLcbQhiB.cjs +3 -0
  52. package/dist/sender-vLcbQhiB.cjs.map +1 -0
  53. package/dist/storage/idb-driver.d.ts +9 -1
  54. package/dist/storage/indexeddb-storage.d.ts +5 -0
  55. package/dist/transport/exit-flush.d.ts +11 -1
  56. package/dist/transport/http-transport.d.ts +2 -0
  57. package/dist/transport/retry-engine.d.ts +28 -3
  58. package/dist/transport/serializers/select.d.ts +8 -0
  59. package/dist/unref-16maCyKA.js +8 -0
  60. package/dist/unref-16maCyKA.js.map +1 -0
  61. package/dist/unref-CU9Nyz_9.cjs +2 -0
  62. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  63. package/dist/utils/console.d.ts +11 -3
  64. package/dist/utils/deadline.d.ts +7 -0
  65. package/dist/utils/identity.d.ts +47 -3
  66. package/dist/utils/tracing.d.ts +6 -5
  67. package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
  68. package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
  69. package/dist/web-vitals-DwWdLBq6.js +51 -0
  70. package/dist/web-vitals-DwWdLBq6.js.map +1 -0
  71. package/package.json +21 -11
  72. package/dist/constants-BpFlszME.cjs +0 -2
  73. package/dist/constants-BpFlszME.cjs.map +0 -1
  74. package/dist/constants-CrU3IUyy.js.map +0 -1
  75. package/dist/indexeddb-storage-CSaDuHGk.js.map +0 -1
  76. package/dist/indexeddb-storage-DIJIbFnp.cjs +0 -2
  77. package/dist/indexeddb-storage-DIJIbFnp.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender-vLcbQhiB.cjs","names":["newId","keyFor","EMERGENCY_STORAGE_KEY_PREFIX","withDeadline","STORAGE_DEADLINE_MS","BATCH_STORAGE_KEY_PREFIX","STORAGE_NAME_LOCAL","STORAGE_NAME_MEMORY","STORAGE_NAME_NONE","STORAGE_PROBE_KEY","NANOS_PATTERN","NANOS_PER_MILLI","ECS_LEVEL_NAMES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_BROWSER_USER_AGENT","CONTENT_TYPE_NDJSON","items","nested","SERIALIZER_NAME_OTLP","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","CONTENT_TYPE_JSON","estimateBytes","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","CONTENT_TYPE_TEXT_PLAIN","ENCODING_GZIP","MILLIS_PER_SECOND","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","HEADER_ATTEMPT","HEADER_CONTENT_ENCODING","ENCODING_GZIP","estimateBytes","REQUEST_TIMEOUT_MS","HEADER_RETRY_AFTER","RETRY_IDLE_DELAY_MS","RETRY_BASE_DELAY_MS","withDeadline","STORAGE_DEADLINE_MS","RETRY_MAX_DELAY_MS","STORAGE_LIMITS","ATTR_LOG_TYPE","LOG_TYPE_METRIC","LOG_FLUSH_INTERVAL_MS","METRIC_FLUSH_INTERVAL_MS","ErrorCeiling","nowUnixNano","newId","withDeadline","STORAGE_DEADLINE_MS","STORAGE_DB_NAME","STORAGE_LIMITS","require_constants","require_sampling","require_unref","isLogBatch","value","id","createdAt","attempts","records","splitBatch","batch","middle","halve","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","keysWithPrefix","out","i","key","prefix","keyFor$1","at","readBatch","parsed","raw","importAll","moved","storage","error","saveToEmergencyQueue","context","keys","old","drainEmergencyQueue","keyFor","createdAtOf","start","LocalStorageStorage","limits","onGap","limit","cutoff","result","drop","alive","excess","stored","countRecords","batches","total","MemoryStorage","found","expired","evicted","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","IndexedDbStorage","dbName","toMillis","timeUnixNano","toLabelValue","pushLabel","existing","labels","flattenLabel","scalar","seen","item","entry","toLabels","source","ecsSerializer","millis","record","toAnyValue","toKeyValues","resourceKeys","resourceKey","cached","resource","otlpSerializer","groups","group","resourceLogs","serializerFor","choice","ExitFlush","deps","me","url","reason","serialized","target","outcome","endpoint","nav","body","config","gzip","CS","stream","text","buffer","TransportError","message","kind","status","retryAfterMs","maxBytes","parseRetryAfter","header","seconds","date","HttpTransport","headers","response","controller","timer","online","throttled","RetryEngine","transport","batchesPerDrain","parts","part","delayMs","work","exponential","failure","halves","isMetric","STREAM_OPTIONS","RecordStream","options","onFlush","LogPipeline","retry","flush","streamOptions","inFlight","throttledMs","Sender","pipeline","exitFlush","started"],"sources":["../src/models/batch.ts","../src/utils/lock.ts","../src/storage/keys.ts","../src/storage/emergency-queue.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp.ts","../src/transport/serializers/select.ts","../src/transport/exit-flush.ts","../src/transport/compression.ts","../src/transport/errors.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. Stable across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Whether a value parsed out of storage carries the whole batch contract. An entry\n * missing `id` is never matched by `keyOf` after delivery, so it is retried forever\n * and blocks every batch behind it. One missing `attempts` counts as NaN, never\n * reaches `maxAttempts`, and is never dead-lettered.\n * @param value Parsed storage entry.\n * @returns True when every required field is present and correctly typed.\n */\nexport function isLogBatch(value: unknown): value is LogBatch {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const id: unknown = Reflect.get(value, \"id\");\n const createdAt: unknown = Reflect.get(value, \"createdAt\");\n const attempts: unknown = Reflect.get(value, \"attempts\");\n const records: unknown = Reflect.get(value, \"records\");\n\n return (\n typeof id === \"string\" &&\n typeof createdAt === \"number\" &&\n typeof attempts === \"number\" &&\n Array.isArray(records)\n );\n}\n\n/**\n * Splits a batch the server rejected as too large into two halves.\n * Each half gets a fresh id; age and attempts carry over unchanged.\n * @param batch The rejected batch.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n","// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without it every window on the origin drains and sends the same batches\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object or null if lock acquisition was unavailable. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback executed with lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * Falls back to direct execution in environments without Web Locks support.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy Skips execution if lock is currently held by another context.\n * @returns Promise resolving to the task result, or undefined if the lock was held\n * and nothing ran. A caller that conflates the two stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Falls back to unguarded execution if Web Locks API is unavailable.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\"storage.degraded\", `acquiring lock ${name}`, () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n","// src/storage/keys.ts\n//\n// Enumerates and filters sorted localStorage keys matching a prefix. A sandboxed\n// frame and private mode throw on first access rather than returning null.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/**\n * Returns all sorted localStorage keys matching the specified prefix.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\"storage.unavailable\", \"enumerating localStorage\", () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) is typed string | null but cannot be null below length.\n // A null check here is a branch no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n });\n\n return out.sort();\n}\n","// src/storage/emergency-queue.ts\n//\n// Synchronous localStorage queue parking oversized batches during unload for startup recovery.\n// Synchronous and never throws. Runs while the document is being destroyed, where\n// no promise settles.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO sorting.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${EMERGENCY_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Parses and validates a raw storage string into a LogBatch object.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"an emergency entry was not JSON and was dropped\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\"storage.degraded\", \"an emergency entry was not a batch and was dropped\");\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target storage adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(storage: StorageAdapter, diagnostics: Diagnostics): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics)) {\n // Atomically removes key before async persistence to prevent duplicate recovery.\n // A second window importing at the same time cannot take the same batch.\n const raw = diagnostics.guard(\"storage.unavailable\", \"reading the emergency queue\", () => {\n const value = localStorage.getItem(key);\n localStorage.removeItem(key);\n return value;\n });\n\n if (!raw) {\n continue;\n }\n\n const batch = readBatch(raw, diagnostics);\n if (batch === null) {\n continue;\n }\n\n try {\n // Bounded: this runs during startup. A save that does not settle keeps the\n // runtime not ready, and each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"an emergency batch could not be recovered\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Synchronously writes an unsent batch to the emergency queue during document unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n */\nexport function saveToEmergencyQueue(batch: LogBatch, diagnostics: Diagnostics): void {\n // Names the record count, because a full localStorage drops this batch for good:\n // evicting emergency keys cannot free quota another application's keys are using.\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n\n diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(EMERGENCY_STORAGE_KEY_PREFIX, diagnostics);\n\n // Evicts oldest entries to enforce capacity ceiling.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n });\n}\n\n/**\n * Recovers batches parked in emergency storage during prior shutdowns.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise resolving to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n): Promise<number> {\n const moved = await withDrainLock(\n EMERGENCY_LOCK_NAME,\n diagnostics,\n () => importAll(storage, diagnostics),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n","// src/storage/local-storage.ts\n//\n// Persistent synchronous storage adapter backed by localStorage using time-ordered\n// keys. The padding makes keys().sort() a sort by creation time. Unpadded it sorts\n// by hex and take() stops returning the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { keysWithPrefix } from \"./keys\";\n\n/**\n * Formats a storage key with zero-padded creation time for FIFO key sorting. Always\n * from batch.createdAt, never Date.now(). A rebuilt key does not match the one\n * written.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nfunction keyFor(batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${BATCH_STORAGE_KEY_PREFIX}${at}.${batch.id}`;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after each save. Read\n * from the batch, this field costs one parse of the full store for each save.\n * @param key Prefixed storage key.\n * @returns Creation time in epoch milliseconds, or null if the key is malformed.\n */\nfunction createdAtOf(key: string): number | null {\n const start = BATCH_STORAGE_KEY_PREFIX.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** Persistent StorageAdapter implementation backed by localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Persists a batch to localStorage, evicting oldest entries on quota errors.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\n\n // The eviction exists to make room for this batch. Without a second attempt\n // save() resolves while the batch is gone and uncounted.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\n }\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // Corrupt and unrecoverable. Dropped without counting a gap: no record count\n // can be read from it.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Deletes a batch from localStorage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Updates delivery attempt count for a stored batch without changing its key.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\"storage.degraded\", \"updating attempts\", () => {\n localStorage.setItem(key, JSON.stringify(batch));\n });\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n // Parses only the batches it deletes. The record count is the one field the\n // key does not carry.\n const drop = (key: string): void => {\n const batch = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += batch?.records.length ?? 0;\n };\n\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key);\n // A key with no readable time also has no position in the sort order.\n if (createdAt === null || createdAt < cutoff) {\n drop(key);\n continue;\n }\n alive.push(key);\n }\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n for (const key of alive.slice(0, excess)) {\n drop(key);\n }\n }\n\n this.reportGap(result);\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batch keys without deserialization.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes all matching batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** No-op storage teardown method. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch Batch to store.\n * @param context Description reported if the write is refused.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(keyFor(batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Drops the oldest quarter of the store to free quota, counting the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n\n for (const key of keys.slice(0, Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR))) {\n const stored = this.read(key);\n this.removeKey(key);\n result.batches++;\n result.records += stored?.records.length ?? 0;\n }\n\n this.reportGap(result);\n }\n\n /**\n * Reports dropped records to diagnostics and registered gap handlers.\n * @param result Eviction metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `dropped ${String(result.batches)} stored batches (${String(result.records)} records)`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deserializes and validates a stored batch from a key.\n * @param key Storage key to read.\n * @returns Validated LogBatch or null if missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\"storage.unavailable\", \"reading a stored batch\", () =>\n localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"a stored batch was corrupt and was removed\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. Reporting again here would\n // count one corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\"storage.degraded\", \"a stored entry was not a batch and was dropped\");\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Resolves storage key containing the specified batch ID suffix.\n * @param id Batch identifier.\n * @returns Matching storage key string or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes an array of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes a single storage key with error guarding.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\"storage.degraded\", \"removing a stored batch\", () => {\n localStorage.removeItem(key);\n });\n }\n\n /**\n * Returns all sorted batch storage keys matching prefix.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(BATCH_STORAGE_KEY_PREFIX, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// In-memory fallback storage adapter for volatile batch retention during offline\n// periods. A reload loses everything here. Last resort adapter.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\n\n/**\n * Sums the total count of records contained across an array of batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\n\n/** In-memory StorageAdapter implementation retaining batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** Storage adapter strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** Internal array holding batches in chronological FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch to memory storage and applies retention pruning.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n this.batches.push(batch);\n await this.prune();\n }\n\n /**\n * Retrieves up to limit batches in chronological order without deletion.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise resolving to an array of batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Deletes a batch from memory storage by batch ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n /**\n * Updates delivery attempt count for a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches and evicts oldest entries exceeding capacity limits.\n * @returns Promise resolving to prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n result.batches += expired.length;\n result.records += countRecords(expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n result.reason = \"over_capacity\";\n const evicted = this.batches.slice(0, excess);\n this.batches = this.batches.slice(excess);\n result.batches += evicted.length;\n result.records += countRecords(evicted);\n }\n\n if (result.batches > 0) {\n this.onGap?.(result);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns total count of stored batches.\n * @returns Promise resolving to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Clears all stored batches from memory. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Clears stored batches on storage teardown. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Factory resolving storage adapters with graceful degradation from IndexedDB to localStorage to memory.\n// Degrades rather than throwing. IndexedDB is unavailable in private mode and\n// sandboxed frames.\n\nimport {\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * No-op storage adapter returned when persistence strategy is \"none\". Every method\n * resolves. A sender calling close() on shutdown must not crash.\n */\nconst noop: StorageAdapter = {\n name: STORAGE_NAME_NONE,\n save: () => Promise.resolve(),\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n};\n\n/**\n * Evaluates whether IndexedDB is accessible in the current execution context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\"storage.unavailable\", \"reading indexedDB\", () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n });\n\n return available === true;\n}\n\n/**\n * Tests whether localStorage is accessible and accepts write operations.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\"storage.unavailable\", \"probing localStorage\", () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n });\n\n return usable === true;\n}\n\n/**\n * Instantiates the requested storage adapter, degrading gracefully if dependencies are unavailable.\n * @param strategy Configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns Promise resolving to the selected StorageAdapter instance.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop;\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // Dynamically imports IndexedDbStorage to omit storage drivers from main\n // bundle. A chunk that fails to load degrades to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"opening IndexedDB\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Opened here, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB and then reject open(). Only a\n // rejection in this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB was asked for by name and is unavailable, using memory\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(limits, diagnostics, onGap);\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"no persistent storage available, offline logs are memory only\",\n );\n return new MemoryStorage(limits, onGap);\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches into Elastic Common Schema (ECS) formatted newline-delimited JSON.\n\nimport {\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record forwarded over\n * the bus has only passed a shape check, and BigInt throws a SyntaxError on a\n * non-numeric string, which loses the whole batch instead of one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input is not numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Value forms Elasticsearch maps under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value into its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, which loses the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads a\n * repeated leaf as one multi-valued field, which is how an array of objects maps.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map; a nested\n * object under it trips Elasticsearch dynamic mapping.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects, so a cycle cannot recurse forever.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can hold a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Removes the object on unwind, so a repeated sibling does not read as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Null prototype: an attribute named `__proto__` must become a key, not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/** Serializer formatting log records into Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes an array of log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n log: { level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase() },\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // Prefers request URL over ambient page URL for captured network events.\n url: {\n full: record.attributes[ATTR_URL_FULL] ?? record.attributes[ATTR_PAGE_URL],\n },\n // Attributes last: a record attribute overrides the resource key of the same name.\n labels: { ...toLabels(record.resource), ...toLabels(record.attributes) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp.ts\n//\n// Serializes log batches into OpenTelemetry (OTLP/JSON) formatted log records grouped by resource.\n\nimport {\n CONTENT_TYPE_JSON,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** OTLP AnyValue container with typed value wrappers. */\ntype AnyValue = Record<string, unknown>;\n\n/** OTLP KeyValue pair container. */\ninterface KeyValue {\n /** Attribute key. */\n key: string;\n /** Typed AnyValue container. */\n value: AnyValue;\n}\n\n/** Records grouped by shared resource attributes. */\ninterface ResourceGroup {\n /** Resource attribute map. */\n resource: Record<string, unknown>;\n /** Log records associated with the resource. */\n records: LogRecord[];\n}\n\n/**\n * Wraps a JavaScript value in an OTLP AnyValue container.\n * @param value Raw attribute or resource value.\n * @returns Typed AnyValue object or null if unsupported.\n */\nfunction toAnyValue(value: unknown): AnyValue | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return { stringValue: value };\n }\n\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n\n // Encodes int64 as decimal strings per OTLP protobuf JSON specification. A number\n // is a silent 400 from a conforming collector.\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n }\n\n // Converts BigInt to decimal string representation for JSON serialization.\n // JSON.stringify throws on a BigInt and loses the batch.\n if (typeof value === \"bigint\") {\n return { intValue: value.toString() };\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const values = items.map(toAnyValue).filter((item): item is AnyValue => item !== null);\n\n return { arrayValue: { values } };\n }\n\n if (typeof value === \"object\") {\n const nested = value as Record<string, unknown>;\n return { kvlistValue: { values: toKeyValues(nested) } };\n }\n\n return null;\n}\n\n/**\n * Converts a plain object into an array of OTLP KeyValue pairs.\n * @param source Key-value attribute object.\n * @returns Array of valid KeyValue pairs.\n */\nfunction toKeyValues(source: Record<string, unknown>): KeyValue[] {\n const out: KeyValue[] = [];\n\n for (const [key, raw] of Object.entries(source)) {\n const value = toAnyValue(raw);\n if (value) {\n out.push({ key, value });\n }\n }\n\n return out;\n}\n\n/** Memoized JSON string keys per resource object to avoid redundant stringification. */\nconst resourceKeys = new WeakMap<object, string>();\n\n/**\n * Computes or retrieves a stable serialization key for a resource object.\n * @param resource Resource attribute object.\n * @returns JSON key string.\n */\nfunction resourceKey(resource: Record<string, unknown>): string {\n const cached = resourceKeys.get(resource);\n if (cached !== undefined) {\n return cached;\n }\n\n const key = JSON.stringify(resource);\n resourceKeys.set(resource, key);\n\n return key;\n}\n\n/** Serializer formatting log records into OTLP/JSON payloads. */\nexport const otlpSerializer: LogSerializer = {\n /** Format identifier name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups records by resource and encodes them into an OTLP ExportLogsServiceRequest JSON payload.\n * @param records Array of log records to serialize.\n * @returns Serialized JSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const groups = new Map<string, ResourceGroup>();\n\n for (const record of records) {\n const key = resourceKey(record.resource);\n const group = groups.get(key);\n\n if (group) {\n group.records.push(record);\n continue;\n }\n\n groups.set(key, { resource: record.resource, records: [record] });\n }\n\n const resourceLogs = [...groups.values()].map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeLogs: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n logRecords: group.records.map((record) => ({\n timeUnixNano: record.timeUnixNano,\n // Falls back to timeUnixNano if observedTimeUnixNano is unset.\n observedTimeUnixNano: record.observedTimeUnixNano ?? record.timeUnixNano,\n severityNumber: record.severityNumber,\n severityText: record.severityText,\n body: { stringValue: record.body },\n traceId: record.traceId,\n spanId: record.spanId,\n flags: record.traceFlags,\n attributes: toKeyValues(record.attributes),\n })),\n },\n ],\n }));\n\n return {\n body: JSON.stringify({ resourceLogs }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this\n// module. config.ts keeps the name, so the main chunk holds no serializer.\n\nimport type { SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n","// src/transport/exit-flush.ts\n//\n// Synchronous exit-flush handler delivering buffered batches via sendBeacon, keepalive fetch, or emergency storage.\n// Runs during unload. Nothing awaits.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_CONTENT_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { serializerFor } from \"./serializers/select\";\n\n/** Document lifecycle event or manual action that triggered an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * The answer of the browser to a beacon. `refused` means the in-flight budget is\n * full. `unavailable` means the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** Structural interface for OpenFin window event subscription. */\ninterface FinMeLike {\n on?: (event: string, listener: () => void) => void;\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** Global environment extended with optional OpenFin runtime APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: { me?: FinMeLike } };\n\n/** Structural type for inspecting navigator.sendBeacon without restoring global DOM assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** Injected dependencies required by ExitFlush. */\nexport interface ExitFlushDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */\n drainForExit: () => LogBatch | null;\n /** Callback draining the buffered records only. An in-flight batch stays where it is. */\n drainPending: () => LogBatch | null;\n}\n\n/** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */\nexport class ExitFlush {\n /** Indicates whether unload listeners are currently active. */\n private installed = false;\n\n /** Handles visibilitychange events when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** Handles window pagehide events. */\n private readonly onPageHide = (): void => {\n this.flush(\"pagehide\");\n };\n\n /** Handles document freeze events. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** Handles OpenFin close-requested events. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** Attaches unload listeners across document, window, and OpenFin environments. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze target the document; pagehide targets window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"subscribing to close-requested\", () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /** Removes all registered unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n\n const me = (globalThis as OpenFinGlobal).fin?.me;\n this.deps.diagnostics.guard(\"openfin.unavailable\", \"releasing close-requested\", () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n });\n }\n\n /**\n * Synchronously drains pending records and transmits via beacon, keepalive, or\n * emergency storage. Never awaits and never throws. The caller is an unload\n * listener.\n * @param reason Trigger reason code.\n */\n flush(reason: ExitReason): void {\n const { diagnostics } = this.deps;\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n const batch = this.drain(reason);\n if (!batch || batch.records.length === 0) {\n return;\n }\n\n const serialized = diagnostics.guard(\n \"transport.serialize_failed\",\n `the ${reason} exit flush could not serialize its batch`,\n () => serializerFor(this.deps.config.serializer).serialize(batch.records),\n );\n if (!serialized) {\n return;\n }\n\n // Parks oversized payloads in synchronous localStorage queue. localStorage is\n // the only storage writable without awaiting.\n if (estimateBytes(serialized.body) > BEACON_LIMIT_BYTES) {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n // Passes batch ID and reason via query parameters. sendBeacon cannot set\n // headers.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n const outcome = this.beacon(target, serialized.body);\n if (outcome === \"sent\") {\n return;\n }\n\n // A refusal means the in-flight budget is full. A keepalive fetch uses the\n // same budget and fails the same way. The document closes, so nothing retries.\n if (outcome === \"refused\") {\n saveToEmergencyQueue(batch, diagnostics);\n return;\n }\n\n this.keepaliveFetch(target, serialized.body, reason);\n }\n\n /**\n * Selects the drain for the reason. `hidden` occurs at each tab switch, and the\n * document continues to run. Taken here, an in-flight batch goes out a second\n * time under a new id, which the server cannot deduplicate.\n * @param reason Trigger reason code.\n * @returns Combined LogBatch, or null if no records are pending.\n */\n private drain(reason: ExitReason): LogBatch | null {\n return reason === \"hidden\" ? this.deps.drainPending() : this.deps.drainForExit();\n }\n\n /**\n * Resolves and parses the destination endpoint URL.\n * @returns URL instance or null if missing or invalid.\n */\n private endpointUrl(): URL | null {\n const { endpoint } = this.deps.config;\n if (!endpoint) {\n return null;\n }\n\n const url = this.deps.diagnostics.guard(\n \"config.invalid\",\n `the exit flush cannot use endpoint ${endpoint}`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Attempts transmission via navigator.sendBeacon with text/plain payload.\n * @param url Target endpoint URL with query parameters.\n * @param body Serialized payload string.\n * @returns The answer of the browser.\n */\n private beacon(url: string, body: string): BeaconOutcome {\n const outcome = this.deps.diagnostics.guard<BeaconOutcome>(\n \"transport.http_error\",\n \"sendBeacon\",\n () => {\n // Invokes sendBeacon directly on navigator to preserve receiver context. A\n // detached sendBeacon throws on invocation.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Uses text/plain to avoid CORS preflights during document unload. A preflight\n // started during unload rarely completes, dropping the beacon silently.\n const accepted = nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n return accepted ? \"sent\" : \"refused\";\n },\n );\n\n // A throw is not a refusal: the method is present but unusable. The keepalive\n // fetch can still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Fallback POST delivery using fetch with keepalive: true. keepalive outlives the\n * document. A plain fetch is cancelled as the page goes.\n * @param url Target endpoint URL.\n * @param body Serialized payload string.\n * @param reason Trigger reason code.\n */\n private keepaliveFetch(url: string, body: string, reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n diagnostics.guard(\"transport.http_error\", \"the keepalive fetch fallback\", () => {\n void fetch(url, {\n method: \"POST\",\n body,\n headers: { [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n credentials: config.credentials,\n keepalive: true,\n }).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"the exit flush failed\", { reason }, error);\n });\n });\n }\n}\n","// src/transport/compression.ts\n//\n// Compresses payloads using the native CompressionStream API when available.\n// Returns null rather than raw text. A non-gzip body under Content-Encoding: gzip\n// is a 400 the server cannot explain.\n\nimport { ENCODING_GZIP } from \"../constants\";\n\n/**\n * Compresses a string into a gzip-encoded byte array using CompressionStream.\n * Returns non-shared ArrayBuffer backed Uint8Array compatible with fetch BodyInit.\n * @param text Raw serialized payload to compress.\n * @returns Promise resolving to compressed Uint8Array, or null if CompressionStream is unsupported.\n */\nexport async function gzip(text: string): Promise<Uint8Array<ArrayBuffer> | null> {\n const CS = (globalThis as { CompressionStream?: typeof CompressionStream }).CompressionStream;\n if (CS === undefined) {\n return null;\n }\n\n const stream = new Blob([text]).stream().pipeThrough(new CS(ENCODING_GZIP));\n const buffer = await new Response(stream).arrayBuffer();\n\n return new Uint8Array(buffer);\n}\n","// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses server Retry-After backoff headers.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * Failure classification determining retry, backoff, or drop behavior. transient,\n * offline and timeout retry with backoff. throttled waits the server's delay.\n * too_large splits the batch. permanent drops it: it will never be accepted.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** Error representing a failed transport attempt with failure classification and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n ) {\n super(message);\n this.name = \"TransportError\";\n }\n}\n\n/**\n * Parses HTTP Retry-After header value (seconds or HTTP date) into millisecond\n * delay. Both forms are legal. A date already past clamps to zero.\n * Clamps negative delays to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/http-transport.ts\n//\n// Serializes, compresses, and delivers log batches over HTTP with error\n// classification. Classifies, reports and throws. What happens to a rejected batch\n// belongs to the caller that owns storage.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_RETRY_AFTER,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n REQUEST_TIMEOUT_MS,\n RETRY_BASE_DELAY_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { serializerFor } from \"./serializers/select\";\n\n/** HTTP transport delivering serialized log batches with header resolution, gzip compression, and error classification. */\nexport class HttpTransport {\n /** Timestamp in epoch milliseconds until which requests are throttled. */\n private throttledUntil = 0;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Delivers a single log batch over HTTP.\n * @param batch Batch to send.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch): Promise<void> {\n const { endpoint } = this.config;\n\n if (!endpoint || batch.records.length === 0) {\n return;\n }\n\n await this.post(batch, endpoint);\n }\n\n /**\n * Returns the remaining throttle backoff duration in milliseconds.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(): number {\n return Math.max(0, this.throttledUntil - Date.now());\n }\n\n /**\n * Serializes, encodes, and dispatches a batch, throwing a classified TransportError on failure.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send cannot change it.\n */\n private async post(batch: LogBatch, endpoint: string): Promise<void> {\n const { config } = this;\n\n let serialized: SerializedBatch;\n try {\n serialized = serializerFor(config.serializer).serialize(batch.records);\n } catch (error) {\n this.diagnostics.report(\n \"transport.serialize_failed\",\n \"serializer threw, dropping the batch\",\n { batchId: batch.id },\n error,\n );\n return;\n }\n\n // Headers normalizes header names case-insensitively.\n const headers = new Headers(await this.resolveHeaders());\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n headers.set(HEADER_ATTEMPT, String(batch.attempts));\n\n const body = await this.encodeBody(serialized.body);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n const response = await this.dispatch(endpoint, headers, body);\n if (response.ok) {\n this.throttledUntil = 0;\n return;\n }\n\n throw await this.classify(response, batch.id);\n }\n\n /**\n * Compresses the serialized payload if gzip compression is enabled and size exceeds threshold.\n * @param text Serialized payload string.\n * @returns Promise resolving to original string or compressed byte array.\n */\n private async encodeBody(text: string): Promise<string | Uint8Array<ArrayBuffer>> {\n const { config } = this;\n if (config.compression !== ENCODING_GZIP || estimateBytes(text) < COMPRESSION_THRESHOLD_BYTES) {\n return text;\n }\n\n const compressed = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"gzipping the payload\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Executes the HTTP POST request with timeout and network error mapping.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @returns Promise resolving to the HTTP Response.\n * @throws TransportError on network failure, timeout, or offline status.\n */\n private async dispatch(\n endpoint: string,\n headers: Headers,\n body: string | Uint8Array<ArrayBuffer>,\n ): Promise<Response> {\n const { config } = this;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, REQUEST_TIMEOUT_MS);\n unrefTimer(timer);\n\n try {\n return await fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n });\n } catch {\n if (controller.signal.aborted) {\n const waited = String(REQUEST_TIMEOUT_MS);\n throw new TransportError(\"timeout\", `request exceeded ${waited}ms`);\n }\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n throw new TransportError(online === false ? \"offline\" : \"transient\", \"network error\");\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Classifies an HTTP error response into a structured TransportError.\n * @param response Unsuccessful HTTP response.\n * @param batchId Identifier of the rejected batch.\n * @returns Classified TransportError instance.\n */\n private async classify(response: Response, batchId: string): Promise<TransportError> {\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice =\n \"In a cross-origin iframe the session cookie is a third-party cookie and is very \" +\n \"likely blocked. Forward to the platform document instead of promoting to sender, \" +\n \"or issue the cookie with the Partitioned attribute.\";\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `server returned ${String(status)}. ${advice}`,\n { status, endpoint: this.config.endpoint },\n );\n // Permanent. Retrying a rejected credential forever blocks every batch behind\n // it.\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n const maxBytes = await this.readMaxBytes(response);\n return new TransportError(\"too_large\", \"payload too large\", status, undefined, maxBytes);\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n this.throttledUntil = Date.now() + (retryAfterMs ?? RETRY_BASE_DELAY_MS);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"server throttled us\", {\n retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"throttled\" : \"service unavailable\",\n status,\n retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `server error ${String(status)}`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `server rejected the batch with ${String(status)}, dropping it`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `rejected with ${String(status)}`, status);\n }\n\n /**\n * Extracts optional maxBytes payload limit from a 413 response body.\n * @param response HTTP 413 Response instance.\n * @returns Promise resolving to maximum byte limit or undefined.\n */\n private async readMaxBytes(response: Response): Promise<number | undefined> {\n return this.diagnostics.guardAsync(\"transport.http_error\", \"reading the 413 body\", async () => {\n const parsed = JSON.parse(await response.text()) as {\n maxBytes?: unknown;\n };\n return typeof parsed.maxBytes === \"number\" ? parsed.maxBytes : undefined;\n });\n }\n\n /**\n * Evaluates configured static or dynamic request headers.\n * @returns Promise resolving to resolved header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n const { headers } = this.config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const resolved = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"headers() threw\",\n () => Promise.resolve(headers()),\n );\n return resolved ?? {};\n }\n}\n","// src/transport/retry-engine.ts\n//\n// Scheduled background redelivery of stored log batches using jittered exponential\n// backoff. One timer, never a chain. Every scheduling path clears the pending\n// timer first.\n\nimport {\n BATCHES_PER_DRAIN,\n DRAIN_LOCK_NAME,\n RETRY_BASE_DELAY_MS,\n RETRY_IDLE_DELAY_MS,\n RETRY_MAX_DELAY_MS,\n STORAGE_DEADLINE_MS,\n STORAGE_LIMITS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { withDrainLock } from \"../utils/lock\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport type { HttpTransport } from \"./http-transport\";\n\n/** Manages timed redelivery of persisted offline batches with backoff, lock coordination, and batch splitting. */\nexport class RetryEngine {\n /** Active retry timer handle or null if unreserved. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Consecutive failed delivery attempts for exponential backoff calculation. */\n private attempt = 0;\n\n /** Indicates whether a storage drain operation is actively executing. */\n private draining = false;\n\n /** Indicates whether the engine is stopped. */\n private stopped = false;\n\n /** Online event listener resetting attempts and scheduling immediate drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: HttpTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n ) {}\n\n /** Starts the retry engine, listens for online events, and arms the initial timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n\n /** Triggers an accelerated retry schedule when a new batch is stored offline. */\n nudge(): void {\n if (!this.draining) {\n this.schedule(RETRY_BASE_DELAY_MS);\n }\n }\n\n /**\n * Persists a batch that failed outside the drain loop, under the same rules the\n * drain applies. Storing it whole would spend another request on a payload the\n * server already refused.\n * @param batch Rejected batch, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n\n if (parts.length > 0) {\n this.nudge();\n }\n }\n\n /** Halts retry execution, removes listeners, and clears pending timers. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Clears existing timers and schedules a new drain execution after a delay.\n * @param delayMs Delay duration in milliseconds.\n */\n private schedule(delayMs: number): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /**\n * Bounds a storage call. A call that does not settle keeps `draining` set, and\n * this window then runs no more drains.\n * @param work Storage promise to bound.\n * @returns The value of the promise, or a rejection after the deadline.\n */\n private bounded<T>(work: Promise<T>): Promise<T> {\n return withDeadline(work, STORAGE_DEADLINE_MS);\n }\n\n /** Clears the pending timer handle if active. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Computes jittered exponential backoff delay based on consecutive failures. Full\n * jitter, not a fixed offset. Tabs reconnecting together stampede otherwise.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(RETRY_BASE_DELAY_MS * 2 ** this.attempt, RETRY_MAX_DELAY_MS);\n\n return Math.random() * exponential;\n }\n\n /** Executes a drain operation protected by the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const ran = await withDrainLock(DRAIN_LOCK_NAME, this.diagnostics, () => this.drainLocked());\n\n // undefined means the lock was held elsewhere. Without the reschedule, one\n // lost race retires this window.\n if (ran !== true) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while holding the Web Lock and schedules subsequent ticks.\n * Always resolves. A throw leaves the engine idle with no timer armed.\n * @returns Promise resolving to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n const online = (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine;\n if (online === false) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n const batches = await this.bounded(this.storage.take(this.batchesPerDrain));\n\n if (batches.length === 0) {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return true;\n }\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const done = await this.deliver(batch);\n if (!done) {\n return true;\n }\n }\n\n this.schedule(batches.length === this.batchesPerDrain ? 0 : RETRY_IDLE_DELAY_MS);\n return true;\n } catch (error) {\n this.diagnostics.report(\"storage.degraded\", \"the drain loop threw\", undefined, error);\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Attempts delivery of a single batch, removing it on success or handling errors.\n * @param batch Log batch to deliver.\n * @returns True to continue processing next batch; false to halt current drain.\n */\n private async deliver(batch: LogBatch): Promise<boolean> {\n if (batch.attempts >= STORAGE_LIMITS.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `giving up on a batch after ${batch.attempts.toString()} attempts`,\n { batchId: batch.id, records: batch.records.length },\n );\n await this.bounded(this.storage.remove(batch.id));\n return true;\n }\n\n try {\n await this.transport.send(batch);\n await this.bounded(this.storage.remove(batch.id));\n this.attempt = 0;\n return true;\n } catch (error) {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\" || failure?.kind === \"too_large\") {\n await this.replaceStored(batch, error);\n return true;\n }\n\n if (failure?.kind === \"offline\") {\n this.schedule(RETRY_IDLE_DELAY_MS);\n return false;\n }\n\n // A throttle rejects no records: the server asks for the batch later. An\n // attempt counted here dead-letters the batch after five throttled answers.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n this.schedule(failure.retryAfterMs ?? this.backoffMs());\n return false;\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n this.schedule(failure?.retryAfterMs ?? this.backoffMs());\n return false;\n }\n }\n\n /**\n * Replaces a stored batch with what survives its failure: the split halves, or\n * nothing when the server refuses the records for good.\n * @param batch Rejected log batch, already held in storage.\n * @param error Failure thrown by the transport.\n */\n private async replaceStored(batch: LogBatch, error: unknown): Promise<void> {\n const parts = this.toStorable(batch, error);\n await this.bounded(this.storage.remove(batch.id));\n\n for (const part of parts) {\n await this.bounded(this.storage.save(part));\n }\n }\n\n /**\n * Decides what a failed batch leaves behind. A 413 splits in two, a permanent\n * refusal keeps nothing, and every other failure keeps the batch whole.\n * @param batch Rejected log batch.\n * @param error Failure thrown by the transport.\n * @returns Batches to persist, empty when the records are dropped.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n return [];\n }\n\n if (failure?.kind !== \"too_large\") {\n return [batch];\n }\n\n const halves = splitBatch(batch);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"a single record exceeds the server limit and was dropped\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n return [];\n }\n\n this.diagnostics.report(\"transport.batch_split\", \"the server refused the batch as too large\", {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes: failure.maxBytes,\n });\n\n return halves;\n }\n}\n","// src/core/pipeline.ts\n//\n// Stream buffering, batch formation, and delivery for logs and metrics.\n//\n// Each stream owns its buffer and its own flush timer, so the exit flush can\n// take every record that has not reached the transport yet.\n\nimport {\n ATTR_LOG_TYPE,\n LOG_BATCH_SIZE,\n LOG_FLUSH_INTERVAL_MS,\n LOG_TYPE_METRIC,\n MAX_CONCURRENT_REQUESTS,\n METRIC_BATCH_SIZE,\n METRIC_FLUSH_INTERVAL_MS,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport { type LogRecord, nowUnixNano } from \"../models/log-record\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport type { HttpTransport } from \"../transport/http-transport\";\nimport type { RetryEngine } from \"../transport/retry-engine\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { ErrorCeiling } from \"./sampling\";\n\n/** Pipeline stream classification for logs versus metrics. */\nexport type StreamName = \"logs\" | \"metrics\";\n\n/**\n * Evaluates whether a log record is classified as a metric.\n * @param record Record to evaluate.\n * @returns True if the record log type attribute equals metric.\n */\nfunction isMetric(record: LogRecord): boolean {\n return record.attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC;\n}\n\n/** Batching policy for one record stream. */\nexport interface StreamOptions {\n /** Max time a partial batch waits before it is sent, in milliseconds. */\n flushIntervalMs: number;\n /** Max records per batch before it is sent early. */\n batchSize: number;\n}\n\n/** Batching policy per stream. Metrics batch harder: higher volume, nothing waits on them. */\nexport const STREAM_OPTIONS: Record<StreamName, StreamOptions> = {\n logs: { flushIntervalMs: LOG_FLUSH_INTERVAL_MS, batchSize: LOG_BATCH_SIZE },\n metrics: { flushIntervalMs: METRIC_FLUSH_INTERVAL_MS, batchSize: METRIC_BATCH_SIZE },\n};\n\n/** One stream's pending records and the timer that closes a partial batch. */\nclass RecordStream {\n /** Pending records waiting in chronological order. */\n private pending: LogRecord[] = [];\n\n /** Handle of the armed flush timer, or null when none is pending. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Batching policy for this stream.\n * @param onFlush Called with this stream when a batch is ready to close.\n */\n constructor(\n readonly options: StreamOptions,\n private readonly onFlush: (stream: RecordStream) => void,\n ) {}\n\n /**\n * Buffers a record, closing the batch at once on the batchSize-th and arming\n * the interval timer on the first. Without the timer a batch below batchSize\n * waits for the next record, which on a quiet page never comes.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n this.pending.push(record);\n\n if (this.pending.length >= this.options.batchSize) {\n this.onFlush(this);\n return;\n }\n\n this.arm();\n }\n\n /**\n * Drains and returns all buffered records, disarming the flush timer.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n this.clearTimer();\n\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n\n /** Disarms the flush timer, leaving buffered records in place. */\n stop(): void {\n this.clearTimer();\n }\n\n /** Arms the flush timer unless one is already pending. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n this.onFlush(this);\n }, this.options.flushIntervalMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /** Clears the pending timer handle if armed. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n\n/** Pipeline orchestrating log and metric stream buffering, batch creation, and HTTP dispatch. */\nexport class LogPipeline {\n /** Buffer instances for logs and metrics streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** Unconfirmed in-flight batches tracked for exit flush recovery. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: LogBatch[] = [];\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Dispatches currently in flight, capped at MAX_CONCURRENT_REQUESTS. */\n private inFlight = 0;\n\n /** Indicates a pump is already queued, so one microtask drains a burst. */\n private pumpScheduled = false;\n\n /** Indicates whether the pipeline has been destroyed. */\n private stopped = false;\n\n /**\n * @param transport HTTP transport for live batch delivery.\n * @param storage Storage adapter for offline batch persistence.\n * @param retry Retry engine for redelivering persisted batches.\n * @param diagnostics Diagnostics reporter.\n * @param streamOptions Batching policy per stream.\n */\n constructor(\n private readonly transport: HttpTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n streamOptions: Record<StreamName, StreamOptions> = STREAM_OPTIONS,\n ) {\n const flush = (stream: RecordStream): void => {\n this.claim(stream);\n };\n\n this.streams = {\n logs: new RecordStream(streamOptions.logs, flush),\n metrics: new RecordStream(streamOptions.metrics, flush),\n };\n }\n\n /**\n * Stamps observed timestamp and enqueues a record into the pipeline.\n * @param record Record to push.\n */\n push(record: LogRecord): void {\n if (this.stopped) {\n return;\n }\n\n record.observedTimeUnixNano = nowUnixNano();\n this.route(record);\n }\n\n /**\n * Drains the stream buffers into one batch. In-flight batches stay where they\n * are. They carry their own ids and are still on their way, so taking them here\n * resends every record under an id the server cannot deduplicate against.\n * @returns Combined LogBatch or null if no records are buffered.\n */\n drainPending(): LogBatch | null {\n return this.toBatch([...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /**\n * Atomically drains all buffered and unconfirmed in-flight records into a single\n * exit batch. Records already handed to fetch go out again under a new batch id,\n * so the server cannot deduplicate them and the exit flush can deliver duplicates.\n * A document being closed cannot confirm delivery, so this is by design.\n * @returns Combined LogBatch or null if no records are pending.\n */\n drainForExit(): LogBatch | null {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n\n return this.toBatch([...inFlight, ...this.streams.metrics.take(), ...this.streams.logs.take()]);\n }\n\n /** Stops the flush timers and refuses further records. */\n destroy(): void {\n this.stopped = true;\n this.streams.logs.stop();\n this.streams.metrics.stop();\n this.queue.length = 0;\n }\n\n /**\n * Wraps drained records in a batch.\n * @param records Records taken from the buffers, in delivery order.\n * @returns New LogBatch, or null when nothing was drained.\n */\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return { id: newId(), records, createdAt: Date.now(), attempts: 0 };\n }\n\n /**\n * Sorts a record into its stream. Sampling already ran, in RecordBuilder for a\n * local record and in the runtime for a forwarded one. Every fault is contained\n * here: a record carrying no `attributes` makes isMetric throw, and a throw\n * escaping this method would surface inside the caller's own log call.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const stream = isMetric(record) ? this.streams.metrics : this.streams.logs;\n\n // ERROR and FATAL bypass sampling upstream, so this is the only limit\n // on them.\n if (!this.ceiling.allow(record)) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n\n stream.add(record);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"a record was dropped on its way into a stream\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Drains a stream buffer into a new batch and queues it for dispatch. The\n * buffer always holds at least one record here: a timer is armed only by a\n * push, and every `take` disarms the timer that would have called this.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n const records = stream.take();\n\n const batch: LogBatch = {\n id: newId(),\n records,\n createdAt: Date.now(),\n attempts: 0,\n };\n this.unconfirmed.set(batch.id, batch);\n this.enqueue(batch);\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. Dispatching inline\n * would start a fetch inside the application's own log call.\n * @param batch Batch ready for delivery.\n */\n private enqueue(batch: LogBatch): void {\n this.queue.push(batch);\n\n if (this.pumpScheduled) {\n return;\n }\n\n this.pumpScheduled = true;\n queueMicrotask(() => {\n this.pumpScheduled = false;\n this.pump();\n });\n }\n\n /** Starts queued dispatches up to the concurrency limit. */\n private pump(): void {\n while (this.inFlight < MAX_CONCURRENT_REQUESTS) {\n const batch = this.queue.shift();\n if (!batch) {\n return;\n }\n\n this.inFlight++;\n void this.run(batch);\n }\n }\n\n /**\n * Delivers one batch and frees its concurrency slot.\n * @param batch Batch to deliver.\n */\n private async run(batch: LogBatch): Promise<void> {\n try {\n await this.dispatch(batch);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"dispatch rejected, which it is written never to do\",\n { batchId: batch.id },\n error,\n );\n } finally {\n this.inFlight--;\n this.pump();\n }\n }\n\n /**\n * Sends a batch over HTTP transport or persists it to offline storage if throttled or failed.\n * @param batch Batch to deliver.\n */\n private async dispatch(batch: LogBatch): Promise<void> {\n try {\n // Persists directly to storage while transport is throttled. Sending here\n // posts a batch every flush interval straight through the throttle.\n // Attempt count unchanged: nothing was sent.\n const throttledMs = this.transport.throttledForMs();\n if (throttledMs > 0) {\n await this.store(batch);\n this.diagnostics.report(\"transport.throttled\", \"stored the batch rather than sending it\", {\n batchId: batch.id,\n records: batch.records.length,\n throttledMs,\n });\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n // Increments attempt count before storing failed live send. Stored at 0,\n // the batch exceeds STORAGE_LIMITS.maxAttempts by one and attempt headers\n // under-report.\n await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n \"batch was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n }\n }\n\n /**\n * Persists a batch the transport refused, letting the retry engine split a 413\n * and drop what the server will never accept.\n * @param batch Batch to persist, with its attempt already counted.\n * @param error Failure thrown by the transport.\n */\n private async storeFailed(batch: LogBatch, error: unknown): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting an undelivered batch\",\n async () => {\n await this.retry.storeFailed(batch, error);\n },\n );\n }\n\n /**\n * Persists an undelivered batch to storage and triggers retry engine. Bounded:\n * a storage call that does not settle holds this dispatch slot. Two of them\n * stop the pipeline.\n * @param batch Batch to persist.\n */\n private async store(batch: LogBatch): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting an undelivered batch\",\n async () => {\n await withDeadline(this.storage.save(batch), STORAGE_DEADLINE_MS);\n this.retry.nudge();\n },\n );\n }\n}\n","// src/core/sender.ts\n//\n// Delivery stack of the sender role: storage, transport, retry, pipeline and exit flush.\n// The runtime imports this module dynamically, and only when an endpoint is set.\n// Console-only mode does not download it.\n\nimport { STORAGE_DB_NAME, STORAGE_LIMITS } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { GapReporter, StorageAdapter } from \"../models/storage\";\nimport { drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage } from \"../storage/factory\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { LogPipeline } from \"./pipeline\";\n\n/** Inputs to build the delivery stack. */\nexport interface SenderDeps {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Receives a report when storage drops batches before delivery. */\n onGap: GapReporter;\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /**\n * @param storage Storage adapter for undelivered batches.\n * @param transport HTTP transport for live delivery.\n * @param retry Retry engine for stored batches.\n * @param pipeline Pipeline that batches records.\n * @param exitFlush Handler that sends pending records on unload.\n * @param diagnostics Diagnostics reporter.\n */\n private constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: HttpTransport,\n private readonly retry: RetryEngine,\n private readonly pipeline: LogPipeline,\n private readonly exitFlush: ExitFlush,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Builds the delivery stack, drains the emergency queue and starts the retry loop.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise resolving to the started sender.\n */\n static async create(deps: SenderDeps): Promise<Sender> {\n const { config, diagnostics } = deps;\n\n const storage = await createStorage(\n config.storage,\n STORAGE_DB_NAME,\n STORAGE_LIMITS,\n diagnostics,\n deps.onGap,\n );\n const transport = new HttpTransport(config, diagnostics);\n const retry = new RetryEngine(storage, transport, diagnostics, config);\n const pipeline = new LogPipeline(transport, storage, retry, diagnostics);\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n drainPending: () => pipeline.drainPending(),\n });\n\n await drainEmergencyQueue(storage, diagnostics);\n\n // Stop both if one fails. A retry loop with no owner sends after the load reports a failure.\n let started = false;\n\n try {\n exitFlush.install();\n retry.start();\n started = true;\n } finally {\n if (!started) {\n exitFlush.uninstall();\n retry.stop();\n }\n }\n\n return new Sender(storage, transport, retry, pipeline, exitFlush, diagnostics);\n }\n\n /**\n * Adds a record to the pipeline.\n * @param record Record to deliver.\n */\n push(record: LogRecord): void {\n this.pipeline.push(record);\n }\n\n /**\n * Sends the records held in the stream buffers.\n * @returns Promise resolving when the batch is sent or stored for retry.\n */\n async flush(): Promise<void> {\n const batch = this.pipeline.drainPending();\n\n if (!batch) {\n return;\n }\n\n try {\n await this.transport.send(batch);\n } catch (error) {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"persisting the batch drained by flush()\",\n // The retry engine classifies the failure. A 413 splits the batch here, as in the drain.\n async () => {\n await this.retry.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n },\n );\n this.diagnostics.report(\n \"transport.http_error\",\n \"the batch drained by flush() was stored for retry instead of being delivered\",\n { batchId: batch.id, records: batch.records.length },\n error,\n );\n }\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise resolving to the batch count, or 0 if storage fails.\n */\n async queueDepth(): Promise<number> {\n const count = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"counting the batches waiting in storage\",\n () => this.storage.count(),\n );\n\n return count ?? 0;\n }\n\n /**\n * Sends pending records, stops every timer and listener, then closes storage.\n * The synchronous steps run before the first await. The runtime relies on this order.\n * @returns Promise resolving when storage is closed.\n */\n async destroy(): Promise<void> {\n this.exitFlush.flush(\"shutdown\");\n this.exitFlush.uninstall();\n this.retry.stop();\n this.pipeline.destroy();\n\n await this.storage.close();\n }\n}\n"],"mappings":"mHA8BA,SAAgB2D,EAAW,EAAmC,CAC5D,GAAI,OAAOC,GAAU,WAAYA,EAC/B,MAAO,GAGT,IAAMC,EAAc,QAAQ,IAAID,EAAO,IAAI,EACrCE,EAAqB,QAAQ,IAAIF,EAAO,WAAW,EACnDG,EAAoB,QAAQ,IAAIH,EAAO,UAAU,EACjDI,EAAmB,QAAQ,IAAIJ,EAAO,SAAS,EAErD,OACE,OAAOC,GAAO,UACd,OAAOC,GAAc,UACrB,OAAOC,GAAa,UACpB,MAAM,QAAQC,CAAO,CAEzB,CAQA,SAAgBC,EAAW,EAA8C,CACvE,GAAIC,EAAM,QAAQ,OAAS,EACzB,OAAO,KAGT,IAAMC,EAAS,KAAK,MAAMD,EAAM,QAAQ,OAAS,CAAC,EAC5CE,EAA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KAAK,EAEf,CAEA,OAAO,IAAIK,EAAOtH,EAASkG,EAAWe,EAAOM,EAAUC,EAAWzI,CAAW,CAC/E,CAMA,KAAK,EAAyB,CAC5B,KAAK,SAAS,KAAKmE,CAAM,CAC3B,CAMA,MAAM,OAAuB,CAC3B,IAAMxE,EAAQ,KAAK,SAAS,aAAa,EAEzC,GAAKA,EAIL,GAAI,CACF,MAAM,KAAK,UAAU,KAAKA,CAAK,CACjC,OAASuB,EAAO,CACd,MAAM,KAAK,YAAY,WACrB,mBACA,0CAEA,SAAY,CACV,MAAM,KAAK,MAAM,YAAY,CAAE,GAAGvB,EAAO,SAAUA,EAAM,SAAW,CAAE,EAAGuB,CAAK,CAChF,CACF,EACA,KAAK,YAAY,OACf,uBACA,+EACA,CAAE,QAASvB,EAAM,GAAI,QAASA,EAAM,QAAQ,MAAO,EACnDuB,CACF,CACF,CACF,CAMA,MAAM,YAA8B,CAOlC,OAAO,MANa,KAAK,YAAY,WACnC,mBACA,8CACM,KAAK,QAAQ,MAAM,CAC3B,GAEgB,CAClB,CAOA,MAAM,SAAyB,CAC7B,KAAK,UAAU,MAAM,UAAU,EAC/B,KAAK,UAAU,UAAU,EACzB,KAAK,MAAM,KAAK,EAChB,KAAK,SAAS,QAAQ,EAEtB,MAAM,KAAK,QAAQ,MAAM,CAC3B,CACF"}
@@ -39,6 +39,8 @@ export declare class IdbDriver {
39
39
  /**
40
40
  * Rewrites the attempt count of a stored batch. An id that is not stored is
41
41
  * left alone: a batch already delivered and deleted must not be resurrected.
42
+ * One transaction for the get and the put. Across two transactions, a prune in
43
+ * another window deletes the batch between them, and the put restores it.
42
44
  * @param id Batch identifier.
43
45
  * @param attempts New absolute attempt count.
44
46
  */
@@ -50,6 +52,11 @@ export declare class IdbDriver {
50
52
  count(): Promise<number>;
51
53
  /** Deletes every stored batch. */
52
54
  clear(): Promise<void>;
55
+ /**
56
+ * Opens the connection. A host that defines indexedDB but rejects open() fails
57
+ * here, where the factory can select a different adapter.
58
+ */
59
+ ready(): Promise<void>;
53
60
  /** Closes the connection, if one was ever opened. */
54
61
  close(): Promise<void>;
55
62
  /**
@@ -60,7 +67,8 @@ export declare class IdbDriver {
60
67
  */
61
68
  private store;
62
69
  /**
63
- * Opens the database once and hands the same connection to every later call.
70
+ * Opens the database one time and gives the same connection to each later call.
71
+ * A failed open is not kept: the next call opens again.
64
72
  * @returns The open database.
65
73
  */
66
74
  private open;
@@ -17,6 +17,11 @@ export declare class IndexedDbStorage implements StorageAdapter {
17
17
  * @param onGap Optional callback for dropped record reporting.
18
18
  */
19
19
  constructor(dbName: string, limits: StorageLimits, diagnostics: Diagnostics, onGap?: GapReporter | undefined);
20
+ /**
21
+ * Opens the database. Not guarded: the factory needs the rejection to select the
22
+ * next adapter.
23
+ */
24
+ open(): Promise<void>;
20
25
  /**
21
26
  * Persists a batch to IndexedDB and triggers storage pruning.
22
27
  * @param batch Batch to store.
@@ -11,6 +11,8 @@ export interface ExitFlushDeps {
11
11
  diagnostics: Diagnostics;
12
12
  /** Callback draining all pending buffered and unconfirmed batches into a single LogBatch. */
13
13
  drainForExit: () => LogBatch | null;
14
+ /** Callback draining the buffered records only. An in-flight batch stays where it is. */
15
+ drainPending: () => LogBatch | null;
14
16
  }
15
17
  /** Flushes pending telemetry on document unload using sendBeacon, keepalive fetch, or emergency storage. */
16
18
  export declare class ExitFlush {
@@ -40,6 +42,14 @@ export declare class ExitFlush {
40
42
  * @param reason Trigger reason code.
41
43
  */
42
44
  flush(reason: ExitReason): void;
45
+ /**
46
+ * Selects the drain for the reason. `hidden` occurs at each tab switch, and the
47
+ * document continues to run. Taken here, an in-flight batch goes out a second
48
+ * time under a new id, which the server cannot deduplicate.
49
+ * @param reason Trigger reason code.
50
+ * @returns Combined LogBatch, or null if no records are pending.
51
+ */
52
+ private drain;
43
53
  /**
44
54
  * Resolves and parses the destination endpoint URL.
45
55
  * @returns URL instance or null if missing or invalid.
@@ -49,7 +59,7 @@ export declare class ExitFlush {
49
59
  * Attempts transmission via navigator.sendBeacon with text/plain payload.
50
60
  * @param url Target endpoint URL with query parameters.
51
61
  * @param body Serialized payload string.
52
- * @returns True if the beacon was accepted by the browser.
62
+ * @returns The answer of the browser.
53
63
  */
54
64
  private beacon;
55
65
  /**
@@ -26,6 +26,7 @@ export declare class HttpTransport {
26
26
  /**
27
27
  * Serializes, encodes, and dispatches a batch, throwing a classified TransportError on failure.
28
28
  * @param batch Batch to deliver.
29
+ * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send cannot change it.
29
30
  */
30
31
  private post;
31
32
  /**
@@ -36,6 +37,7 @@ export declare class HttpTransport {
36
37
  private encodeBody;
37
38
  /**
38
39
  * Executes the HTTP POST request with timeout and network error mapping.
40
+ * @param endpoint Ingest URL.
39
41
  * @param headers HTTP request headers.
40
42
  * @param body Request body string or byte array.
41
43
  * @returns Promise resolving to the HTTP Response.
@@ -1,4 +1,5 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
+ import { type LogBatch } from "../models/batch";
2
3
  import type { ResolvedConfig } from "../models/config";
3
4
  import type { StorageAdapter } from "../models/storage";
4
5
  import type { HttpTransport } from "./http-transport";
@@ -31,6 +32,14 @@ export declare class RetryEngine {
31
32
  start(): void;
32
33
  /** Triggers an accelerated retry schedule when a new batch is stored offline. */
33
34
  nudge(): void;
35
+ /**
36
+ * Persists a batch that failed outside the drain loop, under the same rules the
37
+ * drain applies. Storing it whole would spend another request on a payload the
38
+ * server already refused.
39
+ * @param batch Rejected batch, with its attempt already counted.
40
+ * @param error Failure thrown by the transport.
41
+ */
42
+ storeFailed(batch: LogBatch, error: unknown): Promise<void>;
34
43
  /** Halts retry execution, removes listeners, and clears pending timers. */
35
44
  stop(): void;
36
45
  /**
@@ -38,6 +47,13 @@ export declare class RetryEngine {
38
47
  * @param delayMs Delay duration in milliseconds.
39
48
  */
40
49
  private schedule;
50
+ /**
51
+ * Bounds a storage call. A call that does not settle keeps `draining` set, and
52
+ * this window then runs no more drains.
53
+ * @param work Storage promise to bound.
54
+ * @returns The value of the promise, or a rejection after the deadline.
55
+ */
56
+ private bounded;
41
57
  /** Clears the pending timer handle if active. */
42
58
  private clearTimer;
43
59
  /**
@@ -61,9 +77,18 @@ export declare class RetryEngine {
61
77
  */
62
78
  private deliver;
63
79
  /**
64
- * Splits an oversized batch into two smaller stored batches after a 413 rejection.
80
+ * Replaces a stored batch with what survives its failure: the split halves, or
81
+ * nothing when the server refuses the records for good.
82
+ * @param batch Rejected log batch, already held in storage.
83
+ * @param error Failure thrown by the transport.
84
+ */
85
+ private replaceStored;
86
+ /**
87
+ * Decides what a failed batch leaves behind. A 413 splits in two, a permanent
88
+ * refusal keeps nothing, and every other failure keeps the batch whole.
65
89
  * @param batch Rejected log batch.
66
- * @param serverMaxBytes Optional byte limit reported by the server.
90
+ * @param error Failure thrown by the transport.
91
+ * @returns Batches to persist, empty when the records are dropped.
67
92
  */
68
- private splitStored;
93
+ private toStorable;
69
94
  }
@@ -0,0 +1,8 @@
1
+ import type { SerializerChoice } from "../../models/config";
2
+ import type { LogSerializer } from "../../models/serializer";
3
+ /**
4
+ * Returns the implementation for a resolved serializer option.
5
+ * @param choice Serializer name, or a custom implementation.
6
+ * @returns Serializer implementation.
7
+ */
8
+ export declare function serializerFor(choice: SerializerChoice): LogSerializer;
@@ -0,0 +1,8 @@
1
+ //#region src/utils/unref.ts
2
+ function e(e) {
3
+ typeof e != "number" && e.unref?.();
4
+ }
5
+ //#endregion
6
+ export { e as t };
7
+
8
+ //# sourceMappingURL=unref-16maCyKA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unref-16maCyKA.js","names":["unrefTimer","timer"],"sources":["../src/utils/unref.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Utility for safely unreferencing timer handles across Node and browser\n// environments. A pending timer keeps a Node process alive under SSR and in\n// tests.\n\n/** Cross-platform timer handle representing browser numeric IDs or Node Timeout objects. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle to prevent it from keeping a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n"],"mappings":";AAaA,SAAgBA,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB"}
@@ -0,0 +1,2 @@
1
+ function e(e){typeof e!=`number`&&e.unref?.()}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=unref-CU9Nyz_9.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unref-CU9Nyz_9.cjs","names":["unrefTimer","timer"],"sources":["../src/utils/unref.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Utility for safely unreferencing timer handles across Node and browser\n// environments. A pending timer keeps a Node process alive under SSR and in\n// tests.\n\n/** Cross-platform timer handle representing browser numeric IDs or Node Timeout objects. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle to prevent it from keeping a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n"],"mappings":"AAaA,SAAgBA,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB"}
@@ -15,10 +15,18 @@ export declare class ConsoleSink {
15
15
  */
16
16
  update(minLevel: LogLevel | null): void;
17
17
  /**
18
- * Emits a styled log record to the console if severity clears the configured threshold.
18
+ * Tests whether a level clears the console threshold.
19
+ * @param level Severity level of the record.
20
+ * @returns True if the sink prints this level.
21
+ */
22
+ accepts(level: LogLevel): boolean;
23
+ /**
24
+ * Prints a styled log line if the level clears the console threshold.
25
+ * @param namespace Logger namespace, shown in the prefix.
19
26
  * @param level Severity level of the record.
20
27
  * @param message Primary log message.
21
- * @param payload Optional contextual payload or object reference.
28
+ * @param payload Caller payload. The sink prints a sanitized copy.
29
+ * @param error Error to print before the payload.
22
30
  */
23
- write(level: LogLevel, message: string, payload?: unknown): void;
31
+ write(namespace: string, level: LogLevel, message: string, payload?: Record<string, unknown>, error?: Error): void;
24
32
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Rejects when a promise does not settle within a deadline.
3
+ * @param work Promise to bound.
4
+ * @param ms Deadline in milliseconds.
5
+ * @returns The value of the promise, or a rejection after the deadline.
6
+ */
7
+ export declare function withDeadline<T>(work: Promise<T>, ms: number): Promise<T>;
@@ -8,6 +8,40 @@ export interface Identity {
8
8
  /** Unique execution realm identifier regenerated on every document load. */
9
9
  contextId: string;
10
10
  }
11
+ /** The three Storage methods that identity and journey code use. */
12
+ export interface KeyValueStore {
13
+ /**
14
+ * Reads one value.
15
+ * @param key Storage key.
16
+ * @returns Stored value, or null.
17
+ */
18
+ getItem(key: string): string | null;
19
+ /**
20
+ * Writes one value.
21
+ * @param key Storage key.
22
+ * @param value Value to write.
23
+ */
24
+ setItem(key: string, value: string): void;
25
+ /**
26
+ * Removes one value.
27
+ * @param key Storage key.
28
+ */
29
+ removeItem(key: string): void;
30
+ }
31
+ /** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */
32
+ export interface IdentityStores {
33
+ /** Store that lasts across tabs and reloads. */
34
+ local(): KeyValueStore;
35
+ /** Store that lasts for one tab. */
36
+ session(): KeyValueStore;
37
+ }
38
+ /** Stores that write to the browser. The `identity: "storage"` option uses them. */
39
+ export declare const BROWSER_STORES: IdentityStores;
40
+ /**
41
+ * Creates stores that keep values in memory only. The `identity: "memory"` option uses them.
42
+ * @returns Stores that write nothing to the browser.
43
+ */
44
+ export declare function memoryStores(): IdentityStores;
11
45
  /**
12
46
  * Generates a random lowercase hexadecimal string of the specified byte length.
13
47
  * Uses crypto.getRandomValues when available, falling back to Math.random.
@@ -23,9 +57,17 @@ export declare function newId(): string;
23
57
  /**
24
58
  * Resolves or initializes session, tab, and context identifiers for the active realm.
25
59
  * @param diagnostics Diagnostics reporter.
60
+ * @param stores Identity stores.
26
61
  * @returns Populated Identity object.
27
62
  */
28
- export declare function resolveIdentity(diagnostics: Diagnostics): Identity;
63
+ export declare function resolveIdentity(diagnostics: Diagnostics, stores?: IdentityStores): Identity;
64
+ /**
65
+ * Writes a new tab id to the session store.
66
+ * @param tabId New tab identifier.
67
+ * @param diagnostics Diagnostics reporter.
68
+ * @param stores Identity stores.
69
+ */
70
+ export declare function persistTabId(tabId: string, diagnostics: Diagnostics, stores: IdentityStores): void;
29
71
  /**
30
72
  * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.
31
73
  * The throttle is instance state, not module state: two runtimes in one document
@@ -33,14 +75,16 @@ export declare function resolveIdentity(diagnostics: Diagnostics): Identity;
33
75
  */
34
76
  export declare class SessionTouch {
35
77
  private diagnostics;
78
+ private readonly stores;
36
79
  /** Epoch milliseconds of the last write this instance made. */
37
80
  private lastTouchAt;
38
81
  /**
39
82
  * @param diagnostics Diagnostics reporter.
83
+ * @param stores Identity stores.
40
84
  */
41
- constructor(diagnostics: Diagnostics);
85
+ constructor(diagnostics: Diagnostics, stores?: IdentityStores);
42
86
  /**
43
- * Updates the session activity timestamp in localStorage, at most once per window.
87
+ * Writes the session activity time to the local store. It writes one time in each throttle window.
44
88
  * @param sessionId Active session identifier.
45
89
  */
46
90
  touch(sessionId: string): void;
@@ -27,7 +27,7 @@ export declare function newSpanId(): string;
27
27
  export declare class TraceEngine {
28
28
  private readonly diagnostics;
29
29
  private readonly maxAgeMs;
30
- private readonly load;
30
+ private readonly load?;
31
31
  /**
32
32
  * Active ambient trace context. Instance state, never module state. Two runtimes
33
33
  * in one document must not share a trace id.
@@ -38,12 +38,13 @@ export declare class TraceEngine {
38
38
  /**
39
39
  * @param diagnostics Diagnostics reporter.
40
40
  * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.
41
- * @param load Supplies the OpenTelemetry API.
41
+ * @param load Loader for the OpenTelemetry API. If it is not set, OTel is off.
42
+ * Do not import the peer by name. The Vite dev server fails if the peer is not installed.
42
43
  */
43
- constructor(diagnostics: Diagnostics, maxAgeMs?: number, load?: OtelLoader);
44
+ constructor(diagnostics: Diagnostics, maxAgeMs?: number, load?: OtelLoader | undefined);
44
45
  /**
45
- * Loads the OpenTelemetry API. Records built before this resolves, and every
46
- * record when the package is absent, carry the ambient trace instead.
46
+ * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.
47
+ * If there is no loader or the load fails, all records use the ambient trace.
47
48
  * @returns Promise resolving once the attempt has settled.
48
49
  */
49
50
  loadOtel(): Promise<void>;