@utk09/ui-observability 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +77 -60
  3. package/dist/bus/bus.d.ts +10 -10
  4. package/dist/bus/links.d.ts +1 -1
  5. package/dist/{bus-D3OO0OcL.js → bus-BTMuVkDk.js} +19 -19
  6. package/dist/bus-BTMuVkDk.js.map +1 -0
  7. package/dist/bus-ChIXDAWD.cjs +2 -0
  8. package/dist/bus-ChIXDAWD.cjs.map +1 -0
  9. package/dist/capture/network.d.ts +2 -2
  10. package/dist/capture/types.d.ts +10 -10
  11. package/dist/capture/web-vitals.d.ts +3 -3
  12. package/dist/{constants-B6kdsCzF.js → constants-0-YchbAL.js} +2 -2
  13. package/dist/constants-0-YchbAL.js.map +1 -0
  14. package/dist/{constants-DZH04585.cjs → constants-TUFcy95w.cjs} +2 -2
  15. package/dist/constants-TUFcy95w.cjs.map +1 -0
  16. package/dist/constants.d.ts +53 -40
  17. package/dist/core/breadcrumbs.d.ts +14 -14
  18. package/dist/core/config.d.ts +5 -4
  19. package/dist/core/context.d.ts +2 -2
  20. package/dist/core/diagnostics.d.ts +10 -9
  21. package/dist/core/journey.d.ts +23 -20
  22. package/dist/core/logger.d.ts +7 -7
  23. package/dist/core/pipeline.d.ts +34 -29
  24. package/dist/core/record.d.ts +6 -6
  25. package/dist/core/runtime.d.ts +20 -18
  26. package/dist/core/sampling.d.ts +15 -16
  27. package/dist/core/sender.d.ts +1 -1
  28. package/dist/{errors-DPju_xSI.cjs → errors-DRXBRqvm.cjs} +2 -2
  29. package/dist/errors-DRXBRqvm.cjs.map +1 -0
  30. package/dist/{errors-Dme9tz-6.js → errors-Dwm2SzBa.js} +4 -4
  31. package/dist/errors-Dwm2SzBa.js.map +1 -0
  32. package/dist/index.cjs +1 -1
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.js +61 -61
  36. package/dist/index.js.map +1 -1
  37. package/dist/indexeddb-storage-B5dwq4hW.cjs +2 -0
  38. package/dist/indexeddb-storage-B5dwq4hW.cjs.map +1 -0
  39. package/dist/{indexeddb-storage-nxs_rxGx.js → indexeddb-storage-DjY4Ml6t.js} +16 -16
  40. package/dist/indexeddb-storage-DjY4Ml6t.js.map +1 -0
  41. package/dist/{interactions-DP0-rIPJ.cjs → interactions-DVom6eYn.cjs} +2 -2
  42. package/dist/interactions-DVom6eYn.cjs.map +1 -0
  43. package/dist/{interactions-C1romMpE.js → interactions-DZmLu7l2.js} +2 -2
  44. package/dist/interactions-DZmLu7l2.js.map +1 -0
  45. package/dist/models/batch.d.ts +12 -9
  46. package/dist/models/bus.d.ts +12 -13
  47. package/dist/models/config.d.ts +58 -41
  48. package/dist/models/log-record.d.ts +12 -10
  49. package/dist/models/serializer.d.ts +3 -2
  50. package/dist/models/storage.d.ts +2 -2
  51. package/dist/{network-au-Tqt1n.js → network-C4d2uw2Z.js} +4 -4
  52. package/dist/network-C4d2uw2Z.js.map +1 -0
  53. package/dist/network-CuqWadNn.cjs +2 -0
  54. package/dist/network-CuqWadNn.cjs.map +1 -0
  55. package/dist/platform-CXio0W2n.cjs +2 -0
  56. package/dist/platform-CXio0W2n.cjs.map +1 -0
  57. package/dist/{platform-DMYo3AX3.js → platform-CY8S3hUs.js} +8 -8
  58. package/dist/platform-CY8S3hUs.js.map +1 -0
  59. package/dist/sampling-CEthcmEX.cjs +2 -0
  60. package/dist/sampling-CEthcmEX.cjs.map +1 -0
  61. package/dist/{sampling-ByI5H44E.js → sampling-CJsI_24L.js} +21 -18
  62. package/dist/sampling-CJsI_24L.js.map +1 -0
  63. package/dist/sender-ByFAkXVd.cjs +3 -0
  64. package/dist/sender-ByFAkXVd.cjs.map +1 -0
  65. package/dist/{sender-R7lOpyNc.js → sender-dpvR_bHM.js} +60 -60
  66. package/dist/sender-dpvR_bHM.js.map +1 -0
  67. package/dist/storage/emergency-queue.d.ts +2 -2
  68. package/dist/storage/factory.d.ts +2 -1
  69. package/dist/storage/idb-driver.d.ts +19 -19
  70. package/dist/storage/indexeddb-storage.d.ts +18 -17
  71. package/dist/storage/keys.d.ts +1 -1
  72. package/dist/storage/local-storage.d.ts +19 -18
  73. package/dist/storage/memory-storage.d.ts +12 -11
  74. package/dist/transport/compression.d.ts +2 -2
  75. package/dist/transport/errors.d.ts +8 -7
  76. package/dist/transport/exit-flush.d.ts +27 -24
  77. package/dist/transport/http-transport.d.ts +18 -11
  78. package/dist/transport/retry-engine.d.ts +33 -28
  79. package/dist/transport/serializers/ecs.d.ts +1 -1
  80. package/dist/transport/serializers/otlp.d.ts +1 -1
  81. package/dist/unref-16maCyKA.js.map +1 -1
  82. package/dist/unref-CU9Nyz_9.cjs.map +1 -1
  83. package/dist/utils/identity.d.ts +6 -5
  84. package/dist/utils/lock.d.ts +4 -4
  85. package/dist/utils/platform.d.ts +5 -3
  86. package/dist/utils/sanitize.d.ts +5 -2
  87. package/dist/utils/sequence.d.ts +2 -2
  88. package/dist/utils/tracing.d.ts +8 -7
  89. package/dist/web-vitals-B2FYsEAU.cjs +2 -0
  90. package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
  91. package/dist/{web-vitals-DwWdLBq6.js → web-vitals-DHZ0yA_H.js} +4 -4
  92. package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
  93. package/package.json +1 -1
  94. package/dist/bus-D3OO0OcL.js.map +0 -1
  95. package/dist/bus-OdRJVUzr.cjs +0 -2
  96. package/dist/bus-OdRJVUzr.cjs.map +0 -1
  97. package/dist/constants-B6kdsCzF.js.map +0 -1
  98. package/dist/constants-DZH04585.cjs.map +0 -1
  99. package/dist/errors-DPju_xSI.cjs.map +0 -1
  100. package/dist/errors-Dme9tz-6.js.map +0 -1
  101. package/dist/indexeddb-storage-lGdoHGHy.cjs +0 -2
  102. package/dist/indexeddb-storage-lGdoHGHy.cjs.map +0 -1
  103. package/dist/indexeddb-storage-nxs_rxGx.js.map +0 -1
  104. package/dist/interactions-C1romMpE.js.map +0 -1
  105. package/dist/interactions-DP0-rIPJ.cjs.map +0 -1
  106. package/dist/network-DDVIJSHd.cjs +0 -2
  107. package/dist/network-DDVIJSHd.cjs.map +0 -1
  108. package/dist/network-au-Tqt1n.js.map +0 -1
  109. package/dist/platform-DMYo3AX3.js.map +0 -1
  110. package/dist/platform-g99Kn755.cjs +0 -2
  111. package/dist/platform-g99Kn755.cjs.map +0 -1
  112. package/dist/sampling-ByI5H44E.js.map +0 -1
  113. package/dist/sampling-Dui-Fp3u.cjs +0 -2
  114. package/dist/sampling-Dui-Fp3u.cjs.map +0 -1
  115. package/dist/sender-R7lOpyNc.js.map +0 -1
  116. package/dist/sender-vLcbQhiB.cjs +0 -3
  117. package/dist/sender-vLcbQhiB.cjs.map +0 -1
  118. package/dist/web-vitals-DM2nvcMJ.cjs +0 -2
  119. package/dist/web-vitals-DM2nvcMJ.cjs.map +0 -1
  120. package/dist/web-vitals-DwWdLBq6.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-CEthcmEX.cjs","names":["set","toJson","SESSION_ID_KEY","TAB_ID_KEY","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","require_unref","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","reject","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. Otherwise a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`The operation took longer than ${String(ms)} ms.`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"8EAwDA,SAAgBY,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAUA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOC,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAMC,EAASD,EACf,OACE,OAAOC,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA,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EAA4B,CAChC,GAAI/E,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMiD,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
