@utk09/ui-observability 0.9.1 → 0.9.3

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 (172) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +75 -64
  3. package/dist/batch-D5qvsMQ_.cjs +2 -0
  4. package/dist/batch-D5qvsMQ_.cjs.map +1 -0
  5. package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
  6. package/dist/batch-DDgxg16_.js.map +1 -0
  7. package/dist/bus/bus.d.ts +0 -4
  8. package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
  9. package/dist/bus-C6RwKzPW.js.map +1 -0
  10. package/dist/bus-WPVDFw2y.cjs +2 -0
  11. package/dist/bus-WPVDFw2y.cjs.map +1 -0
  12. package/dist/capture/network.d.ts +2 -0
  13. package/dist/capture/storm.d.ts +2 -7
  14. package/dist/capture/types.d.ts +3 -0
  15. package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
  16. package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
  17. package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
  18. package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
  19. package/dist/constants-Cb92egPS.cjs +2 -0
  20. package/dist/constants-Cb92egPS.cjs.map +1 -0
  21. package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
  22. package/dist/constants-DhH6VI5a.js.map +1 -0
  23. package/dist/constants.d.ts +28 -3
  24. package/dist/core/breadcrumbs.d.ts +1 -3
  25. package/dist/core/context.d.ts +0 -8
  26. package/dist/core/diagnostics.d.ts +1 -3
  27. package/dist/core/meter.d.ts +45 -0
  28. package/dist/core/pipeline.d.ts +5 -12
  29. package/dist/core/record.d.ts +7 -0
  30. package/dist/core/runtime.d.ts +17 -0
  31. package/dist/core/sampling.d.ts +3 -3
  32. package/dist/core/sender.d.ts +2 -0
  33. package/dist/deadline-CUrH0Hd8.cjs +2 -0
  34. package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
  35. package/dist/deadline-DeqXEliN.js +31 -0
  36. package/dist/deadline-DeqXEliN.js.map +1 -0
  37. package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
  38. package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
  39. package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
  40. package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
  41. package/dist/fixed-window-BR0bu32Y.cjs +2 -0
  42. package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
  43. package/dist/fixed-window-Re7jIRJH.js +9 -0
  44. package/dist/fixed-window-Re7jIRJH.js.map +1 -0
  45. package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
  46. package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
  47. package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
  48. package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
  49. package/dist/index.cjs +1 -1
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +522 -369
  53. package/dist/index.js.map +1 -1
  54. package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
  55. package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
  56. package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
  57. package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
  58. package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
  59. package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
  60. package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
  61. package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
  62. package/dist/journey-BRUj0hqD.cjs +2 -0
  63. package/dist/journey-BRUj0hqD.cjs.map +1 -0
  64. package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
  65. package/dist/journey-yALMEWF7.js.map +1 -0
  66. package/dist/library-request-BcAxuwsf.cjs +2 -0
  67. package/dist/library-request-BcAxuwsf.cjs.map +1 -0
  68. package/dist/library-request-CQD4HUiP.js +25 -0
  69. package/dist/library-request-CQD4HUiP.js.map +1 -0
  70. package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
  71. package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
  72. package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
  73. package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
  74. package/dist/models/batch.d.ts +6 -0
  75. package/dist/models/config.d.ts +23 -0
  76. package/dist/models/metric.d.ts +50 -0
  77. package/dist/network--GoE7_Or.js +211 -0
  78. package/dist/network--GoE7_Or.js.map +1 -0
  79. package/dist/network-DcuS2H1P.cjs +2 -0
  80. package/dist/network-DcuS2H1P.cjs.map +1 -0
  81. package/dist/openfin-BwEN0uj4.js +8 -0
  82. package/dist/openfin-BwEN0uj4.js.map +1 -0
  83. package/dist/openfin-DtH2f7zX.cjs +2 -0
  84. package/dist/openfin-DtH2f7zX.cjs.map +1 -0
  85. package/dist/platform-GaM6h7XM.js +52 -0
  86. package/dist/platform-GaM6h7XM.js.map +1 -0
  87. package/dist/platform-kIL5AZB7.cjs +2 -0
  88. package/dist/platform-kIL5AZB7.cjs.map +1 -0
  89. package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
  90. package/dist/remote-rules-6ePq8CrI.js.map +1 -0
  91. package/dist/remote-rules-CI3gbRCL.cjs +2 -0
  92. package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
  93. package/dist/sampling-C-M8p3FK.cjs +2 -0
  94. package/dist/sampling-C-M8p3FK.cjs.map +1 -0
  95. package/dist/sampling-Ud_WiuU9.js +65 -0
  96. package/dist/sampling-Ud_WiuU9.js.map +1 -0
  97. package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
  98. package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
  99. package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
  100. package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
  101. package/dist/sender-BESHz6my.cjs +3 -0
  102. package/dist/sender-BESHz6my.cjs.map +1 -0
  103. package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
  104. package/dist/sender-BUBWLn5i.js.map +1 -0
  105. package/dist/storage/gap.d.ts +20 -0
  106. package/dist/storage/indexeddb-storage.d.ts +1 -7
  107. package/dist/storage/keys.d.ts +9 -0
  108. package/dist/storage/local-storage.d.ts +0 -6
  109. package/dist/storage/memory-storage.d.ts +1 -1
  110. package/dist/storm-DhHGHhOc.cjs +2 -0
  111. package/dist/storm-DhHGHhOc.cjs.map +1 -0
  112. package/dist/storm-OD5J6Ylm.js +10 -0
  113. package/dist/storm-OD5J6Ylm.js.map +1 -0
  114. package/dist/transport/custom-transport.d.ts +3 -2
  115. package/dist/transport/exit-flush.d.ts +13 -2
  116. package/dist/transport/http-transport.d.ts +6 -4
  117. package/dist/transport/retry-engine.d.ts +3 -1
  118. package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
  119. package/dist/transport/serializers/otlp.d.ts +30 -0
  120. package/dist/transport/serializers/select.d.ts +20 -4
  121. package/dist/transport/status-transport.d.ts +19 -11
  122. package/dist/utils/fixed-window.d.ts +15 -0
  123. package/dist/utils/guards.d.ts +6 -0
  124. package/dist/utils/library-request.d.ts +12 -0
  125. package/dist/utils/openfin.d.ts +48 -0
  126. package/dist/utils/platform.d.ts +5 -0
  127. package/package.json +2 -3
  128. package/dist/batch-DEK4bv9N.js.map +0 -1
  129. package/dist/batch-DEVFs28i.cjs +0 -2
  130. package/dist/batch-DEVFs28i.cjs.map +0 -1
  131. package/dist/bus-DNFvTkif.cjs +0 -2
  132. package/dist/bus-DNFvTkif.cjs.map +0 -1
  133. package/dist/bus-HVQ8E72V.js.map +0 -1
  134. package/dist/constants-N99w84xy.js.map +0 -1
  135. package/dist/constants-X86IDwkC.cjs +0 -2
  136. package/dist/constants-X86IDwkC.cjs.map +0 -1
  137. package/dist/deadline-5_PecIl5.js +0 -26
  138. package/dist/deadline-5_PecIl5.js.map +0 -1
  139. package/dist/deadline-XSnm95pg.cjs +0 -2
  140. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  141. package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
  142. package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
  143. package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
  144. package/dist/journey-DjvDzHyp.js.map +0 -1
  145. package/dist/journey-DxlfdFJV.cjs +0 -2
  146. package/dist/journey-DxlfdFJV.cjs.map +0 -1
  147. package/dist/library-request-BZ1ekVtl.cjs +0 -2
  148. package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
  149. package/dist/library-request-C8kc5YWv.js +0 -14
  150. package/dist/library-request-C8kc5YWv.js.map +0 -1
  151. package/dist/network-51iicpLl.js +0 -174
  152. package/dist/network-51iicpLl.js.map +0 -1
  153. package/dist/network-jBbjyAJP.cjs +0 -2
  154. package/dist/network-jBbjyAJP.cjs.map +0 -1
  155. package/dist/platform-Cjts-8k8.js +0 -48
  156. package/dist/platform-Cjts-8k8.js.map +0 -1
  157. package/dist/platform-DW3GFIUE.cjs +0 -2
  158. package/dist/platform-DW3GFIUE.cjs.map +0 -1
  159. package/dist/remote-rules-ByS34k4e.cjs +0 -2
  160. package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
  161. package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
  162. package/dist/sampling-BN3Oi6SV.js +0 -63
  163. package/dist/sampling-BN3Oi6SV.js.map +0 -1
  164. package/dist/sampling-b2ck5X98.cjs +0 -2
  165. package/dist/sampling-b2ck5X98.cjs.map +0 -1
  166. package/dist/sender-BBY0IcUo.js.map +0 -1
  167. package/dist/sender-BXoAZKum.cjs +0 -3
  168. package/dist/sender-BXoAZKum.cjs.map +0 -1
  169. package/dist/storm-CKuaBp7i.cjs +0 -2
  170. package/dist/storm-CKuaBp7i.cjs.map +0 -1
  171. package/dist/storm-DhtL2eVr.js +0 -10
  172. package/dist/storm-DhtL2eVr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants-DhH6VI5a.js","names":["LIBRARY_LOG_PREFIX","DIAGNOSTIC_THROTTLE_MS","SESSION_ID_KEY","TAB_ID_KEY","SESSION_IDLE_MS","SESSION_TOUCH_MS","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","WEBKIT_UA_TOKEN","SAFARI_UA_TOKEN","HIGH_SURROGATE_MIN","HIGH_SURROGATE_MAX","UTF8_TWO_BYTE_CEILING","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_ERROR_DATA","ATTR_BREADCRUMBS","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","HEADER_SAMPLING","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","LEVEL_BYPASS_TYPES","LOG_TYPE_METRIC","LOG_TYPE_ACTION","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","LIBRARY_REQUEST_KEY","LIBRARY_CONSOLE_KEY","TRANSPORT_CALL_KEY","ERROR_STORM_WINDOW_MS","CONSOLE_DEFAULT_STYLES","DURATION_PRECISION","GAP_REPORT_THROTTLE_MS","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DEFAULT_METRIC_UNIT","METRIC_NAMESPACE","ATTR_METRIC_OVERFLOW","METRIC_DEFAULT_BOUNDARIES","METRIC_KEYS","UNKNOWN_SERVICE_NAME","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","REMOTE_SAMPLING_POLL_MS","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","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","BUS_MAX_BOOT_BUFFER_ACTIONS","ERROR_DEDUPE_MS","RECORD_LIMITS","DEFAULT_CONFIG"],"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 library built the record. */\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/** Own fields of an Error reason, or the whole reason when it is not an Error. */\nexport const ATTR_ERROR_DATA = \"error.data\";\n\n/** Breadcrumb history of an error record. */\nexport const ATTR_BREADCRUMBS = \"breadcrumbs\";\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 build writes the version of package.json here.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = __UIOBS_VERSION__;\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 in decimal digits, for example \"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/** Response header that carries sampling rules from the ingest server. */\nexport const HEADER_SAMPLING = \"X-UiObs-Sampling\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** Lowest valid HTTP status code. */\nexport const HTTP_STATUS_MIN = 100;\n\n/** Highest valid HTTP status code. */\nexport const HTTP_STATUS_MAX = 599;\n\n/** Lowest HTTP status code that accepts a batch. */\nexport const HTTP_SUCCESS_MIN = 200;\n\n/** Lowest HTTP status code above the success range. */\nexport const HTTP_SUCCESS_END = 300;\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/** Maximum number of exit batches in the emergency queue. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key that the library writes to test if 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/** Name of the storage adapter that keeps nothing. */\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 * Types that minLevel does not drop. An action is an audit fact and a metric is a measurement.\n * The remote rate cap for records below minLevel does not apply to them.\n */\nexport const LEVEL_BYPASS_TYPES: readonly LogType[] = [\"action\", \"metric\"];\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Record kind of an audit fact. Storage and the hold buffers drop it last. */\nexport const LOG_TYPE_ACTION: LogType = \"action\";\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/** Global symbol key of the library request scope count. All library copies on a page share it. */\nexport const LIBRARY_REQUEST_KEY = \"ui-observability.request-scope\";\n\n/** Global symbol key of the library console scope count. All library copies on a page share it. */\nexport const LIBRARY_CONSOLE_KEY = \"ui-observability.console-scope\";\n\n/** Global symbol key of the count of custom transport calls that wait for an answer. */\nexport const TRANSPORT_CALL_KEY = \"ui-observability.transport-calls\";\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/** Default minimum duration of a long frame that the library records, in milliseconds. */\nexport const LONG_FRAME_THRESHOLD_MS = 100;\n\n/** Maximum long frames recorded in each storm window. A frozen tab cannot flood the pipeline. */\nexport const LONG_FRAME_MAX_PER_WINDOW = 20;\n\n/** Maximum character length of a console breadcrumb message. */\nexport const CONSOLE_BREADCRUMB_MAX_CHARS = 200;\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/** Measurement unit that the library uses when the call gives no unit. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n/** Namespace of the points that the counter and histogram instruments give. */\nexport const METRIC_NAMESPACE = \"uiobs.metrics\";\n\n/** Maximum attribute sets of one instrument in one interval. More sets go to one overflow set. */\nexport const METRIC_MAX_SERIES = 100;\n\n/** Maximum bucket boundaries of one histogram. More boundaries make a large point. */\nexport const METRIC_MAX_BOUNDARIES = 50;\n\n/** Attribute of the overflow set. OpenTelemetry uses the same key. */\nexport const ATTR_METRIC_OVERFLOW = \"otel.metric.overflow\";\n\n/** Default histogram boundaries. They are the OpenTelemetry default boundaries. */\nexport const METRIC_DEFAULT_BOUNDARIES: readonly number[] = [\n 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000,\n];\n\n/**\n * Attribute keys of an aggregated metric point. The OTLP metrics serializer reads them.\n * Sampling keeps each record with a start time. A sample of a sum gives a false sum.\n */\nexport const METRIC_KEYS = {\n start: \"metric.start_time_unix_nano\",\n attributeKeys: \"metric.attribute_keys\",\n count: \"metric.count\",\n sum: \"metric.sum\",\n min: \"metric.min\",\n max: \"metric.max\",\n bounds: \"metric.bounds\",\n buckets: \"metric.bucket_counts\",\n} as const;\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/** Version of the remote sampling rules that the library accepts. */\nexport const REMOTE_SAMPLING_VERSION = 1;\n\n/** Maximum length of the sampling header, in characters. */\nexport const REMOTE_SAMPLING_MAX_CHARS = 4096;\n\n/** Maximum time that remote sampling rules stay in force, in milliseconds. */\nexport const REMOTE_SAMPLING_MAX_TTL_MS = 60 * 60 * 1000;\n\n/** Maximum namespace rates in one set of remote sampling rules. */\nexport const REMOTE_SAMPLING_MAX_RATES = 100;\n\n/** Time between two requests of a forwarder for the remote sampling rules, in milliseconds. */\nexport const REMOTE_SAMPLING_POLL_MS = 30_000;\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 \"onDrop\",\n \"headers\",\n \"serializer\",\n \"otelLoader\",\n \"transport\",\n \"transportOnExit\",\n] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"sampling\",\n \"bus\",\n \"journey\",\n \"batching\",\n \"retention\",\n \"limits\",\n \"capture\",\n] 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 journey: [],\n batching: [],\n retention: [],\n limits: [],\n capture: [\"webVitalsLoader\"],\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/** True if the journey ends for all contexts when the owning context closes. */\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 that are not actions in one hold buffer. A full buffer drops the oldest. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n/** Max action records in one hold buffer. Actions have their own cap. A log storm cannot push one out. */\nexport const BUS_MAX_BOOT_BUFFER_ACTIONS = 2000;\n\n/** Max different values in each list of an onDrop summary. */\nexport const DROP_SUMMARY_MAX_ITEMS = 20;\n\n/** Max characters of an untrusted message type in a diagnostic detail. The sender sets the text. */\nexport const BUS_TYPE_DETAIL_MAX_CHARS = 32;\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\n// ----------------------------------\n// Config defaults\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 * It comes after the constants that it reads. A const cannot be read before its line.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n metricsEndpoint: \"\",\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: {\n defaultRate: 1,\n rates: {},\n alwaysSampleTypes: [\"action\"],\n remote: false,\n remoteMaxRate: 1,\n },\n bus: { mode: \"auto\", trustedOrigins: [], openFinRole: \"auto\" },\n journey: { scope: \"auto\", maxAgeMs: JOURNEY_MAX_AGE_MS },\n batching: {\n logFlushIntervalMs: LOG_FLUSH_INTERVAL_MS,\n logBatchSize: LOG_BATCH_SIZE,\n metricFlushIntervalMs: METRIC_FLUSH_INTERVAL_MS,\n metricBatchSize: METRIC_BATCH_SIZE,\n },\n retention: { mode: \"limited\", ...STORAGE_LIMITS },\n limits: { ...RECORD_LIMITS },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n httpMetrics: true,\n interactions: false,\n navigation: false,\n webVitals: false,\n longFrames: false,\n longFrameThresholdMs: LONG_FRAME_THRESHOLD_MS,\n console: false,\n fullUrls: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n },\n console: { level: null, styles: CONSOLE_DEFAULT_STYLES },\n};\n"],"mappings":";AAcA,IAAaA,KAAqB,sBAUrBC,KAAyB,KAOzBC,IAAiB,4BAGjBC,KAAa,wBAGbC,KAAkB,MAGlBC,KAAmB,KAanBC,IAAqB,YAGrBC,IAA6B,UAG7BC,IAAwB,0BAGxBC,IAAuB,iBAGvBC,IAAoB,cAGpBC,IAAkB,eAGlBC,IAAkB,WAOlBC,IAAqB,OAGrBC,IAAqB,OAMrBC,IAAwB,MA+BxBC,IAA4C;CACvD,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT,GAMaC,IAAwCD,GAUxCE,IAAgB,YAGhBC,IAAe,WAGfC,IAAqB,iBAGrBC,IAAgB,YAOhBC,IAAgB,YAGhBC,IAAkB,cAGlBC,IAAoB,gBAGpBC,IAAyB,qBAGzBC,IAAuB,yBAGvBC,IAAkB,cAGlBC,IAAmB,eAMnBC,IAA0B,4BAM1BC,IAAwB,0BAGxBC,IAAwB,gBAGxBC,IAA2B,mBAG3BC,IAAkC,0BAMlCC,IAA8B,sBAM9BC,IAAiC,yBAMjCC,IAAkC,0BAGlCC,IAAyB,iBAGzBC,IAAsB,cAGtBC,IAAkB,UAGlBC,IAAsB,cAGtBC,IAA8B,sBAG9BC,IAAwB,gBAGxBC,IAAwB,gBAMxBC,IAAqB,2BAMrBC,IAAA,SAMAC,IAAyB,SAOzBC,IAAuB,QAUvBC,IAAqD,EAAE,MAAM,UAAU,GAGvEC,IAAoB,oBAGpBC,IAAsB,wBAGtBC,IAAkB,UAMlBC,IAAgB,SAOhBC,IAAsB,gBAGtBC,IAA0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R,YAAY;EACZ,gBAAgB;EAChB,OAAO;EACP,KAAK;EACL,aAAa;EACb,cAAc;EACd,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,sBAAA;EACA,SAAS;EACT,UAAU;EACV,YAAY,CAAC;EACb,wBAAwB,CAAC;CAC3B;CACA,SAAS;EAAE,OAAO;EAAM,QAAQlC;CAAuB;AACzD"}
