@utk09/ui-observability 0.7.0 → 0.8.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 (122) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +122 -0
  3. package/dist/bus/bus.d.ts +30 -0
  4. package/dist/bus-CUXRY0JR.cjs +2 -0
  5. package/dist/bus-CUXRY0JR.cjs.map +1 -0
  6. package/dist/{bus-DfAbg_pg.js → bus-DPDrlUBY.js} +96 -50
  7. package/dist/bus-DPDrlUBY.js.map +1 -0
  8. package/dist/capture/console.d.ts +37 -0
  9. package/dist/capture/errors.d.ts +2 -4
  10. package/dist/capture/long-frames.d.ts +31 -0
  11. package/dist/capture/storm.d.ts +17 -0
  12. package/dist/capture/types.d.ts +2 -0
  13. package/dist/console-CNljJict.js +81 -0
  14. package/dist/console-CNljJict.js.map +1 -0
  15. package/dist/console-PKzc-FmR.cjs +2 -0
  16. package/dist/console-PKzc-FmR.cjs.map +1 -0
  17. package/dist/constants-B28fDv2F.cjs +2 -0
  18. package/dist/constants-B28fDv2F.cjs.map +1 -0
  19. package/dist/constants-Bu49bm39.js +93 -0
  20. package/dist/constants-Bu49bm39.js.map +1 -0
  21. package/dist/constants.d.ts +32 -2
  22. package/dist/core/breadcrumbs.d.ts +1 -1
  23. package/dist/core/pipeline.d.ts +2 -2
  24. package/dist/core/record.d.ts +3 -0
  25. package/dist/core/remote-rules.d.ts +17 -0
  26. package/dist/core/remote-sampling.d.ts +65 -0
  27. package/dist/core/runtime.d.ts +10 -4
  28. package/dist/core/sampling.d.ts +5 -2
  29. package/dist/core/sender.d.ts +3 -0
  30. package/dist/errors-C78ZTjet.cjs +3 -0
  31. package/dist/errors-C78ZTjet.cjs.map +1 -0
  32. package/dist/{errors-4MQyjZVj.js → errors-Dnc-X4Ec.js} +19 -20
  33. package/dist/errors-Dnc-X4Ec.js.map +1 -0
  34. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  35. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  36. package/dist/global-scope-dp2jADRl.js +19 -0
  37. package/dist/global-scope-dp2jADRl.js.map +1 -0
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.js +287 -242
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
  44. package/dist/{indexeddb-storage-CcEJlq2l.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
  45. package/dist/{indexeddb-storage-0LtUALBg.js → indexeddb-storage-uD4oaRMc.js} +10 -10
  46. package/dist/{indexeddb-storage-0LtUALBg.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
  47. package/dist/{interactions-BMNPQ3WH.cjs → interactions-CsE2y_fQ.cjs} +2 -2
  48. package/dist/{interactions-BMNPQ3WH.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
  49. package/dist/{interactions-BaCmoGLB.js → interactions-igKTAJvj.js} +2 -2
  50. package/dist/{interactions-BaCmoGLB.js.map → interactions-igKTAJvj.js.map} +1 -1
  51. package/dist/library-request-Br_T09Bn.cjs +2 -0
  52. package/dist/library-request-Br_T09Bn.cjs.map +1 -0
  53. package/dist/library-request-Dt0fXhcn.js +14 -0
  54. package/dist/library-request-Dt0fXhcn.js.map +1 -0
  55. package/dist/long-frames-6pnjWSSR.js +65 -0
  56. package/dist/long-frames-6pnjWSSR.js.map +1 -0
  57. package/dist/long-frames-DahhqM6u.cjs +2 -0
  58. package/dist/long-frames-DahhqM6u.cjs.map +1 -0
  59. package/dist/models/bus.d.ts +16 -0
  60. package/dist/models/config.d.ts +90 -0
  61. package/dist/network-CZ0aFUsy.cjs +2 -0
  62. package/dist/network-CZ0aFUsy.cjs.map +1 -0
  63. package/dist/{network-jQ2t8rU4.js → network-aSNbwpue.js} +16 -15
  64. package/dist/network-aSNbwpue.js.map +1 -0
  65. package/dist/{platform-YuByH8A5.js → platform-BwbMRwHm.js} +7 -7
  66. package/dist/{platform-YuByH8A5.js.map → platform-BwbMRwHm.js.map} +1 -1
  67. package/dist/{platform-ByQllE_W.cjs → platform-D_XkVIF6.cjs} +2 -2
  68. package/dist/{platform-ByQllE_W.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
  69. package/dist/remote-rules-5UA23alm.js +86 -0
  70. package/dist/remote-rules-5UA23alm.js.map +1 -0
  71. package/dist/remote-rules-rJJZKVG8.cjs +2 -0
  72. package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
  73. package/dist/sampling-E4x92Nn2.cjs +2 -0
  74. package/dist/sampling-E4x92Nn2.cjs.map +1 -0
  75. package/dist/sampling-J1eahbfT.js +160 -0
  76. package/dist/sampling-J1eahbfT.js.map +1 -0
  77. package/dist/sanitize-BMhh8ghJ.cjs +2 -0
  78. package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
  79. package/dist/sanitize-UJ-4Lb0n.js +114 -0
  80. package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
  81. package/dist/sender-B6ufz26f.cjs +3 -0
  82. package/dist/sender-B6ufz26f.cjs.map +1 -0
  83. package/dist/{sender-BIob8eZz.js → sender-G6v4Uqi4.js} +304 -219
  84. package/dist/sender-G6v4Uqi4.js.map +1 -0
  85. package/dist/storm-BtzgLOCX.cjs +2 -0
  86. package/dist/storm-BtzgLOCX.cjs.map +1 -0
  87. package/dist/storm-DJkEZP_8.js +10 -0
  88. package/dist/storm-DJkEZP_8.js.map +1 -0
  89. package/dist/transport/custom-transport.d.ts +20 -0
  90. package/dist/transport/errors.d.ts +2 -1
  91. package/dist/transport/exit-flush.d.ts +15 -0
  92. package/dist/transport/http-transport.d.ts +2 -24
  93. package/dist/transport/memory-transport.d.ts +30 -0
  94. package/dist/transport/retry-engine.d.ts +2 -2
  95. package/dist/transport/serializers/select.d.ts +12 -1
  96. package/dist/transport/status-transport.d.ts +72 -0
  97. package/dist/utils/deadline.d.ts +7 -0
  98. package/dist/utils/global-scope.d.ts +20 -0
  99. package/dist/utils/library-console.d.ts +11 -0
  100. package/dist/utils/library-request.d.ts +12 -0
  101. package/package.json +1 -1
  102. package/dist/bus-DeZzr2bx.cjs +0 -2
  103. package/dist/bus-DeZzr2bx.cjs.map +0 -1
  104. package/dist/bus-DfAbg_pg.js.map +0 -1
  105. package/dist/constants-C8nZQBmQ.js +0 -86
  106. package/dist/constants-C8nZQBmQ.js.map +0 -1
  107. package/dist/constants-IBL_jd5R.cjs +0 -2
  108. package/dist/constants-IBL_jd5R.cjs.map +0 -1
  109. package/dist/errors-4MQyjZVj.js.map +0 -1
  110. package/dist/errors-CUdShXe7.cjs +0 -3
  111. package/dist/errors-CUdShXe7.cjs.map +0 -1
  112. package/dist/indexeddb-storage-CcEJlq2l.cjs +0 -2
  113. package/dist/network-DBNvxCE3.cjs +0 -2
  114. package/dist/network-DBNvxCE3.cjs.map +0 -1
  115. package/dist/network-jQ2t8rU4.js.map +0 -1
  116. package/dist/sampling-CbYySsZ1.js +0 -251
  117. package/dist/sampling-CbYySsZ1.js.map +0 -1
  118. package/dist/sampling-Cs50xsZl.cjs +0 -2
  119. package/dist/sampling-Cs50xsZl.cjs.map +0 -1
  120. package/dist/sender-BIob8eZz.js.map +0 -1
  121. package/dist/sender-iOjzcueM.cjs +0 -3
  122. package/dist/sender-iOjzcueM.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-IBL_jd5R.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","SEVERITY_NUMBER","LEVEL_ORDER","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_URL_FULL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","ATTR_SANITIZE_FAILED","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","TELEMETRY_SDK_LANGUAGE","SERIALIZER_NAME_OTLP","ECS_LEVEL_NAMES","CONTENT_TYPE_JSON","CONTENT_TYPE_NDJSON","NANOS_PER_MILLI","NANOS_PATTERN","HEADER_CONTENT_TYPE","HEADER_CONTENT_ENCODING","HEADER_RETRY_AFTER","HEADER_BATCH_ID","HEADER_ATTEMPT","ENCODING_GZIP","MILLIS_PER_SECOND","BEACON_LIMIT_BYTES","CONTENT_TYPE_TEXT_PLAIN","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","BATCH_STORAGE_KEY_PREFIX","EMERGENCY_STORAGE_KEY_PREFIX","STORAGE_PROBE_KEY","QUOTA_EXCEEDED_ERROR","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","STORAGE_NAME_LOCAL","STORAGE_NAME_MEMORY","STORAGE_NAME_NONE","DRAIN_LOCK_NAME","EMERGENCY_LOCK_NAME","JOURNEY_STORAGE_KEY","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LOG_TYPE_METRIC","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","ERROR_STORM_WINDOW_MS","CONSOLE_DEFAULT_STYLES","DURATION_PRECISION","GAP_REPORT_THROTTLE_MS","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DEFAULT_METRIC_UNIT","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","DEFAULT_CONFIG","CONSOLE_DEFAULT_LEVEL","LOG_FLUSH_INTERVAL_MS","METRIC_FLUSH_INTERVAL_MS","REQUEST_TIMEOUT_MS","COMPRESSION_THRESHOLD_BYTES","STORAGE_DB_NAME","STORAGE_LIMITS","STORAGE_DEADLINE_MS","RETRY_BASE_DELAY_MS","RETRY_MAX_DELAY_MS","RETRY_IDLE_DELAY_MS","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","ERROR_DEDUPE_MS","RECORD_LIMITS"],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// Defines all limits, thresholds, timing windows, storage keys, patterns, and\n// defaults that the library uses.\n\nimport type { ConsoleStyles, ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\nimport type { StorageLimits } from \"./models/storage\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/**\n * Throttle window for each diagnostic code, in milliseconds. It limits how often an error\n * loop calls the handler.\n */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Maps each log level to its OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names that records carry in the payload. The names\n// follow OpenTelemetry conventions. The `uiobs.` prefix marks the fields of this library.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number in its context. It starts at 1. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key. Network capture sets it. Do not reuse `ATTR_PAGE_URL`.\n * The page URL overwrites the request target under that key.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record when the library drops its attributes because they exceed the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. The code does not read it from package.json.\n * Change it by hand when you change the version in package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.7.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/**\n * ECS `log.level` names that differ from the lowercase severity text. ECS spells\n * the warning level in full. All other levels match in lowercase.\n * @see {@link SERIALIZER_NAME_ECS}\n */\nexport const ECS_LEVEL_NAMES: Partial<Record<LogLevel, string>> = { WARN: \"warning\" };\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. The transport can retry. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large. The transport must split the batch. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. It is CORS-safelisted and does not cause a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a stored batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch that exit flush stores. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store to evict on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/**\n * Native IndexedDB version. It starts at 11. Dexie, the previous adapter, opened the\n * same database at ten times its declared version. A version below 11 makes open()\n * fail with VersionError for an existing installation. Then no code can read the\n * batches in that database.\n */\nexport const INDEXEDDB_SCHEMA_VERSION = 11;\n\n/** IndexedDB object store that holds batches. Dexie set this name before the library removed it. */\nexport const INDEXEDDB_STORE_NAME = \"batches\";\n\n/** Index on the batch store that orders reads by creation time. */\nexport const INDEXEDDB_CREATED_AT_INDEX = \"createdAt\";\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. It rejects an oversized token. It does not\n * validate the token content.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * Time to wait for `fin.me.getOptions()`, in milliseconds. After this time, the\n * runtime continues without a seeded journey.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/**\n * W3C trace context header name\n * @see {@link TRACEPARENT_VERSION}\n */\nexport const TRACEPARENT_HEADER = \"traceparent\";\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants. The sampler uses them to change a sampling key into a\n// stable 0-1 fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. The bus drops an envelope with a different version. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n/** Global key of the runtime that shutdown() stopped. Calls go to it until the next configure(). */\nexport const RUNTIME_STOPPED_KEY = \"ui-observability.stopped\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/**\n * Max ERROR and FATAL records that the pipeline admits in each storm window.\n * It is a safety limit for a render loop. It does not shape normal traffic.\n * ERROR and FATAL records skip sampling. A direct logger.error call has no other limit.\n */\nexport const ERROR_CEILING_MAX_PER_WINDOW = 500;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** Default CSS of the console prefix. The colors are readable on light and dark devtools. */\nexport const CONSOLE_DEFAULT_STYLES: Readonly<Required<ConsoleStyles>> = {\n namespace: \"color:#888\",\n TRACE: \"color:#888;font-weight:bold\",\n DEBUG: \"color:#888;font-weight:bold\",\n INFO: \"color:#1e6fd9;font-weight:bold\",\n WARN: \"color:#c77700;font-weight:bold\",\n ERROR: \"color:#d32f2f;font-weight:bold\",\n FATAL: \"color:#d32f2f;font-weight:bold\",\n};\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\n \"redact\",\n \"onDiagnostic\",\n \"headers\",\n \"serializer\",\n \"otelLoader\",\n] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\"sampling\", \"bus\", \"capture\"] as const;\n\n/**\n * Section keys with no default, excluded from their section of `DEFAULT_CONFIG`.\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const UNDEFAULTED_SECTION_KEYS: Record<(typeof CONFIG_SECTIONS)[number], string[]> = {\n sampling: [],\n bus: [],\n capture: [\"webVitalsLoader\"],\n};\n\n/**\n * Default runtime config before the consumer calls `configure()`. It excludes `serializer`.\n * `resolveConfig` supplies that default to prevent a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n compression: \"gzip\",\n credentials: \"omit\",\n storage: \"auto\",\n identity: \"storage\",\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n bus: { mode: \"auto\", trustedOrigins: [], openFinRole: \"auto\" },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n fullUrls: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n },\n console: { level: null, styles: CONSOLE_DEFAULT_STYLES },\n};\n\n/** Console mirroring level used when a consumer passes `console: true`. */\nexport const CONSOLE_DEFAULT_LEVEL: LogLevel = \"DEBUG\";\n\n// ----------------------------------\n// Batching\n// ----------------------------------\n\n/** Max time a partial log batch waits before the pipeline sends it, in milliseconds. */\nexport const LOG_FLUSH_INTERVAL_MS = 2000;\n\n/** Max records per log batch. At this count, the pipeline sends the batch early. */\nexport const LOG_BATCH_SIZE = 100;\n\n/**\n * Max time a partial metric batch waits before the pipeline sends it, in milliseconds.\n * Metric batches wait longer than log batches. Metrics have a higher volume, and no\n * caller waits for them.\n */\nexport const METRIC_FLUSH_INTERVAL_MS = 10_000;\n\n/** Max records per metric batch. At this count, the pipeline sends the batch early. */\nexport const METRIC_BATCH_SIZE = 500;\n\n/** Max concurrent ingest requests, across both streams. */\nexport const MAX_CONCURRENT_REQUESTS = 2;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Max time for one ingest request, in milliseconds. Then the transport aborts and retries it. */\nexport const REQUEST_TIMEOUT_MS = 15_000;\n\n/** Min payload size to compress, in bytes. */\nexport const COMPRESSION_THRESHOLD_BYTES = 1024;\n\n// ----------------------------------\n// Storage retention\n// ----------------------------------\n\n/** IndexedDB database name. */\nexport const STORAGE_DB_NAME = \"UiObservability\";\n\n/** Capacity and retention thresholds every storage adapter enforces. */\nexport const STORAGE_LIMITS: StorageLimits = {\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n};\n\n/**\n * Max time for one storage call, in milliseconds. Then the library treats the call as failed.\n * A call that does not settle keeps a dispatch slot or the drain flag.\n */\nexport const STORAGE_DEADLINE_MS = 10_000;\n\n// ----------------------------------\n// Retry backoff\n// ----------------------------------\n\n/** First backoff step, in milliseconds. Each attempt doubles it. */\nexport const RETRY_BASE_DELAY_MS = 2000;\n\n/** Backoff ceiling, in milliseconds. */\nexport const RETRY_MAX_DELAY_MS = 60_000;\n\n/** How often to check for stored work when nothing has failed recently, in milliseconds. */\nexport const RETRY_IDLE_DELAY_MS = 30_000;\n\n// ----------------------------------\n// Journey lifetime\n// ----------------------------------\n\n/** Max time a journey stays open, in milliseconds. Then the library treats it as abandoned. */\nexport const JOURNEY_MAX_AGE_MS = 30 * 60 * 1000;\n\n/** Whether closing the owning context ends the journey for everyone. */\nexport const JOURNEY_END_ON_OWNER_CLOSE = false;\n\n/** Query parameter checked at boot for a seeded journey token. */\nexport const JOURNEY_URL_PARAM = \"__uiobs_journey\";\n\n// ----------------------------------\n// Bus handshake\n// ----------------------------------\n\n/** BroadcastChannel name for the control plane. */\nexport const BUS_CHANNEL_NAME = \"ui_observability_control\";\n\n/** Max time a forwarder waits for an owner to answer before it promotes itself, in milliseconds. */\nexport const BUS_HANDSHAKE_TIMEOUT_MS = 1500;\n\n/** Handshake attempts allowed before a cross-origin forwarder promotes itself to sender. */\nexport const BUS_MAX_HANDSHAKE_ATTEMPTS = 3;\n\n/** Max records a context buffers before it knows its bus role. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Breadcrumbs kept as context for the next error. */\nexport const MAX_BREADCRUMBS = 50;\n\n/**\n * Time window in which the library counts identical errors but does not send them again,\n * in milliseconds.\n */\nexport const ERROR_DEDUPE_MS = 5000;\n\n// ----------------------------------\n// Per-record size caps\n// ----------------------------------\n\n/** Size caps for every record. The library applies them after sanitize and after redact. */\nexport const RECORD_LIMITS = {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxNodes: 10_000,\n maxRecordBytes: 32_768,\n};\n"],"mappings":"AAcA,IAuCaA,GAAqB,WAGrBC,GAA6B,SAG7BC,EAAwB,yBAGxBC,GAAuB,gBAGvBC,EAAoB,aAqDpBC,EAA4C,CACvD,MAAO,EACP,MAAO,EACP,KAAM,EACN,KAAM,GACN,MAAO,GACP,MAAO,EACT,EAMaC,EAAwCD,EAUxCE,EAAgB,WAGhBC,EAAe,UAGfC,EAAqB,gBAGrBC,EAAgB,WAOhBC,EAAgB,WAGhBC,EAAkB,aAGlBC,EAAoB,eAGpBC,EAAyB,oBAGzBC,EAAuB,wBAMvBC,EAA0B,2BAM1BC,EAAwB,yBAGxBC,EAAwB,eAGxBC,EAA2B,kBAG3BC,EAAkC,yBAMlCC,EAA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CAAC,WAAY,MAAO,SAAS,EAM/CC,GAA+E,CAC1F,SAAU,CAAC,EACX,IAAK,CAAC,EACN,QAAS,CAAC,iBAAiB,CAC7B,EAQaC,GAAqD,CAChE,SAAU,GACV,YAAa,GACb,eAAgB,GAChB,YAAa,GACb,QAAS,GACT,SAAU,OACV,YAAa,OACb,YAAa,OACb,QAAS,OACT,SAAU,UACV,SAAU,CAAE,YAAa,EAAG,MAAO,CAAC,EAAG,kBAAmB,CAAC,QAAQ,CAAE,EACrE,IAAK,CAAE,KAAM,OAAQ,eAAgB,CAAC,EAAG,YAAa,MAAO,EAC7D,QAAS,CACP,OAAQ,GACR,WAAY,GACZ,eAAgB,GAChB,MAAO,GACP,IAAK,GACL,aAAc,GACd,WAAY,GACZ,UAAW,GACX,SAAU,GACV,WAAY,CAAC,EACb,uBAAwB,CAAC,CAC3B,EACA,QAAS,CAAE,MAAO,KAAM,OAAQV,CAAuB,CACzD,EAGaW,GAAkC,QAOlCC,GAAwB,IAUxBC,GAA2B,IAa3BC,GAAqB,KAGrBC,GAA8B,KAO9BC,GAAkB,kBAGlBC,GAAgC,CAC3C,WAAY,IACZ,SAAU,MACV,YAAa,CACf,EAMaC,GAAsB,IAOtBC,GAAsB,IAGtBC,GAAqB,IAGrBC,GAAsB,IAOtBC,GAAqB,KAMrBC,GAAoB,kBAOpBC,GAAmB,2BAGnBC,GAA2B,KAmB3BC,GAAkB,IAOlBC,GAAgB,CAC3B,aAAc,KACd,kBAAmB,KACnB,kBAAmB,IACnB,cAAe,KACf,SAAU,EACV,eAAgB,IAChB,SAAU,IACV,eAAgB,KAClB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-4MQyjZVj.js","names":["ERROR_STORM_WINDOW_MS","stripUrlQuery","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;AAsBA,IAAaE,IAAb,MAA6C;CAmBd;CAjB7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,cAAsB;CAGtB,cAAsB;CAKtB,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK,KAAK,MAAM;CAClB;CAGA,WAA4B,MAAoC;EAC9D,IAAMC,IAASC,EAAM,QACfC,IAAcF,GAAQ,OAAOA,GAAQ,QAAQ;EAGnD,IACEA,MAAW,QACXA,MAAY,cACZE,MAAgB,IAChB;GACA,IAAI,CAAC,KA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,IAAIC,KAAYJ,IAAMI,EAAS,KAAA,KAAsB;GAEnD,AADA,EAAS,SACT,EAAS,KAAKJ;GACd;EACF;EAIA,IAAMK,IAAaD,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOD,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIH;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACM,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,YAAY,KAAKM,IAASN,EAAQ,SAASA,GAAS;GAChF,GAAGO;GACH,qBAAqBD;GACrB,0BAA0BF;EAC5B,CAAC;CACH;AACF"}
@@ -1,3 +0,0 @@
1
- const e=require("./constants-IBL_jd5R.cjs"),t=require("./platform-ByQllE_W.cjs");var n=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`More than 20 errors occurred in ${String(e.V)} ms. The library ignores the other errors in this window.`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
2
- `)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};exports.ErrorCapture=n;
3
- //# sourceMappingURL=errors-CUdShXe7.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-CUdShXe7.cjs","names":["stripUrlQuery","ERROR_STORM_WINDOW_MS","require_constants","require_platform","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"iFAsBA,IAAaI,EAAb,KAA6C,CAmBd,IAjB7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,YAAsB,EAGtB,YAAsB,EAKtB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qBAAsB,KAAK,WAAW,EACzD,CAGA,WAAkB,CACX,KAAK,YAGV,KAAK,UAAY,GAEjB,oBAAoB,QAAS,KAAK,QAAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CAGA,QAA4B,GAAoC,CAC9D,IAAMC,EAASC,EAAM,OACfC,EAAcF,GAAQ,KAAOA,GAAQ,MAAQ,GAGnD,GACEA,IAAW,MACXA,IAAY,YACZE,IAAgB,GAChB,CACA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,eAC3B,OAKF,IAAMC,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAWD,EAAcR,EAAAA,EAAcQ,CAAW,EAEtF,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,oBAAoBC,GAC/B,CAAC,EACD,KAAK,IAAI,OAAO,KAAK,0BAA2B,CAC9C,aAAc,WACd,eAAgBA,EAChB,eAAgBH,EAAO,QAAQ,YAAY,CAC7C,CAAC,EACD,MACF,CAEA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,OAC3B,OAGF,IAAMI,EAAaH,EACbI,EAAWD,EAAW,UAAY,GAAK,gBAAkBA,EAAW,QAEpEE,EADkBF,EAAW,OACP,MAA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CACH,CACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-IBL_jd5R.cjs");function t(e){return e.error??Error(`The IndexedDB request failed.`)}function n(e){return new Promise((n,r)=>{e.onsuccess=()=>{n(e.result)},e.onerror=()=>{r(t(e))}})}var r=class{name;connection=null;constructor(e){this.name=e}async put(e){await n((await this.store(`readwrite`)).put(e))}async takeOldest(t){return n((await this.store(`readonly`)).index(e.Q).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Q).getAll(i))}async delete(e){await n((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>n(t.delete(e))))}async bumpAttempts(e,t){let r=await this.store(`readwrite`),i=await n(r.get(e));i!==void 0&&await n(r.put({...i,attempts:t}))}async count(){return n((await this.store(`readonly`)).count())}async clear(){await n((await this.store(`readwrite`)).clear())}async ready(){await this.open()}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.$,t).objectStore(e.$)}open(){let n=this.connection;if(n!==null)return n;let r=new Promise((n,r)=>{let i=indexedDB.open(this.name,11),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.$,{keyPath:`id`}).createIndex(e.Q,e.Q)},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},n(e))},i.onerror=()=>{r(t(i))},i.onblocked=()=>{a=!0,r(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=r.catch(e=>{throw this.connection=null,e}),this.connection}};function i(e){return e.reduce((e,t)=>e+t.records.length,0)}var a=class{limits;diagnostics;onGap;name=e.Xt;db;constructor(e,t,n,i){this.limits=t,this.diagnostics=n,this.onGap=i,this.db=new r(e)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e),await this.prune()}catch(t){if(t instanceof Error&&t.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full. The library removes the oldest batches.`);let t=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove old batches after a full disk.`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));t&&this.reportGap({...t,reason:`quota`}),await this.diagnostics.guardAsync(`storage.degraded`,`The library could not write the batch after it removed old batches.`,async()=>(await this.db.put(e),!0))!==!0&&this.reportGap({batches:1,records:e.records.length,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(e))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not delete a batch.`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not update the attempt count.`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),e.batches+=n.length,e.records+=i(n));let r=await this.db.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the stored batches.`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not clear the stored batches.`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not close the database.`,()=>this.db.close())}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))}async evictOldest(e){let t=await this.db.takeOldest(e);return await this.db.deleteMany(t.map(e=>e.id)),{batches:t.length,records:i(t)}}};exports.IndexedDbStorage=a;
2
- //# sourceMappingURL=indexeddb-storage-CcEJlq2l.cjs.map
@@ -1,2 +0,0 @@
1
- const e=require("./platform-ByQllE_W.cjs");function t(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function n(){return XMLHttpRequest.prototype}var r=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(n().open=this.originalOpen,null),this.originalSend&&=(n().send=this.originalSend,null)}ignored(e){return t(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let n=this.ctx,r=e=>this.ignored(e),i=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(a,o){let s=typeof a==`string`?a:a instanceof URL?a.href:a.url,c=(o?.method??(a instanceof Request?a.method:`GET`)).toUpperCase();if(r(s))return e(a,o);let l=a,u=o;if(t(s,n.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(n.tracing.headers());if(a instanceof Request){let t=new Headers(a.headers);for(let[n,r]of e)t.set(n,r);l=new Request(a,{headers:t})}else{let t=new Headers(o?.headers);for(let[n,r]of e)t.set(n,r);u={...o,headers:t}}}catch(e){l=a,u=o,n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:s},e)}let d=performance.now();try{let t=await e(l,u);return i(c,s,t.status,performance.now()-d,void 0),t}catch(e){throw i(c,s,0,performance.now()-d,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},r=n(),i=r.open,a=r.send;this.originalOpen=i,this.originalSend=a,r.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},i.apply(this,[e,t,...n])},r.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),a.apply(this,n)}}record(t,n,r,i,a){let o=this.ctx.config.capture.fullUrls?n:e.r(n);this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${t} ${o}.`,()=>{let e=Math.round(i);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${t} ${o} ${r===0?`failed`:String(r)}`,data:{durationMs:e}});let n={"http.request.method":t,"url.full":o,"http.response.status_code":r,"http.duration_ms":e};r===0?this.ctx.logger.error(`${t} ${o} failed`,a,n):r>=400?this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`,n):this.ctx.logger.debug(`${t} ${o}`,n)})}};exports.NetworkCapture=r;
2
- //# sourceMappingURL=network-DBNvxCE3.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-DBNvxCE3.cjs","names":["stripUrlQuery","require_platform","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":"2CA8GA,SAAgBE,EAAW,EAAa,EAAwC,CAC9E,OAAOC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWC,EAAI,SAASD,CAAO,EAAIA,EAAQ,KAAKC,CAAG,CACxE,CACF,CC5FA,SAASC,GAAyB,CAChC,OAAO,eAAe,SACxB,CAGA,IAAaC,EAAb,KAA+C,CAgBhB,IAd7B,KAAgB,UAGhB,cAAwC,KAGxC,aAAkD,KAGlD,aAAkD,KAKlD,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,aAAa,EAEhB,KAAK,IAAI,OAAO,QAAQ,KAC1B,KAAK,WAAW,CAEpB,CAGA,WAAkB,CAChB,AAEE,KAAK,iBADL,WAAW,MAAQ,KAAK,cACH,MAEvB,AAEE,KAAK,gBADL,EAAW,CAAC,CAAC,KAAO,KAAK,aACL,MAEtB,AAEE,KAAK,gBADL,EAAW,CAAC,CAAC,KAAO,KAAK,aACL,KAExB,CAOA,QAAgB,EAAsB,CAGpC,OA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A,EAAcgC,CAAM,EAI5E,KAAK,IAAI,YAAY,MACnB,wBACA,gCAAgCpB,EAAO,GAAGP,EAAI,OACxC,CACJ,IAAM4B,EAAU,KAAK,MAAMnB,CAAU,EAErC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,GAAGF,EAAO,GAAGP,EAAI,GAAGQ,IAAW,EAAI,SAAW,OAAOA,CAAM,IACpE,KAAM,CAAE,WAAYoB,CAAQ,CAC9B,CAAC,EAED,IAAMC,EAAa,CACjB,sBAAuBtB,EACvB,WAAYP,EACZ,4BAA6BQ,EAC7B,mBAAoBoB,CACtB,EAEIpB,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,SAAUU,EAAOmB,CAAU,EAGhErB,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,IAAKqB,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,IAAO6B,CAAU,CACtD,CACF,CACF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-jQ2t8rU4.js","names":["stripUrlQuery","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":";;AA8GA,SAAgBC,EAAW,GAAa,GAAwC;CAC9E,OAAOC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWC,EAAI,SAASD,CAAO,IAAIA,EAAQ,KAAKC,CAAG,CACxE;AACF;;;AC5FA,SAASC,IAAyB;CAChC,OAAO,eAAe;AACxB;AAGA,IAAaC,IAAb,MAA+C;CAgBhB;CAd7B,OAAgB;CAGhB,gBAAwC;CAGxC,eAAkD;CAGlD,eAAkD;CAKlD,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EAId,AAHI,KAAK,IAAI,OAAO,QAAQ,SAC1B,KAAK,aAAa,GAEhB,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,WAAW;CAEpB;CAGA,YAAkB;EAShB,AARA,AAEE,KAAK,mBADL,WAAW,QAAQ,KAAK,eACH,OAEvB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO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MAAM,MAAME,CAAI;EAC/B;CACF;CAUA,OACE,GACA,GACA,GACA,GACA,GACM;EAGN,IAAMzB,IAAM,KAAK,IAAI,OAAO,QAAQ,WAAW2B,IAAS/B,EAAc+B,CAAM;EAI5E,KAAK,IAAI,YAAY,MACnB,yBACA,gCAAgCpB,EAAO,GAAGP,EAAI,UACxC;GACJ,IAAM4B,IAAU,KAAK,MAAMnB,CAAU;GAErC,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,GAAGF,EAAO,GAAGP,EAAI,GAAGQ,MAAW,IAAI,WAAW,OAAOA,CAAM;IACpE,MAAM,EAAE,YAAYoB,EAAQ;GAC9B,CAAC;GAED,IAAMC,IAAa;IACjB,uBAAuBtB;IACvB,YAAYP;IACZ,6BAA6BQ;IAC7B,oBAAoBoB;GACtB;GAEA,AAAIpB,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,UAAUU,GAAOmB,CAAU,IAGhErB,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,KAAKqB,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,KAAO6B,CAAU;EACtD,CACF;CACF;AACF"}
@@ -1,251 +0,0 @@
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-C8nZQBmQ.js";
2
- import { t as c } from "./unref-16maCyKA.js";
3
- //#region src/models/log-record.ts
4
- function l() {
5
- return `${String(Date.now())}000000`;
6
- }
7
- function u(e) {
8
- if (typeof e != "object" || !e) return !1;
9
- let t = e;
10
- return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
11
- }
12
- //#endregion
13
- //#region src/utils/sanitize.ts
14
- function d(e, t) {
15
- if (e.length <= t) return e;
16
- let n = f(e.charCodeAt(t - 1)) ? t - 1 : t;
17
- return `${e.slice(0, n)}… [truncated ${String(e.length - n)} chars]`;
18
- }
19
- function f(e) {
20
- return e >= 55296 && e <= 56319;
21
- }
22
- function p(e) {
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
- }
25
- function m(e, t, n) {
26
- return h(e, t, n).value;
27
- }
28
- function h(e, t, n) {
29
- let r = {
30
- bytes: 0,
31
- nodes: 0,
32
- diagnostics: n
33
- };
34
- return {
35
- value: _(e, t, /* @__PURE__ */ new WeakSet(), 0, r),
36
- bytes: r.bytes
37
- };
38
- }
39
- function g(e, t) {
40
- return t.bytes += v(e) + 2, e;
41
- }
42
- function _(e, t, n, r, i) {
43
- if (i.nodes++, i.nodes > t.maxNodes) return g("[MaxNodes]", i);
44
- if (e == null) return i.bytes += 4, e;
45
- if (typeof e == "string") return g(d(e, t.maxAttributeChars), i);
46
- if (typeof e == "number") return i.bytes += 8, Number.isFinite(e) ? e : String(e);
47
- if (typeof e == "boolean") return i.bytes += 5, e;
48
- if (typeof e == "bigint") return g(`${e.toString()}n`, i);
49
- if (typeof e == "symbol") return g(e.toString(), i);
50
- if (typeof e == "function") return g(`[Function ${e.name === "" ? "anonymous" : e.name}]`, i);
51
- if (r >= t.maxDepth) return g("[MaxDepth]", i);
52
- if (n.has(e)) return g("[Circular]", i);
53
- n.add(e), i.bytes += 2;
54
- try {
55
- if (e instanceof Error) return {
56
- name: g(e.name, i),
57
- message: g(d(e.message, t.maxAttributeChars), i),
58
- stack: e.stack ? g(d(e.stack, t.maxStackChars), i) : void 0,
59
- cause: e.cause ? _(e.cause, t, n, r + 1, i) : void 0
60
- };
61
- if (e instanceof Date) return g(e.toISOString(), i);
62
- if (e instanceof RegExp) return g(e.toString(), i);
63
- if (e instanceof Map) {
64
- let a = e, o = {}, s = 0;
65
- for (let [e, c] of a) {
66
- if (s >= t.maxArrayLength) {
67
- o["…"] = g(`[${String(a.size - t.maxArrayLength)} more entries]`, i);
68
- break;
69
- }
70
- s++;
71
- let l = String(e);
72
- i.bytes += v(l) + 4, o[l] = _(c, t, n, r + 1, i);
73
- }
74
- return o;
75
- }
76
- if (e instanceof Set) return _([...e].slice(0, t.maxArrayLength), t, n, r, i);
77
- if (ArrayBuffer.isView(e)) {
78
- let t = e.length ?? 0;
79
- return g(`[${e.constructor.name}(${String(t)})]`, i);
80
- }
81
- if (e instanceof Promise) return g("[Promise]", i);
82
- if (typeof Node < "u" && e instanceof Node) return g(p(e), i);
83
- if (Array.isArray(e)) {
84
- let a = e, o = a.slice(0, t.maxArrayLength).map((e) => _(e, t, n, r + 1, i));
85
- return a.length > t.maxArrayLength && o.push(g(`[${String(a.length - t.maxArrayLength)} more items]`, i)), o;
86
- }
87
- let a = e.toJSON;
88
- if (typeof a == "function") return _(a.call(e), t, n, r + 1, i);
89
- let o = e, s = Object.keys(o), c = {}, l = 0;
90
- for (let e of s) {
91
- if (l >= t.maxAttributeCount) {
92
- c["…"] = g(`[${String(s.length - l)} more keys]`, i);
93
- break;
94
- }
95
- l++, i.bytes += v(e) + 4, c[e] = _(o[e], t, n, r + 1, i);
96
- }
97
- return c;
98
- } catch (e) {
99
- return i.diagnostics.count("record.sanitize_failed"), g(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
100
- } finally {
101
- n.delete(e);
102
- }
103
- }
104
- function v(e) {
105
- let t = 0;
106
- for (let n = 0; n < e.length; n++) {
107
- let r = e.charCodeAt(n);
108
- r < 128 ? t += 1 : r < 2048 ? t += 2 : r >= 55296 && r <= 56319 ? (t += 4, n++) : t += 3;
109
- }
110
- return t;
111
- }
112
- //#endregion
113
- //#region src/utils/identity.ts
114
- var y = {
115
- local: () => localStorage,
116
- session: () => sessionStorage
117
- };
118
- function b() {
119
- let e = (e) => ({
120
- getItem: (t) => e.get(t) ?? null,
121
- setItem: (t, n) => {
122
- e.set(t, n);
123
- },
124
- removeItem: (t) => {
125
- e.delete(t);
126
- }
127
- }), t = e(/* @__PURE__ */ new Map()), n = e(/* @__PURE__ */ new Map());
128
- return {
129
- local: () => t,
130
- session: () => n
131
- };
132
- }
133
- function x(e) {
134
- let t = new Uint8Array(e);
135
- if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
136
- else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
137
- return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
138
- }
139
- function S(e) {
140
- try {
141
- if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
142
- } catch {
143
- e.count("platform.api_blocked");
144
- }
145
- return x(16);
146
- }
147
- function C(e, t, n, r) {
148
- return r.guard("storage.unavailable", `The library could not read ${t}Storage.`, () => e[t]().getItem(n)) ?? null;
149
- }
150
- function w(e, t, n, r, i) {
151
- i.guard("storage.unavailable", `The library could not write to ${t}Storage.`, () => {
152
- e[t]().setItem(n, r);
153
- });
154
- }
155
- function T(e, t = y) {
156
- let r = S(e), i = Date.now(), a = S(e), o = C(t, "local", n, e);
157
- if (o) try {
158
- let e = JSON.parse(o);
159
- e.id && i - (e.lastSeenAt ?? 0) < 18e5 && (a = e.id);
160
- } catch {
161
- e.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
162
- }
163
- let c = JSON.stringify({
164
- id: a,
165
- lastSeenAt: i
166
- });
167
- w(t, "local", n, c, e);
168
- let l = C(t, "session", "ui-observability.tab", e) ?? "";
169
- return l || (l = S(e), w(t, "session", s, l, e)), {
170
- sessionId: a,
171
- tabId: l,
172
- contextId: r
173
- };
174
- }
175
- function E(e, t, n) {
176
- w(n, "session", s, e, t);
177
- }
178
- var D = class {
179
- diagnostics;
180
- stores;
181
- lastTouchAt = 0;
182
- constructor(e, t = y) {
183
- this.diagnostics = e, this.stores = t;
184
- }
185
- touch(e) {
186
- let t = Date.now();
187
- if (t - this.lastTouchAt < 6e4) return;
188
- this.lastTouchAt = t;
189
- let r = JSON.stringify({
190
- id: e,
191
- lastSeenAt: t
192
- });
193
- w(this.stores, "local", n, r, this.diagnostics);
194
- }
195
- };
196
- //#endregion
197
- //#region src/utils/deadline.ts
198
- function O(e, t) {
199
- let n, r = new Promise((e, r) => {
200
- let i = setTimeout(() => {
201
- r(/* @__PURE__ */ Error(`The operation took longer than ${String(t)} ms.`));
202
- }, t);
203
- n = i, c(i);
204
- });
205
- return Promise.race([e, r]).finally(() => {
206
- clearTimeout(n);
207
- });
208
- }
209
- //#endregion
210
- //#region src/core/sampling.ts
211
- function k(n) {
212
- let r = e;
213
- for (let e = 0; e < n.length; e++) r ^= n.charCodeAt(e), r = Math.imul(r, t);
214
- return r >>> 0;
215
- }
216
- function A(e, t) {
217
- let n = e.attributes[t];
218
- return typeof n == "string" ? n : "";
219
- }
220
- function j(e, t) {
221
- let { rates: n, defaultRate: r } = t.sampling, i, a = -1;
222
- for (let [t, r] of Object.entries(n)) (e === t || e.startsWith(`${t}.`)) && t.length > a && (i = r, a = t.length);
223
- return i ?? r;
224
- }
225
- function M(e, t) {
226
- if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
227
- let n = j(e.namespace, t);
228
- return n >= 1 ? !0 : n <= 0 ? !1 : k(e.journeyId || e.traceId) / o < n;
229
- }
230
- function N(e, t) {
231
- return M({
232
- level: e.severityText,
233
- type: A(e, i),
234
- namespace: A(e, a),
235
- journeyId: A(e, r),
236
- traceId: e.traceId
237
- }, t);
238
- }
239
- var P = class {
240
- windowStart = 0;
241
- count = 0;
242
- allow(e) {
243
- if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
244
- let t = Date.now();
245
- return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
246
- }
247
- };
248
- //#endregion
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 };
250
-
251
- //# sourceMappingURL=sampling-CbYySsZ1.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampling-CbYySsZ1.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,EAAgB,GAAuB;CAC9C,OAAOC,KAAA,SAA8BA,KAAA;AACvC;AAcA,SAASC,EAAa,GAAwB;CAO5C,OAAO,aANMC,EAAK,YAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,KAAK,IAAIA,EAAK,OAAO,KAEnC,OAAOA,EAAK,aAAc,YAAYA,EAAK,YACvC,IAAIA,EAAK,UAAU,KAAK,CA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O,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"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-IBL_jd5R.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(){return`${String(Date.now())}000000`}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function i(e,t){if(e.length<=t)return e;let n=a(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function a(e){return e>=55296&&e<=56319}function o(e){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(`.`)}`:``}]`}function s(e,t,n){return c(e,t,n).value}function c(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:u(e,t,new WeakSet,0,r),bytes:r.bytes}}function l(e,t){return t.bytes+=d(e)+2,e}function u(e,t,n,r,a){if(a.nodes++,a.nodes>t.maxNodes)return l(`[MaxNodes]`,a);if(e==null)return a.bytes+=4,e;if(typeof e==`string`)return l(i(e,t.maxAttributeChars),a);if(typeof e==`number`)return a.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return a.bytes+=5,e;if(typeof e==`bigint`)return l(`${e.toString()}n`,a);if(typeof e==`symbol`)return l(e.toString(),a);if(typeof e==`function`)return l(`[Function ${e.name===``?`anonymous`:e.name}]`,a);if(r>=t.maxDepth)return l(`[MaxDepth]`,a);if(n.has(e))return l(`[Circular]`,a);n.add(e),a.bytes+=2;try{if(e instanceof Error)return{name:l(e.name,a),message:l(i(e.message,t.maxAttributeChars),a),stack:e.stack?l(i(e.stack,t.maxStackChars),a):void 0,cause:e.cause?u(e.cause,t,n,r+1,a):void 0};if(e instanceof Date)return l(e.toISOString(),a);if(e instanceof RegExp)return l(e.toString(),a);if(e instanceof Map){let i=e,o={},s=0;for(let[e,c]of i){if(s>=t.maxArrayLength){o[`…`]=l(`[${String(i.size-t.maxArrayLength)} more entries]`,a);break}s++;let f=String(e);a.bytes+=d(f)+4,o[f]=u(c,t,n,r+1,a)}return o}if(e instanceof Set)return u([...e].slice(0,t.maxArrayLength),t,n,r,a);if(ArrayBuffer.isView(e)){let t=e.length??0;return l(`[${e.constructor.name}(${String(t)})]`,a)}if(e instanceof Promise)return l(`[Promise]`,a);if(typeof Node<`u`&&e instanceof Node)return l(o(e),a);if(Array.isArray(e)){let i=e,o=i.slice(0,t.maxArrayLength).map(e=>u(e,t,n,r+1,a));return i.length>t.maxArrayLength&&o.push(l(`[${String(i.length-t.maxArrayLength)} more items]`,a)),o}let s=e.toJSON;if(typeof s==`function`)return u(s.call(e),t,n,r+1,a);let c=e,f=Object.keys(c),p={},m=0;for(let e of f){if(m>=t.maxAttributeCount){p[`…`]=l(`[${String(f.length-m)} more keys]`,a);break}m++,a.bytes+=d(e)+4,p[e]=u(c[e],t,n,r+1,a)}return p}catch(e){return a.diagnostics.count(`record.sanitize_failed`),l(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,a)}finally{n.delete(e)}}function d(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}var f={local:()=>localStorage,session:()=>sessionStorage};function p(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function m(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function h(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return m(16)}function g(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function _(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function v(t,n=f){let r=h(t),i=Date.now(),a=h(t),o=g(n,`local`,e.Ut,t);if(o)try{let e=JSON.parse(o);e.id&&i-(e.lastSeenAt??0)<18e5&&(a=e.id)}catch{t.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`)}let s=JSON.stringify({id:a,lastSeenAt:i});_(n,`local`,e.Ut,s,t);let c=g(n,`session`,`ui-observability.tab`,t)??``;return c||(c=h(t),_(n,`session`,e.tn,c,t)),{sessionId:a,tabId:c,contextId:r}}function y(t,n,r){_(r,`session`,e.tn,t,n)}var b=class{diagnostics;stores;lastTouchAt=0;constructor(e,t=f){this.diagnostics=e,this.stores=t}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});_(this.stores,`local`,e.Ut,r,this.diagnostics)}};function x(e,n){let r,i=new Promise((e,i)=>{let a=setTimeout(()=>{i(Error(`The operation took longer than ${String(n)} ms.`))},n);r=a,t.t(a)});return Promise.race([e,i]).finally(()=>{clearTimeout(r)})}function S(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function C(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function w(e,t){let{rates:n,defaultRate:r}=t.sampling,i,a=-1;for(let[t,r]of Object.entries(n))(e===t||e.startsWith(`${t}.`))&&t.length>a&&(i=r,a=t.length);return i??r}function T(t,n){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let r=w(t.namespace,n);return r>=1?!0:r<=0?!1:S(t.journeyId||t.traceId)/e.sn<r}function E(t,n){return T({level:t.severityText,type:C(t,e.l),namespace:C(t,e.n),journeyId:C(t,e.a),traceId:t.traceId},n)}var D=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return m}});
2
- //# sourceMappingURL=sampling-Cs50xsZl.cjs.map