@@ -1,4 +1,4 @@
1
- import { H as e, U as t, Ut as n, a as r, l as i, n as a, sn as o, tn as s } from "./constants-B6kdsCzF.js";
1
+ import { H as e, U as t, Ut as n, a as r, l as i, n as a, sn as o, tn as s } from "./constants-0-YchbAL.js";
2
2
  import { t as c } from "./unref-16maCyKA.js";
3
3
  //#region src/models/log-record.ts
4
4
  function l() {
@@ -22,17 +22,18 @@ function f(e) {
22
22
  function p(e) {
23
23
  return `[Element ${(e.nodeName ?? "NODE").toLowerCase()}${e.id ? `#${e.id}` : ""}${typeof e.className == "string" && e.className ? `.${e.className.trim().split(/\s+/).slice(0, 3).join(".")}` : ""}]`;
24
24
  }
25
- function m(e, t) {
26
- return h(e, t).value;
25
+ function m(e, t, n) {
26
+ return h(e, t, n).value;
27
27
  }
28
- function h(e, t) {
29
- let n = {
28
+ function h(e, t, n) {
29
+ let r = {
30
30
  bytes: 0,
31
- nodes: 0
31
+ nodes: 0,
32
+ diagnostics: n
32
33
  };
33
34
  return {
34
- value: _(e, t, /* @__PURE__ */ new WeakSet(), 0, n),
35
- bytes: n.bytes
35
+ value: _(e, t, /* @__PURE__ */ new WeakSet(), 0, r),
36
+ bytes: r.bytes
36
37
  };
37
38
  }
38
39
  function g(e, t) {
@@ -95,7 +96,7 @@ function _(e, t, n, r, i) {
95
96
  }
96
97
  return c;
97
98
  } catch (e) {
98
- return g(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
99
+ return i.diagnostics.count("record.sanitize_failed"), g(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
99
100
  } finally {
100
101
  n.delete(e);
101
102
  }
@@ -135,27 +136,29 @@ function x(e) {
135
136
  else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
136
137
  return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
137
138
  }
138
- function S() {
139
+ function S(e) {
139
140
  try {
140
141
  if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
141
- } catch {}
142
+ } catch {
143
+ e.count("platform.api_blocked");
144
+ }
142
145
  return x(16);
143
146
  }
144
147
  function C(e, t, n, r) {
145
- return r.guard("storage.unavailable", `reading ${t}Storage`, () => e[t]().getItem(n)) ?? null;
148
+ return r.guard("storage.unavailable", `The library could not read ${t}Storage.`, () => e[t]().getItem(n)) ?? null;
146
149
  }
147
150
  function w(e, t, n, r, i) {
148
- i.guard("storage.unavailable", `writing ${t}Storage`, () => {
151
+ i.guard("storage.unavailable", `The library could not write to ${t}Storage.`, () => {
149
152
  e[t]().setItem(n, r);
150
153
  });
151
154
  }
152
155
  function T(e, t = y) {
153
- let r = S(), i = Date.now(), a = S(), o = C(t, "local", n, e);
156
+ let r = S(e), i = Date.now(), a = S(e), o = C(t, "local", n, e);
154
157
  if (o) try {
155
158
  let e = JSON.parse(o);
156
159
  e.id && i - (e.lastSeenAt ?? 0) < 18e5 && (a = e.id);
157
160
  } catch {
158
- e.report("storage.degraded", "session record was not JSON, starting a new session");
161
+ e.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
159
162
  }
160
163
  let c = JSON.stringify({
161
164
  id: a,
@@ -163,7 +166,7 @@ function T(e, t = y) {
163
166
  });
164
167
  w(t, "local", n, c, e);
165
168
  let l = C(t, "session", "ui-observability.tab", e) ?? "";
166
- return l || (l = S(), w(t, "session", s, l, e)), {
169
+ return l || (l = S(e), w(t, "session", s, l, e)), {
167
170
  sessionId: a,
168
171
  tabId: l,
169
172
  contextId: r
@@ -195,7 +198,7 @@ var D = class {
195
198
  function O(e, t) {
196
199
  let n, r = new Promise((e, r) => {
197
200
  let i = setTimeout(() => {
198
- r(/* @__PURE__ */ Error(`timed out after ${String(t)}ms`));
201
+ r(/* @__PURE__ */ Error(`The operation took longer than ${String(t)} ms.`));
199
202
  }, t);
200
203
  n = i, c(i);
201
204
  });
@@ -245,4 +248,4 @@ var P = class {
245
248
  //#endregion
246
249
  export { l as _, y as a, S as c, T as d, v as f, u as g, d as h, O as i, E as l, h as m, N as n, D as o, m as p, M as r, b as s, P as t, x as u };
247
250
 
248
- //# sourceMappingURL=sampling-ByI5H44E.js.map
251
+ //# sourceMappingURL=sampling-CJsI_24L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-CJsI_24L.js","names":["set","toJson","FNV_OFFSET_BASIS","FNV_PRIME","SESSION_ID_KEY","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","UINT32_MAX","TAB_ID_KEY","unrefTimer","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. Otherwise a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`The operation took longer than ${String(ms)} ms.`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;;AAwDA,SAAgBW,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAMC,IAASD;CACf,OACE,OAAOC,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AC1CA,SAAgBC,EAAS,GAAe,GAAqB;CAC3D,IAAIF,EAAM,UAAUG,GAClB,OAAOH;CAKT,IAAMI,IAAMC,EAAgBL,EAAM,WAAWG,IAAM,CAAC,CAAC,IAAIA,IAAM,IAAIA;CACnE,OAAO,GAAGH,EAAM,MAAM,GAAGI,CAAG,EAAE,eAAe,OAAOJ,EAAM,SAASI,CAAG,EAAE;AAC1E;AAOA,SAASC,EA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A,IAAQ;AAC7C;AASA,SAASmE,EAAQ,GAAmB,GAAgC;CAClE,IAAM,EAAE,UAAO,mBAAgBC,EAAO,UAClCC,GACAC,IAAa;CAEjB,KAAK,IAAM,CAACC,GAAQC,MAAS,OAAO,QAAQC,CAAK,GAG/C,CAFgBC,MAAcH,KAAUG,EAAU,WAAW,GAAGH,EAAO,EAAE,MAE1DA,EAAO,SAASD,MAC7B,IAAOE,GACP,IAAaD,EAAO;CAIxB,OAAOF,KAAQM;AACjB;AAuBA,SAAgBC,EAAkB,GAAoB,GAAiC;CAMrF,IAJIC,EAAM,UAAU,WAAWA,EAAM,UAAU,WAI3CT,EAAO,SAAS,kBAAkB,SAASS,EAAM,IAAI,GACvD,OAAO;CAGT,IAAML,IAAOL,EAAQU,EAAM,WAAWT,CAAM;CAY5C,OAXII,KAAA,IACK,KAELA,KAAA,IACK,KAOFR,EAFKa,EAAM,aAAaA,EAAM,OAEtB,IAAIlF,IAAa6E;AAClC;AASA,SAAgBM,EAAa,GAAmB,GAAiC;CAC/E,OAAOF,EACL;EACE,OAAO3E,EAAO;EACd,MAAMiE,EAASjE,GAAQR,CAAa;EACpC,WAAWyE,EAASjE,GAAQP,CAAkB;EAC9C,WAAWwE,EAASjE,GAAQT,CAAe;EAC3C,SAASS,EAAO;CAClB,GACAmE,CACF;AACF;AAQA,IAAaW,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAI9E,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMiD,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
@@ -0,0 +1,3 @@
1
+ const e=require("./constants-TUFcy95w.cjs"),t=require("./sampling-CEthcmEX.cjs"),n=require("./unref-CU9Nyz_9.cjs");function r(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function i(e,n){if(e.records.length<2)return null;let r=Math.floor(e.records.length/2),i=r=>({id:t.c(n),records:r,createdAt:e.createdAt,attempts:e.attempts});return[i(e.records.slice(0,r)),i(e.records.slice(r))]}function a(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function o(e,t){let n=[];return t.guard(`storage.unavailable`,`The library could not list the localStorage keys.`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function s(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.R}${n}.${t.id}`}function c(e,t){let n=t.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return n===void 0?null:r(n)?n:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function l(n,r){let i=0;for(let a of o(e.R,r)){let o=r.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(a);return localStorage.removeItem(a),e});if(!o)continue;let s=c(o,r);if(s!==null)try{await t.i(n.save(s),e.qt),i++}catch(e){r.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:a},e)}}return i}function u(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=o(e.R,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(s(t),JSON.stringify(t))})}async function d(e,t){return await a(`ui-observability.emergency`,t,()=>l(e,t),{skipIfBusy:!1})??0}function f(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}function p(t){let n=e.v.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var m=class{limits;diagnostics;onGap;name=e.Zt;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){this.write(e,`localStorage refused a batch, evicting the oldest`)?await this.prune():(this.evictForQuota(),this.write(e,`localStorage refused a batch even after evicting`)||this.reportGap({batches:1,records:e.records.length,reason:`quota`}))}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=e=>{let n=this.read(e);this.removeKey(e),t.batches++,t.records+=n?.records.length??0},r=[];for(let t of this.keys()){let i=p(t);i===null||i<e?n(t):r.push(t)}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e)}return this.reportGap(t),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(f(e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`};for(let n of e.slice(0,Math.ceil(e.length/4))){let e=this.read(n);this.removeKey(n),t.batches++,t.records+=e?.records.length??0}this.reportGap(t)}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`The library dropped ${String(e.batches)} stored batches (${String(e.records)} records).`,{...e}),this.onGap?.(e))}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(t));return n===void 0?null:r(n)?n:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return o(e.v,this.diagnostics)}};function h(e){return e.reduce((e,t)=>e+t.records.length,0)}var g=class{limits;onGap;name=e.Qt;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),t.batches+=n.length,t.records+=h(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=h(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},_={name:e.$t,save:()=>Promise.resolve(),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()};function v(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function y(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e.en,`1`),localStorage.removeItem(e.en),!0))===!0}async function b(e,t,n,r,i){if(e===`none`)return _;if(e===`memory`)return new g(n,i);if(e===`indexeddb`||e===`auto`){if(v(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-B5dwq4hW.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new g(n,i)}return y(r)?new m(n,r,i):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new g(n,i))}function x(t){return e.ft.test(t)?Number(BigInt(t)/e.pt):Date.now()}function S(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function C(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function w(e,t,n,r){let i=S(n);if(i!==null)C(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)w(e,t,i,r);else for(let[i,a]of Object.entries(n))w(e,`${t}.${i}`,a,r);r.delete(n)}}function T(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))w(t,r,i,n);return t}var E={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=x(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:e.I[t.severityText]??t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Ot],version:t.resource[e.kt],environment:t.resource[e.wt]},user_agent:{original:t.resource[e.St]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...T(t.resource),...T(t.attributes)}})}).join(`
2
+ `)}\n`,contentType:e.k}}};function D(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(D).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:O(e)}}:null}function O(e){let t=[];for(let[n,r]of Object.entries(e)){let e=D(r);e&&t.push({key:n,value:e})}return t}var k=new WeakMap;function A(e){let t=k.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return k.set(e,n),n}var j={name:e.Vt,serialize(t){let n=new Map;for(let e of t){let t=A(e.resource),r=n.get(t);r?r.records.push(e):n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:O(t.resource)},scopeLogs:[{scope:{name:e.rn,version:e.in},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:O(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.O}}};function M(e){return e===`otlp`?j:e===`ecs`?E:e}var N=class{deps;installed=!1;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(n){let{diagnostics:r}=this.deps,i=this.endpointUrl();if(i===null)return;let a=this.drain(n);if(!a||a.records.length===0)return;let o=r.guard(`transport.serialize_failed`,`The ${n} exit flush could not serialize its batch.`,()=>M(this.deps.config.serializer).serialize(a.records));if(!o)return;if(t.f(o.body)>6e4){u(a,r);return}i.searchParams.set(e._t,a.id),i.searchParams.set(e.vt,n);let s=i.toString(),c=this.beacon(s,o.body);c!==`sent`&&(c===`refused`?u(a,r):this.keepaliveFetch(s,o.body,n))}drain(e){return e===`hidden`?this.deps.drainPending():this.deps.drainForExit()}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`The keepalive fetch fallback failed.`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.J]:e.A},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`The exit flush failed.`,{reason:r},e)})})}};async function P(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.z)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var F=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i){super(t),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function I(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.ut);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var L=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){let{endpoint:t}=this.config;t&&e.records.length!==0&&await this.post(e,t)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t,n){let{config:r}=this,i;try{i=M(r.serializer).serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`The serializer threw an error. The library dropped the batch.`,{batchId:t.id},e);return}let a=new Headers(await this.resolveHeaders());a.set(e.J,i.contentType),a.set(e.K,t.id),a.set(e.G,String(t.attempts));let o=await this.encodeBody(i.body);typeof o!=`string`&&a.set(e.q,e.z);let s=await this.dispatch(n,a,o);if(s.ok)this.throttledUntil=0;else throw await this.classify(s,t.id)}async encodeBody(e){let{config:n}=this;return n.compression!==`gzip`||t.f(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>P(e))??e}async dispatch(t,r,i){let{config:a}=this,o=new AbortController,s=setTimeout(()=>{o.abort()},e.xt);n.t(s);try{return await fetch(t,{method:`POST`,headers:r,body:i,credentials:a.credentials,signal:o.signal,cache:`no-store`})}catch{if(o.signal.aborted)throw new F(`timeout`,`The request took longer than ${String(e.xt)} ms.`);let t=globalThis.navigator?.onLine;throw new F(t===!1?`offline`:`transient`,`A network error occurred.`)}finally{clearTimeout(s)}}async classify(t,n){let r=t.status,i=I(t.headers.get(e.Y));if(r===401||r===403)return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${String(r)}. In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,{status:r,endpoint:this.config.endpoint}),new F(`permanent`,`The server rejected the batch with ${String(r)}.`,r);if(r===413)return new F(`too_large`,`The payload is too large.`,r,void 0,await this.readMaxBytes(t));if(r===429||r===503){let e=r===429;return this.throttledUntil=Date.now()+(i??2e3),e&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:i}),new F(`throttled`,e?`The server throttles the requests.`:`The service is not available.`,r,i)}return r===408||r>=500?new F(`transient`,`The server returned the error ${String(r)}.`,r):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${String(r)}. The library dropped it.`,{batchId:n,status:r}),new F(`permanent`,`The server rejected the batch with ${String(r)}.`,r))}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`The library could not read the body of the 413 response.`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()))??{}:e:{}}},R=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.It)}nudge(){this.draining||this.schedule(e.Ft)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,n.t(t)}bounded(n){return t.i(n,e.qt)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Ft*2**this.attempt,e.Lt);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await a(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.It)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(e.It),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.It),!0;for(let e of t)if(this.stopped||!await this.deliver(e))return!0;return this.schedule(t.length===this.batchesPerDrain?0:e.It),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=e.Jt.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${t.attempts.toString()} attempts.`,{batchId:t.id,records:t.records.length}),await this.bounded(this.storage.remove(t.id)),!0;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,!0}catch(n){let r=n instanceof F?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),!0):r?.kind===`offline`?(this.schedule(e.It),!1):r?.kind===`throttled`?(this.attempt++,this.schedule(r.retryAfterMs??this.backoffMs()),!1):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,this.schedule(r?.retryAfterMs??this.backoffMs()),!1)}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof F?t:void 0;if(n?.kind===`permanent`)return[];if(n?.kind!==`too_large`)return[e];let r=i(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),[])}};function z(t){return t.attributes[e.l]===e.st}var B={logs:{flushIntervalMs:e.ot,batchSize:100},metrics:{flushIntervalMs:e.lt,batchSize:500}},V=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,n.t(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},H=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i=B){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new V(i.logs,a),metrics:new V(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=t._(),this.route(e))}drainPending(){return this.toBatch([...this.streams.metrics.take(),...this.streams.logs.take()])}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.toBatch([...e,...this.streams.metrics.take(),...this.streams.logs.take()])}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.stop(),this.queue.length=0}toBatch(e){return e.length===0?null:{id:t.c(this.diagnostics),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=z(e)?this.streams.metrics:this.streams.logs;if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){let n=e.take(),r={id:t.c(this.diagnostics),records:n,createdAt:Date.now(),attempts:0};this.unconfirmed.set(r.id,r),this.enqueue(r)}enqueue(e){this.queue.push(e),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){try{await this.dispatch(e)}catch(t){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:e.id},t)}finally{this.inFlight--,this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs();if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`The server throttles requests. The pipeline stored the batch and did not send it.`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e)}catch(t){await this.storeFailed({...e,attempts:e.attempts+1},t),this.diagnostics.report(`transport.http_error`,`The send failed. The pipeline stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await this.retry.storeFailed(e,t)})}async store(n){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await t.i(this.storage.save(n),e.qt),this.retry.nudge()})}},U=class t{storage;transport;retry;pipeline;exitFlush;diagnostics;constructor(e,t,n,r,i,a){this.storage=e,this.transport=t,this.retry=n,this.pipeline=r,this.exitFlush=i,this.diagnostics=a}static async create(n){let{config:r,diagnostics:i}=n,a=await b(r.storage,e.Kt,e.Jt,i,n.onGap),o=new L(r,i),s=new R(a,o,i,r),c=new H(o,a,s,i),l=new N({config:r,diagnostics:i,drainForExit:()=>c.drainForExit(),drainPending:()=>c.drainPending()});await d(a,i);let u=!1;try{l.install(),s.start(),u=!0}finally{u||(l.uninstall(),s.stop())}return new t(a,o,s,c,l,i)}push(e){this.pipeline.push(e)}async flush(){let e=this.pipeline.drainPending();if(e)try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store the batch that flush() drained.`,async()=>{await this.retry.storeFailed({...e,attempts:e.attempts+1},t)}),this.diagnostics.report(`transport.http_error`,`The send from flush() failed. The library stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}async destroy(){this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}};exports.Sender=U;
3
+ //# sourceMappingURL=sender-ByFAkXVd.cjs.map