@@ -143,11 +143,10 @@ export declare const RESOURCE_OPENFIN_NAME = "openfin.name";
143
143
  */
144
144
  export declare const TELEMETRY_SDK_NAME = "@utk09/ui-observability";
145
145
  /**
146
- * Value of `telemetry.sdk.version`. The code does not read it from package.json.
147
- * Change it by hand when you change the version in package.json.
146
+ * Value of `telemetry.sdk.version`. The build writes the version of package.json here.
148
147
  * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}
149
148
  */
150
- export declare const TELEMETRY_SDK_VERSION = "0.9.1";
149
+ export declare const TELEMETRY_SDK_VERSION: string;
151
150
  /**
152
151
  * Value of `telemetry.sdk.language`.
153
152
  * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}
@@ -348,6 +347,8 @@ export declare const RUNTIME_STOPPED_KEY = "ui-observability.stopped";
348
347
  export declare const LIBRARY_REQUEST_KEY = "ui-observability.request-scope";
349
348
  /** Global symbol key of the library console scope count. All library copies on a page share it. */
350
349
  export declare const LIBRARY_CONSOLE_KEY = "ui-observability.console-scope";
350
+ /** Global symbol key of the count of custom transport calls that wait for an answer. */
351
+ export declare const TRANSPORT_CALL_KEY = "ui-observability.transport-calls";
351
352
  /** Maximum error records captured per throttling window before suppression. */
352
353
  export declare const ERROR_STORM_MAX_PER_WINDOW = 20;
353
354
  /** Error rate-limiting window duration in milliseconds. */
@@ -384,6 +385,30 @@ export declare const CAPTURE_NAMESPACE = "uiobs.capture";
384
385
  export declare const STORAGE_NAMESPACE = "uiobs.storage";
385
386
  /** Measurement unit that the library uses when the call gives no unit. */
386
387
  export declare const DEFAULT_METRIC_UNIT = "count";
388
+ /** Namespace of the points that the counter and histogram instruments give. */
389
+ export declare const METRIC_NAMESPACE = "uiobs.metrics";
390
+ /** Maximum attribute sets of one instrument in one interval. More sets go to one overflow set. */
391
+ export declare const METRIC_MAX_SERIES = 100;
392
+ /** Maximum bucket boundaries of one histogram. More boundaries make a large point. */
393
+ export declare const METRIC_MAX_BOUNDARIES = 50;
394
+ /** Attribute of the overflow set. OpenTelemetry uses the same key. */
395
+ export declare const ATTR_METRIC_OVERFLOW = "otel.metric.overflow";
396
+ /** Default histogram boundaries. They are the OpenTelemetry default boundaries. */
397
+ export declare const METRIC_DEFAULT_BOUNDARIES: readonly number[];
398
+ /**
399
+ * Attribute keys of an aggregated metric point. The OTLP metrics serializer reads them.
400
+ * Sampling keeps each record with a start time. A sample of a sum gives a false sum.
401
+ */
402
+ export declare const METRIC_KEYS: {
403
+ readonly start: "metric.start_time_unix_nano";
404
+ readonly attributeKeys: "metric.attribute_keys";
405
+ readonly count: "metric.count";
406
+ readonly sum: "metric.sum";
407
+ readonly min: "metric.min";
408
+ readonly max: "metric.max";
409
+ readonly bounds: "metric.bounds";
410
+ readonly buckets: "metric.bucket_counts";
411
+ };
387
412
  /** Default `service.name` when a consumer sets none. */
388
413
  export declare const UNKNOWN_SERVICE_NAME = "unknown-service";
389
414
  /** Lowest sampling rate (drop everything). */
@@ -14,7 +14,7 @@ export interface Breadcrumb {
14
14
  /** Ring buffer of fixed size. It keeps recent breadcrumbs in time order. */
15
15
  export declare class BreadcrumbBuffer {
16
16
  /** Storage array of the ring buffer. */
17
- private buffer;
17
+ private readonly buffer;
18
18
  /** Next write index in the circular buffer. */
19
19
  private pointer;
20
20
  /**
@@ -38,6 +38,4 @@ export declare class BreadcrumbBuffer {
38
38
  * @returns List of breadcrumbs in time order.
39
39
  */
40
40
  snapshot(): Breadcrumb[];
41
- /** Removes all breadcrumbs and resets the buffer. */
42
- clear(): void;
43
41
  }
@@ -13,19 +13,11 @@ export declare class ContextStore {
13
13
  * @param values Record of attributes to merge.
14
14
  */
15
15
  setMany(values: Record<string, unknown>): void;
16
- /**
17
- * Retrieves an attribute value by key.
18
- * @param key Attribute key.
19
- * @returns Stored attribute value or undefined if not set.
20
- */
21
- get(key: string): unknown;
22
16
  /**
23
17
  * Deletes an attribute from the ambient context store.
24
18
  * @param key Attribute key to remove.
25
19
  */
26
20
  remove(key: string): void;
27
- /** Clears all attributes from the ambient context store. */
28
- clear(): void;
29
21
  /**
30
22
  * Returns a copy of all ambient context attributes. The copy prevents a merge
31
23
  * target or a sanitizer from changing the store.
@@ -1,5 +1,5 @@
1
1
  /** Closed set of diagnostic event codes emitted by library subsystems. */
2
- export type DiagnosticCode = "config.invalid" | "config.reconfigured" | "record.sanitize_failed" | "record.truncated" | "record.dropped_by_level" | "record.dropped_by_sampling" | "record.dropped_by_ceiling" | "record.dropped_by_redact" | "record.dropped_boot_buffer_full" | "record.dropped_malformed" | "record.dropped_no_destination" | "runtime.version_mismatch" | "journey.expired" | "journey.adopted" | "journey.token_too_large" | "trace.otel_failed" | "bus.role_resolved" | "bus.no_owner" | "bus.handshake_timeout" | "bus.untrusted_origin" | "bus.send_failed" | "transport.http_error" | "transport.timeout" | "transport.batch_split" | "transport.throttled" | "transport.dropped_permanent" | "transport.rejected_credentials" | "transport.serialize_failed" | "storage.unavailable" | "storage.degraded" | "storage.quota_exceeded" | "storage.evicted" | "storage.dead_lettered" | "pipeline.crashed" | "capture.install_failed" | "capture.rate_limited" | "capture.header_failed" | "capture.record_failed" | "openfin.unavailable" | "platform.api_blocked" | "handler.threw";
2
+ export type DiagnosticCode = "config.invalid" | "config.reconfigured" | "record.sanitize_failed" | "record.truncated" | "record.dropped_by_level" | "record.dropped_by_sampling" | "record.dropped_by_ceiling" | "record.dropped_by_redact" | "record.dropped_boot_buffer_full" | "record.dropped_malformed" | "record.dropped_no_destination" | "runtime.version_mismatch" | "journey.expired" | "journey.adopted" | "journey.token_too_large" | "trace.otel_failed" | "bus.role_resolved" | "bus.no_owner" | "bus.handshake_timeout" | "bus.untrusted_origin" | "bus.send_failed" | "transport.http_error" | "transport.timeout" | "transport.batch_split" | "transport.throttled" | "transport.dropped_permanent" | "transport.rejected_credentials" | "transport.serialize_failed" | "storage.unavailable" | "storage.degraded" | "storage.quota_exceeded" | "storage.evicted" | "storage.dead_lettered" | "pipeline.crashed" | "capture.install_failed" | "capture.rate_limited" | "capture.header_failed" | "capture.record_failed" | "capture.transport_request" | "openfin.unavailable" | "platform.api_blocked" | "handler.threw";
3
3
  /** Diagnostic event payload dispatched to consumer handlers. */
4
4
  export interface DiagnosticEvent {
5
5
  /** Diagnostic fault code. */
@@ -72,6 +72,4 @@ export declare class Diagnostics {
72
72
  * @returns Map of diagnostic codes to occurrence counts.
73
73
  */
74
74
  snapshot(): Record<string, number>;
75
- /** Clears all counters and throttling history. */
76
- reset(): void;
77
75
  }
@@ -0,0 +1,45 @@
1
+ import type { InstrumentDef, MetricAttributes } from "../models/metric";
2
+ import type { Diagnostics } from "./diagnostics";
3
+ /** Sums the values of the counter and histogram instruments for one interval. */
4
+ export declare class Meter {
5
+ private readonly intervalMs;
6
+ private readonly emit;
7
+ private readonly diagnostics;
8
+ /** Instruments with a value in the current interval. */
9
+ private readonly instruments;
10
+ /** Timer of the current interval. It runs only while a value waits. */
11
+ private timer;
12
+ /** Time of the first value of the interval, in epoch milliseconds. */
13
+ private startedAt;
14
+ /**
15
+ * @param intervalMs Gives the interval length, in milliseconds.
16
+ * @param emit Builds and sends the record of one point from the call attributes and the
17
+ * metric fields.
18
+ * @param diagnostics Diagnostics reporter.
19
+ */
20
+ constructor(intervalMs: () => number, emit: (name: string, attributes: MetricAttributes, fields: Record<string, unknown>) => void, diagnostics: Diagnostics);
21
+ /**
22
+ * Adds a value to the series of its attribute set. It never throws into the call of the app.
23
+ * @param def Definition of the instrument.
24
+ * @param value Value to add.
25
+ * @param attributes Attribute set of the value.
26
+ */
27
+ record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void;
28
+ /** Sends one point for each series of the interval. It then starts a new interval. */
29
+ collect(): void;
30
+ /**
31
+ * Finds the instrument of the interval. The first value of the interval sets its definition.
32
+ * @param def Definition of the call.
33
+ * @returns The instrument, or null when the name has another kind.
34
+ */
35
+ private instrumentOf;
36
+ /**
37
+ * Adds a value to the series of an attribute set.
38
+ * @param instrument Instrument of the value.
39
+ * @param value Value to add.
40
+ * @param attributes Clean attribute set.
41
+ */
42
+ private add;
43
+ /** Starts the timer of the interval at its first value. An idle meter has no timer. */
44
+ private arm;
45
+ }
@@ -49,21 +49,14 @@ export declare class LogPipeline {
49
49
  */
50
50
  push(record: LogRecord): void;
51
51
  /**
52
- * Drains the stream buffers into one batch. It does not take in-flight batches.
53
- * An in-flight batch has its own ID and its send is not complete. If this method
54
- * takes it, the pipeline sends each record again under a new ID. The server cannot
55
- * deduplicate that ID.
56
- * @returns Combined LogBatch, or null if the buffers hold no records.
57
- */
58
- drainPending(): LogBatch | null;
59
- /**
60
- * Drains all buffered and unconfirmed in-flight records into one exit batch in one step.
52
+ * Drains all buffered and unconfirmed in-flight records into exit batches in one step.
61
53
  * Records already given to fetch go again under a new batch ID. The server cannot
62
54
  * deduplicate them. Thus the exit flush can deliver duplicates. This is intentional.
63
55
  * A closing document cannot confirm delivery.
64
- * @returns Combined LogBatch or null if no records are pending.
56
+ * @returns One batch of metric records and one batch of other records. A kind with no
57
+ * records has no batch. A mixed batch sends a metric to the endpoint of the logs.
65
58
  */
66
- drainForExit(): LogBatch | null;
59
+ drainForExit(): LogBatch[];
67
60
  /**
68
61
  * Sends the buffered records through the normal dispatch path. Then it waits for each
69
62
  * batch in the queue and in flight. The throttle check and the concurrency limit apply.
@@ -89,7 +82,7 @@ export declare class LogPipeline {
89
82
  private route;
90
83
  /**
91
84
  * Drains a stream buffer into a new batch and queues the batch for dispatch.
92
- * The buffer always has one or more records here. Only a push starts a timer.
85
+ * A timer or a flush calls it. An empty buffer gives no batch.
93
86
  * Each `take` stops the timer that calls this method.
94
87
  * @param stream Stream buffer to drain.
95
88
  */
@@ -65,6 +65,13 @@ export interface BuildInput {
65
65
  scoped?: Record<string, unknown>;
66
66
  /** Call-site payload attributes. */
67
67
  payload?: Record<string, unknown>;
68
+ /**
69
+ * Fields that the library builds with a fixed size bound, for example the buckets of a point.
70
+ * The record limits do not cut them. They override a payload key of the same name.
71
+ */
72
+ fixed?: Record<string, unknown>;
73
+ /** True for a point of a counter or histogram. Sampling keeps it. */
74
+ aggregated?: boolean;
68
75
  }
69
76
  /** Builds validated and sanitized LogRecord instances from logger inputs. */
70
77
  export declare class RecordBuilder {
@@ -1,6 +1,7 @@
1
1
  import type { Receive, WorkerLike } from "../bus/links";
2
2
  import type { BusMessage } from "../models/bus";
3
3
  import type { ObservabilityConfig, ResolvedConfig } from "../models/config";
4
+ import type { InstrumentDef, MetricAttributes } from "../models/metric";
4
5
  import { type LogRecord } from "../models/log-record";
5
6
  import { ConsoleSink } from "../utils/console";
6
7
  import { type Identity } from "../utils/identity";
@@ -57,6 +58,8 @@ export declare class ObservabilityRuntime {
57
58
  readonly console: ConsoleSink;
58
59
  /** Collects lost records into onDrop summaries. */
59
60
  private readonly drops;
61
+ /** Sums the values of the counter and histogram instruments. */
62
+ private readonly meter;
60
63
  /**
61
64
  * Cross-realm communication bus. It is null until its chunk loads.
62
65
  * In bus.mode "off", it loads only when a child frame or a worker needs it.
@@ -108,6 +111,20 @@ export declare class ObservabilityRuntime {
108
111
  * no capture.
109
112
  */
110
113
  private constructor();
114
+ /**
115
+ * Adds a value to a counter or a histogram. The meter sends one point at each interval.
116
+ * @param def Definition of the instrument.
117
+ * @param value Value to add.
118
+ * @param attributes Attribute set of the value.
119
+ */
120
+ recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void;
121
+ /**
122
+ * Builds and emits the record of one aggregated point. The console does not print it.
123
+ * @param name Metric name.
124
+ * @param attributes Attributes of the call. The record limits apply to them.
125
+ * @param fields Metric fields of the point. The record limits do not cut them.
126
+ */
127
+ private emitPoint;
111
128
  /**
112
129
  * Receives direct messages from same-origin child frames.
113
130
  * @param message Inbound bus message.
@@ -13,6 +13,8 @@ export interface SampleInput {
13
13
  journeyId: string;
14
14
  /** Trace ID. It is the sampling key when no journey runs. */
15
15
  traceId: string;
16
+ /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */
17
+ aggregated?: boolean;
16
18
  }
17
19
  /**
18
20
  * Decides if sampling keeps an entry. It reads fields, not a record.
@@ -39,10 +41,8 @@ export declare function shouldSample(record: LogRecord, config: ResolvedConfig,
39
41
  * An example is application code that calls logger.error in a render loop.
40
42
  */
41
43
  export declare class ErrorCeiling {
42
- /** Start of the current window, in epoch milliseconds. */
43
- private windowStart;
44
44
  /** ERROR and FATAL records admitted in the current window. */
45
- private count;
45
+ private readonly window;
46
46
  /**
47
47
  * Checks a record against the limit. It counts only ERROR and FATAL records.
48
48
  * @param record Record about to enter a stream.
@@ -16,6 +16,8 @@ export interface SenderDeps {
16
16
  onLoss: LossReporter;
17
17
  /** Slot of the runtime for the sampling rules from the ingest server. */
18
18
  remote: RemoteSlot;
19
+ /** Sends the points of the open metric interval before the exit flush drains the buffers. */
20
+ beforeExit?: () => void;
19
21
  }
20
22
  /** Delivery stack for one sender runtime. */
21
23
  export declare class Sender {
@@ -0,0 +1,2 @@
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){typeof e!=`number`&&e.unref?.()}var n=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function r(e,r){let i,a=new Promise((e,a)=>{let o=setTimeout(()=>{a(new n(r))},r);i=o,t(o)});return Promise.race([e,a]).finally(()=>{clearTimeout(i)})}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
2
+ //# sourceMappingURL=deadline-CUrH0Hd8.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-CUrH0Hd8.cjs","names":["isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// 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/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\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 DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"AAUA,SAAgBA,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CCAA,SAAgBC,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAAkB,EAAwB,CACxE,IAAIC,EAEEC,EAAW,IAAI,SAAgB,EAAU,IAAW,CACxD,IAAML,EAAQ,eAAiB,CAC7BM,EAAO,IAAIL,EAAcC,CAAE,CAAC,CAC9B,EAAGA,CAAE,EAEL,EAASF,EACTD,EAAWC,CAAK,CAClB,CAAC,EAGD,OAAO,QAAQ,KAAK,CAACO,EAAMF,CAAQ,CAAC,CAAC,CAAC,YAAc,CAClD,aAAaD,CAAM,CACrB,CAAC,CACH"}
@@ -0,0 +1,31 @@
1
+ //#region src/utils/guards.ts
2
+ function e(e) {
3
+ return typeof e == "object" && !!e && !Array.isArray(e);
4
+ }
5
+ //#endregion
6
+ //#region src/utils/unref.ts
7
+ function t(e) {
8
+ typeof e != "number" && e.unref?.();
9
+ }
10
+ //#endregion
11
+ //#region src/utils/deadline.ts
12
+ var n = class extends Error {
13
+ constructor(e) {
14
+ super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
15
+ }
16
+ };
17
+ function r(e, r) {
18
+ let i, a = new Promise((e, a) => {
19
+ let o = setTimeout(() => {
20
+ a(new n(r));
21
+ }, r);
22
+ i = o, t(o);
23
+ });
24
+ return Promise.race([e, a]).finally(() => {
25
+ clearTimeout(i);
26
+ });
27
+ }
28
+ //#endregion
29
+ export { e as i, r as n, t as r, n as t };
30
+
31
+ //# sourceMappingURL=deadline-DeqXEliN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-DeqXEliN.js","names":["isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// 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/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\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 DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":";AAUA,SAAgBA,EAAS,GAAkD;CACzE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;;;ACAA,SAAgBC,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB;;;ACRA,IAAaC,IAAb,cAAmC,MAAM;CAIvC,YAAY,GAAY;EAEtB,AADA,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,GACxD,KAAK,OAAO;CACd;AACF;AAQA,SAAgBC,EAAgB,GAAkB,GAAwB;CACxE,IAAIC,GAEEC,IAAW,IAAI,SAAgB,GAAU,MAAW;EACxD,IAAML,IAAQ,iBAAiB;GAC7B,EAAO,IAAIC,EAAcC,CAAE,CAAC;EAC9B,GAAGA,CAAE;EAGL,AADA,IAASF,GACTD,EAAWC,CAAK;CAClB,CAAC;CAGD,OAAO,QAAQ,KAAK,CAACM,GAAMD,CAAQ,CAAC,CAAC,CAAC,cAAc;EAClD,aAAaD,CAAM;CACrB,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
- import "./constants-N99w84xy.js";
1
+ import "./constants-DhH6VI5a.js";
2
2
  import { r as e } from "./error-like-Ywo5uRHo.js";
3
- import { r as t } from "./platform-Cjts-8k8.js";
4
- import { t as n } from "./storm-DhtL2eVr.js";
3
+ import { i as t } from "./platform-GaM6h7XM.js";
4
+ import { t as n } from "./storm-OD5J6Ylm.js";
5
5
  //#region src/capture/errors.ts
6
6
  function r(t) {
7
7
  if (e(t)) {
@@ -91,4 +91,4 @@ var i = class {
91
91
  //#endregion
92
92
  export { i as ErrorCapture };
93
93
 
94
- //# sourceMappingURL=errors-CQusIGWJ.js.map
94
+ //# sourceMappingURL=errors-DCZWcHkd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-CQusIGWJ.js","names":["isErrorLike","stripUrlQuery","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAqCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,E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DCZWcHkd.js","names":["isErrorLike","stripUrlQuery","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAqCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,M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H;AACF"}
@@ -1,3 +1,3 @@
1
- require("./constants-X86IDwkC.cjs");const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-DW3GFIUE.cjs"),n=require("./storm-CKuaBp7i.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
2
- `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count: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(e,t,i){if(!n.t(this.window,20,this.ctx.diagnostics,`errors`))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<5e3){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
3
- //# sourceMappingURL=errors-BTWuVnHZ.cjs.map
1
+ require("./constants-Cb92egPS.cjs");const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-kIL5AZB7.cjs"),n=require("./storm-DhHGHhOc.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
2
+ `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count: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.i(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(e,t,i){if(!n.t(this.window,20,this.ctx.diagnostics,`errors`))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<5e3){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
3
+ //# sourceMappingURL=errors-ERu-su8m.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BTWuVnHZ.cjs","names":["isErrorLike","stripUrlQuery","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"wJAqCA,SAASM,EAAY,EAA2B,CAC9C,GAAIN,EAAAA,EAAYO,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,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,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,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMT,CAAO,EAAIS,EAC1D,KAAK,IAAI,OAAO,MAAMT,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"errors-ERu-su8m.cjs","names":["isErrorLike","stripUrlQuery","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"wJAqCA,SAASM,EAAY,EAA2B,CAC9C,GAAIN,EAAAA,EAAYO,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,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,IA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EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMT,CAAO,EAAIS,EAC1D,KAAK,IAAI,OAAO,MAAMT,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF"}
@@ -0,0 +1,2 @@
1
+ function e(e,t,n){let r=Date.now();return(r<e.start||r-e.start>n)&&(e.start=r,e.count=0),e.count++,e.count<=t}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=fixed-window-BR0bu32Y.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixed-window-BR0bu32Y.cjs","names":["countInWindow","now","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period adds no allowance. The capture modules and\n// the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param windowMs Length of the window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n // Guard against a clock that moves back. The window then never ends.\n if (now < window.start || now - window.start > windowMs) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n"],"mappings":"AAoBA,SAAgBA,EAAc,EAAqB,EAAe,EAA2B,CAC3F,IAAMC,EAAM,KAAK,IAAI,EAUrB,OAPIA,EAAMC,EAAO,OAASD,EAAMC,EAAO,MAAQC,KAC7C,EAAO,MAAQF,EACf,EAAO,MAAQ,GAGjB,EAAO,QAEAC,EAAO,OAASE,CACzB"}
@@ -0,0 +1,9 @@
1
+ //#region src/utils/fixed-window.ts
2
+ function e(e, t, n) {
3
+ let r = Date.now();
4
+ return (r < e.start || r - e.start > n) && (e.start = r, e.count = 0), e.count++, e.count <= t;
5
+ }
6
+ //#endregion
7
+ export { e as t };
8
+
9
+ //# sourceMappingURL=fixed-window-Re7jIRJH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixed-window-Re7jIRJH.js","names":["countInWindow","now","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period adds no allowance. The capture modules and\n// the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param windowMs Length of the window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n // Guard against a clock that moves back. The window then never ends.\n if (now < window.start || now - window.start > windowMs) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n"],"mappings":";AAoBA,SAAgBA,EAAc,GAAqB,GAAe,GAA2B;CAC3F,IAAMC,IAAM,KAAK,IAAI;CAUrB,QAPIA,IAAMC,EAAO,SAASD,IAAMC,EAAO,QAAQC,OAC7C,EAAO,QAAQF,GACf,EAAO,QAAQ,IAGjB,EAAO,SAEAC,EAAO,SAASE;AACzB"}