@utk09/ui-observability 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +67 -25
  3. package/dist/{bus-ChIXDAWD.cjs → bus-DeZzr2bx.cjs} +2 -2
  4. package/dist/{bus-ChIXDAWD.cjs.map → bus-DeZzr2bx.cjs.map} +1 -1
  5. package/dist/{bus-BTMuVkDk.js → bus-DfAbg_pg.js} +2 -2
  6. package/dist/{bus-BTMuVkDk.js.map → bus-DfAbg_pg.js.map} +1 -1
  7. package/dist/constants-C8nZQBmQ.js +86 -0
  8. package/dist/constants-C8nZQBmQ.js.map +1 -0
  9. package/dist/constants-IBL_jd5R.cjs +2 -0
  10. package/dist/constants-IBL_jd5R.cjs.map +1 -0
  11. package/dist/constants.d.ts +4 -4
  12. package/dist/{errors-Dwm2SzBa.js → errors-4MQyjZVj.js} +3 -3
  13. package/dist/{errors-Dwm2SzBa.js.map → errors-4MQyjZVj.js.map} +1 -1
  14. package/dist/{errors-DRXBRqvm.cjs → errors-CUdShXe7.cjs} +2 -2
  15. package/dist/{errors-DRXBRqvm.cjs.map → errors-CUdShXe7.cjs.map} +1 -1
  16. package/dist/index.cjs +1 -1
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +87 -66
  20. package/dist/index.js.map +1 -1
  21. package/dist/{indexeddb-storage-DjY4Ml6t.js → indexeddb-storage-0LtUALBg.js} +2 -2
  22. package/dist/{indexeddb-storage-DjY4Ml6t.js.map → indexeddb-storage-0LtUALBg.js.map} +1 -1
  23. package/dist/{indexeddb-storage-B5dwq4hW.cjs → indexeddb-storage-CcEJlq2l.cjs} +2 -2
  24. package/dist/{indexeddb-storage-B5dwq4hW.cjs.map → indexeddb-storage-CcEJlq2l.cjs.map} +1 -1
  25. package/dist/{interactions-DVom6eYn.cjs → interactions-BMNPQ3WH.cjs} +2 -2
  26. package/dist/{interactions-DVom6eYn.cjs.map → interactions-BMNPQ3WH.cjs.map} +1 -1
  27. package/dist/{interactions-DZmLu7l2.js → interactions-BaCmoGLB.js} +2 -2
  28. package/dist/{interactions-DZmLu7l2.js.map → interactions-BaCmoGLB.js.map} +1 -1
  29. package/dist/models/config.d.ts +30 -6
  30. package/dist/{network-CuqWadNn.cjs → network-DBNvxCE3.cjs} +2 -2
  31. package/dist/{network-CuqWadNn.cjs.map → network-DBNvxCE3.cjs.map} +1 -1
  32. package/dist/{network-C4d2uw2Z.js → network-jQ2t8rU4.js} +2 -2
  33. package/dist/{network-C4d2uw2Z.js.map → network-jQ2t8rU4.js.map} +1 -1
  34. package/dist/{platform-CXio0W2n.cjs → platform-ByQllE_W.cjs} +2 -2
  35. package/dist/{platform-CXio0W2n.cjs.map → platform-ByQllE_W.cjs.map} +1 -1
  36. package/dist/{platform-CY8S3hUs.js → platform-YuByH8A5.js} +2 -2
  37. package/dist/{platform-CY8S3hUs.js.map → platform-YuByH8A5.js.map} +1 -1
  38. package/dist/{sampling-CJsI_24L.js → sampling-CbYySsZ1.js} +2 -2
  39. package/dist/{sampling-CJsI_24L.js.map → sampling-CbYySsZ1.js.map} +1 -1
  40. package/dist/{sampling-CEthcmEX.cjs → sampling-Cs50xsZl.cjs} +2 -2
  41. package/dist/{sampling-CEthcmEX.cjs.map → sampling-Cs50xsZl.cjs.map} +1 -1
  42. package/dist/{sender-dpvR_bHM.js → sender-BIob8eZz.js} +4 -4
  43. package/dist/{sender-dpvR_bHM.js.map → sender-BIob8eZz.js.map} +1 -1
  44. package/dist/{sender-ByFAkXVd.cjs → sender-iOjzcueM.cjs} +2 -2
  45. package/dist/{sender-ByFAkXVd.cjs.map → sender-iOjzcueM.cjs.map} +1 -1
  46. package/dist/utils/console.d.ts +7 -6
  47. package/package.json +4 -2
  48. package/dist/constants-0-YchbAL.js +0 -75
  49. package/dist/constants-0-YchbAL.js.map +0 -1
  50. package/dist/constants-TUFcy95w.cjs +0 -2
  51. package/dist/constants-TUFcy95w.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"errors-Dwm2SzBa.js","names":["ERROR_STORM_WINDOW_MS","stripUrlQuery","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"errors-4MQyjZVj.js","names":["ERROR_STORM_WINDOW_MS","stripUrlQuery","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"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"}
@@ -1,3 +1,3 @@
1
- const e=require("./constants-TUFcy95w.cjs"),t=require("./platform-CXio0W2n.cjs");var n=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`More than 20 errors occurred in ${String(e.V)} ms. The library ignores the other errors in this window.`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
1
+ const e=require("./constants-IBL_jd5R.cjs"),t=require("./platform-ByQllE_W.cjs");var n=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`More than 20 errors occurred in ${String(e.V)} ms. The library ignores the other errors in this window.`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
2
2
  `)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};exports.ErrorCapture=n;
3
- //# sourceMappingURL=errors-DRXBRqvm.cjs.map
3
+ //# sourceMappingURL=errors-CUdShXe7.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-DRXBRqvm.cjs","names":["stripUrlQuery","ERROR_STORM_WINDOW_MS","require_constants","require_platform","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"iFAsBA,IAAaI,EAAb,KAA6C,CAmBd,IAjB7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,YAAsB,EAGtB,YAAsB,EAKtB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qBAAsB,KAAK,WAAW,EACzD,CAGA,WAAkB,CACX,KAAK,YAGV,KAAK,UAAY,GAEjB,oBAAoB,QAAS,KAAK,QAAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CAGA,QAA4B,GAAoC,CAC9D,IAAMC,EAASC,EAAM,OACfC,EAAcF,GAAQ,KAAOA,GAAQ,MAAQ,GAGnD,GACEA,IAAW,MACXA,IAAY,YACZE,IAAgB,GAChB,CACA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,eAC3B,OAKF,IAAMC,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAWD,EAAcR,EAAAA,EAAcQ,CAAW,EAEtF,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,oBAAoBC,GAC/B,CAAC,EACD,KAAK,IAAI,OAAO,KAAK,0BAA2B,CAC9C,aAAc,WACd,eAAgBA,EAChB,eAAgBH,EAAO,QAAQ,YAAY,CAC7C,CAAC,EACD,MACF,CAEA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,OAC3B,OAGF,IAAMI,EAAaH,EACbI,EAAWD,EAAW,UAAY,GAAK,gBAAkBA,EAAW,QAEpEE,EADkBF,EAAW,OACP,MAAMC,CAAQ,EAE1C,KAAK,OAAO,iBAAkBC,EAAO,CACnC,eAAgBF,EAAW,SAC3B,aAAcA,EAAW,OACzB,eAAgBA,EAAW,KAC7B,CAAC,CACH,EAGA,YAAgC,GAAuC,CAChE,KAAK,IAAI,OAAO,QAAQ,YAI7B,KAAK,OAAO,qBAAsBH,EAAM,OAAQ,CAC9C,aAAc,oBAChB,CAAC,CACH,EAQA,OAAe,EAAgB,EAAgB,EAAsC,CACnF,IAAMM,EAAM,KAAK,IAAI,EAQrB,GANIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,YAAc,GAGrB,KAAK,cACD,KAAK,YAAA,GAA0C,CAGjD,KAAK,IAAI,YAAY,OACnB,uBACA,mCAAsE,OAAOZ,EAAAA,CAAqB,EAAE,0DACtG,EACA,MACF,CAEA,IAAMa,EAAUF,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,EAClEG,GAASD,EAAQ,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GAChDE,EAAM,GAAGF,EAAQ,KAAK,GAAGA,EAAQ,QAAQ,GAAGC,IAC5CE,EAAW,KAAK,KAAK,IAAID,CAAG,EAElC,GAAIC,GAAYJ,EAAMI,EAAS,GAAA,IAAsB,CACnD,EAAS,QACT,EAAS,GAAKJ,EACd,MACF,CAIA,IAAMK,EAAaD,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOD,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIH,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACM,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,UAAY,GAAKM,EAASN,EAAQ,QAASA,EAAS,CAChF,GAAGO,EACH,oBAAqBD,EACrB,yBAA0BF,CAC5B,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"errors-CUdShXe7.cjs","names":["stripUrlQuery","ERROR_STORM_WINDOW_MS","require_constants","require_platform","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"iFAsBA,IAAaI,EAAb,KAA6C,CAmBd,IAjB7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,YAAsB,EAGtB,YAAsB,EAKtB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qBAAsB,KAAK,WAAW,EACzD,CAGA,WAAkB,CACX,KAAK,YAGV,KAAK,UAAY,GAEjB,oBAAoB,QAAS,KAAK,QAAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CAGA,QAA4B,GAAoC,CAC9D,IAAMC,EAASC,EAAM,OACfC,EAAcF,GAAQ,KAAOA,GAAQ,MAAQ,GAGnD,GACEA,IAAW,MACXA,IAAY,YACZE,IAAgB,GAChB,CACA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,eAC3B,OAKF,IAAMC,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAWD,EAAcR,EAAAA,EAAcQ,CAAW,EAEtF,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,oBAAoBC,GAC/B,CAAC,EACD,KAAK,IAAI,OAAO,KAAK,0BAA2B,CAC9C,aAAc,WACd,eAAgBA,EAChB,eAAgBH,EAAO,QAAQ,YAAY,CAC7C,CAAC,EACD,MACF,CAEA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,OAC3B,OAGF,IAAMI,EAAaH,EACbI,EAAWD,EAAW,UAAY,GAAK,gBAAkBA,EAAW,QAEpEE,EADkBF,EAAW,OACP,MAAMC,CAAQ,EAE1C,KAAK,OAAO,iBAAkBC,EAAO,CACnC,eAAgBF,EAAW,SAC3B,aAAcA,EAAW,OACzB,eAAgBA,EAAW,KAC7B,CAAC,CACH,EAGA,YAAgC,GAAuC,CAChE,KAAK,IAAI,OAAO,QAAQ,YAI7B,KAAK,OAAO,qBAAsBH,EAAM,OAAQ,CAC9C,aAAc,oBAChB,CAAC,CACH,EAQA,OAAe,EAAgB,EAAgB,EAAsC,CACnF,IAAMM,EAAM,KAAK,IAAI,EAQrB,GANIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,YAAc,GAGrB,KAAK,cACD,KAAK,YAAA,GAA0C,CAGjD,KAAK,IAAI,YAAY,OACnB,uBACA,mCAAsE,OAAOZ,EAAAA,CAAqB,EAAE,0DACtG,EACA,MACF,CAEA,IAAMa,EAAUF,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,EAClEG,GAASD,EAAQ,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GAChDE,EAAM,GAAGF,EAAQ,KAAK,GAAGA,EAAQ,QAAQ,GAAGC,IAC5CE,EAAW,KAAK,KAAK,IAAID,CAAG,EAElC,GAAIC,GAAYJ,EAAMI,EAAS,GAAA,IAAsB,CACnD,EAAS,QACT,EAAS,GAAKJ,EACd,MACF,CAIA,IAAMK,EAAaD,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOD,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIH,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACM,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,UAAY,GAAKM,EAASN,EAAQ,QAASA,EAAS,CAChF,GAAGO,EACH,oBAAqBD,EACrB,yBAA0BF,CAC5B,CAAC,CACH,CACF"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-TUFcy95w.cjs"),t=require("./sampling-CEthcmEX.cjs"),n=require("./platform-CXio0W2n.cjs"),r=require("./unref-CU9Nyz_9.cjs");function i(t){return Math.round((performance.now()-t)*e.F)/e.F}function a(e,t,n,r,a){e.logMetric(`${t}.duration`,i(n),`ms`,`histogram`,{status:r,...a})}function o(e,t,n,r,a){e.error(`${t} failed`,r,{"action.duration_ms":i(n),status:`FAILURE`,...a})}function s(e,t,n,r){let i=performance.now();try{let o=n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}async function c(e,t,n,r){let i=performance.now();try{let o=await n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}function l(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(n??typeof e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var d=class t{bind;namespace;options;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>s(this,e,t,n);timeAsync=(e,t,n)=>c(this,e,t,n);write(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;if(!i.builder.isEnabled(e)){this.mirrors(i,e)&&this.print(i,e,n,r,void 0,null);return}let{record:a,dropped:o}=i.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&o!==`redact`&&i.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.print(i,e,n,r,void 0,a),i.emit(a)}writeError(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;let a=i.builder.isEnabled(e);if(!a&&!this.mirrors(i,e))return;let o=r===void 0&&u(n),s=o?n:r,c=o||n===void 0?void 0:l(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:d}=i.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...s,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:i.breadcrumbs.snapshot()}});this.print(i,e,t,s,c,d),i.emit(d)}print(e,t,n,r,i,a){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},f={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},p=class{minLevel;diagnostics;constructor(e,t){this.minLevel=e,this.diagnostics=t}update(e){this.minLevel=e}accepts(t){return this.minLevel!==null&&e.it[t]>=e.it[this.minLevel]}write(n,r,i,a,o){if(!this.accepts(r)||typeof console>`u`)return;let s=`%c[%s]%c ${r}`,c=f[r];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${c}.`,()=>{let r=[];o!==void 0&&r.push(o),a!==void 0&&r.push(t.p(a,e.bt,this.diagnostics)),console[c](s,e.D,n,``,i,...r)})}},m=class{value=0;next(){return++this.value}reset(){this.value=0}},h=/^[0-9a-f]{32}$/,g=/^[0-9a-f]{16}$/,_=/[1-9a-f]/;function v(e){return h.test(e.traceId)&&_.test(e.traceId)&&g.test(e.spanId)&&_.test(e.spanId)}function y(){return t.u(16)}function b(){return t.u(8)}function x(){return{traceId:y(),spanId:b(),traceFlags:1,startedAt:Date.now()}}function S(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var C=class{diagnostics;maxAgeMs;load;ambient=x();otel;constructor(t,n=e.on,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),S(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(v(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=x(),S(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.an]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},w=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function T(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function E(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||T(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Vt}", "ecs" or an implementation. The library uses "${e.Vt}".`),e.Vt)}function D(t,n){return t===void 0?n:t===!1?null:t===!0?e.E:t}function O(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:E(t.serializer,r?.serializer,n),console:D(t.console,i.console),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(a.endpoint===``)n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}.`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.un}'.`),e.un);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(o)}. The library uses 1.`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1. The value is ${String(t)}. The library uses 1.`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),k(t,n),a}function k(t,n){let r=new Set([...Object.keys(e.j),...e.cn]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.ln[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function A(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var j=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},M=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.at} The onDiagnostic handler threw an error.`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},N={maxAgeMs:e.tt,endOnOwnerClose:!1,urlParam:e.rt};function P(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function F(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function I(e){if(typeof e!=`object`||!e)return null;let t=P(e,`id`),n=P(e,`name`),r=F(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:P(e,`parentId`),ownerContextId:P(e,`ownerContextId`)??``}}function L(e){if(typeof e!=`object`||!e)return null;let t=P(e,`i`),n=P(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:F(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function R(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}var z=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.a){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.nt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.c(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=R(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=I(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return L(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.nt):this.stores.session().setItem(e.nt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=i,r.t(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.nt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.i(r.call(n),e.ht)))?.customData?.[e.mt];return typeof i==`string`?i:null}};function B(e){return e}var V=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.it[t]>=e.it[n.minLevel]:!1}build(r){let{config:i,diagnostics:a,tracing:o,journey:s,sequence:c,limits:l}=this.deps;if(!this.isEnabled(r.level))return a.count(`record.dropped_by_level`),{record:null,dropped:`level`};let u=o.resolve(),d=s.current();if(!t.r({level:r.level,type:r.type,namespace:r.namespace,journeyId:d?.id??``,traceId:u.traceId},i))return a.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let f=c.next(),p=n.t(a),m=i.capture.fullUrls?p:n.r(p),h,g=0;try{let e=t.m(this.deps.context.getAll(),l,a),n=t.m(r.scoped??{},l,a),i=t.m(r.payload??{},l,a);g=e.bytes+n.bytes+i.bytes,h={...B(e.value),...B(n.value),...B(i.value)}}catch(t){a.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),h={[e.d]:!0}}h[e.l]=r.type,h[e.c]=f,h[e.n]=r.namespace,h[e.u]=m,d&&(h[e.a]=d.id,h[e.o]=d.name,d.parentId!==void 0&&(h[e.s]=d.parentId));let _=t.h(r.body,l.maxBodyChars);_!==r.body&&a.count(`record.truncated`);let v={timeUnixNano:t._(),traceId:u.traceId,spanId:u.spanId,traceFlags:u.traceFlags,severityNumber:e.Gt[r.level],severityText:r.level,body:_,attributes:h,resource:this.resource()},y=i.redact;if(y){let e=a.guard(`record.sanitize_failed`,`The redact hook threw an error.`,()=>y(v));if(e===null)return a.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==v){if(t.g(e)){let n=t.m(e.attributes,l,a);v={...e,attributes:B(n.value)},g=n.bytes}else a.report(`record.sanitize_failed`,`The redact hook returned a value that is not a record. The library keeps the original record.`)}}if(g>l.maxRecordBytes){a.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped them.`,{bytes:g,body:v.body});let t={[e.l]:r.type,[e.c]:f,[e.n]:r.namespace,[e.u]:m,[e.i]:!0,[e.r]:g};d&&(t[e.a]=d.id,t[e.o]=d.name),v.attributes=t}return{record:v}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Ot]:t.serviceName,[e.kt]:t.serviceVersion,[e.wt]:t.environment,[e.Nt]:e.rn,[e.Pt]:e.in,[e.Mt]:e.nn,[e.Tt]:r.platform,[e.At]:n.sessionId,[e.jt]:n.tabId,[e.Ct]:n.contextId,[e.St]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Dt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Et]:r.openfinName}},this.resourceCache}},H={errors:async()=>(await Promise.resolve().then(()=>require("./errors-DRXBRqvm.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-CuqWadNn.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-DVom6eYn.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-B2FYsEAU.cjs"))).WebVitalsCapture},U=Symbol.for(e.Rt),W=Symbol.for(e.zt),G=class r{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new j;breadcrumbs;tracing;sequence=new m;journey;builder;console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(r){this.diagnostics=new M(r.onDiagnostic),this.platform=n.n(this.diagnostics),this.config=O(r,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.s():t.a,this.identity=t.d(this.diagnostics,this.stores),this.sessionTouch=new t.o(this.diagnostics,this.stores),this.breadcrumbs=new w(50),this.tracing=new C(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new p(this.config.console,this.diagnostics),this.journey=new z(N,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new V({config:this.config,limits:e.bt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{n.acceptDirect(e,t)})})};static current(){return globalThis[U]??null}static stopped(){return globalThis[W]??null}isDestroyed(){return this.destroyed}static configure(e){let t=r.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let n=new r(e);return globalThis[U]=n,Reflect.deleteProperty(globalThis,W),n.init(),n}reconfigure(e){let t=this.keepEndpoint(e);A(this.config,O(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup. It stays ${e}.`,{requested:this.config.storage}),this.config.storage=e)}keepEndpoint(e){return this.senderLoad===void 0||e.endpoint!==null&&e.endpoint!==``?e:(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),{...e,endpoint:void 0})}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}await e}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-ChIXDAWD.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.config.endpoint||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-ByFAkXVd.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new d(()=>this,e.C),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${e.name} capture.`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,H[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,r.current()===this&&(Reflect.deleteProperty(globalThis,U),globalThis[W]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad&&this.pushCapped(this.pendingRecords,e)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let n of e)t.g(n)?t.n(n,this.config)?this.deliver(n):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new d(()=>this,e.Yt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.c(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,t.l(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}},K=new Map;function q(){return(G.current()??G.stopped())||G.configure({})}function J(e){G.configure(e)}function Y(e,t){if(t)return new d(q,e,t);let n=K.get(e);return n||(n=new d(q,e),K.set(e,n)),n}function X(){return Y(`app`)}function Z(e,t){X().trace(e,t)}function Q(e,t){X().debug(e,t)}function $(e,t){X().info(e,t)}function ee(e,t){X().warn(e,t)}function te(e,t,n){X().error(e,t,n)}function ne(e,t){X().logAction(e,t)}function re(e,t){X().logEvent(e,t)}function ie(e,t,n,r,i){X().logMetric(e,t,n,r,i)}function ae(e,t,n){return X().timeSync(e,t,n)}function oe(e,t,n){return X().timeAsync(e,t,n)}function se(e,t){q().context.set(e,t)}function ce(e){q().context.setMany(e)}function le(e){q().context.remove(e)}function ue(e,t){return q().journey.start(e,t)}function de(){q().journey.end()}function fe(){return q().journey.current()}function pe(){return q().journey.getToken()}function me(e){return q().journey.adopt(e,`manual`,!0)}function he(e){q().registerWorker(e)}function ge(){q().tracing.rotate(`explicit`)}function _e(){return q().tracing.headers()}function ve(){return q().flush()}function ye(){return q().queueDepth()}function be(){return q().diagnostics.snapshot()}async function xe(){await G.current()?.destroy()}exports.OneLogger=d,exports.adoptJourney=me,exports.configure=J,exports.currentJourney=fe,exports.debug=Q,exports.endJourney=de,exports.error=te,exports.flush=ve,exports.getDiagnosticCounters=be,exports.getJourneyToken=pe,exports.getLogger=Y,exports.getQueueDepth=ye,exports.getTraceHeaders=_e,exports.info=$,exports.logAction=ne,exports.logEvent=re,exports.logMetric=ie,exports.registerWorker=he,exports.removeContext=le,exports.setContext=se,exports.setContextMap=ce,exports.shutdown=xe,exports.startJourney=ue,exports.startTrace=ge,exports.timeAsync=oe,exports.timeSync=ae,exports.trace=Z,exports.warn=ee;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-IBL_jd5R.cjs"),t=require("./sampling-Cs50xsZl.cjs"),n=require("./platform-ByQllE_W.cjs"),r=require("./unref-CU9Nyz_9.cjs");function i(t){return Math.round((performance.now()-t)*e.F)/e.F}function a(e,t,n,r,a){e.logMetric(`${t}.duration`,i(n),`ms`,`histogram`,{status:r,...a})}function o(e,t,n,r,a){e.error(`${t} failed`,r,{"action.duration_ms":i(n),status:`FAILURE`,...a})}function s(e,t,n,r){let i=performance.now();try{let o=n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}async function c(e,t,n,r){let i=performance.now();try{let o=await n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}function l(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(n??typeof e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var d=class t{bind;namespace;options;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>s(this,e,t,n);timeAsync=(e,t,n)=>c(this,e,t,n);write(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;if(!i.builder.isEnabled(e)){this.mirrors(i,e)&&this.print(i,e,n,r,void 0,null);return}let{record:a,dropped:o}=i.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&o!==`redact`&&i.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.print(i,e,n,r,void 0,a),i.emit(a)}writeError(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;let a=i.builder.isEnabled(e);if(!a&&!this.mirrors(i,e))return;let o=r===void 0&&u(n),s=o?n:r,c=o||n===void 0?void 0:l(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:d}=i.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...s,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:i.breadcrumbs.snapshot()}});this.print(i,e,t,s,c,d),i.emit(d)}print(e,t,n,r,i,a){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},f={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},p=class{settings;diagnostics;constructor(e,t){this.settings=e,this.diagnostics=t}update(e){this.settings=e}accepts(t){return this.settings.level!==null&&e.it[t]>=e.it[this.settings.level]}write(n,r,i,a,o){if(!this.accepts(r)||typeof console>`u`)return;let s=`%c[%s]%c[${r}]%c`,{styles:c}=this.settings,l=f[r];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${l}.`,()=>{let u=[];o!==void 0&&u.push(o),a!==void 0&&u.push(t.p(a,e.bt,this.diagnostics)),console[l](s,c.namespace,n,c[r],``,i,...u)})}},m=class{value=0;next(){return++this.value}reset(){this.value=0}},h=/^[0-9a-f]{32}$/,g=/^[0-9a-f]{16}$/,_=/[1-9a-f]/;function v(e){return h.test(e.traceId)&&_.test(e.traceId)&&g.test(e.spanId)&&_.test(e.spanId)}function y(){return t.u(16)}function b(){return t.u(8)}function x(){return{traceId:y(),spanId:b(),traceFlags:1,startedAt:Date.now()}}function S(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var C=class{diagnostics;maxAgeMs;load;ambient=x();otel;constructor(t,n=e.on,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),S(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(v(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=x(),S(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.an]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},w=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function T(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function E(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||T(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Vt}", "ecs" or an implementation. The library uses "${e.Vt}".`),e.Vt)}var D=new Set(Object.keys(e.D));function O(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)D.has(e)?typeof i==`string`?n[e]=i:t.report(`config.invalid`,`console.styles.${e} must be a string. The library keeps the style in force.`):t.report(`config.invalid`,`The library ignores the unknown console.styles key "${e}". Check the spelling.`);return n}function k(t,n,r){return t===void 0?n:t===!1?{level:null,styles:n.styles}:t===!0?{level:e.E,styles:n.styles}:typeof t==`string`?{level:t,styles:n.styles}:typeof t!=`object`||!t?(r.report(`config.invalid`,`console must be a boolean, a level or an object. The console settings in force stay.`),n):{level:t.level??n.level??`DEBUG`,styles:{...n.styles,...O(t.styles,r)}}}function A(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:E(t.serializer,r?.serializer,n),console:k(t.console,i.console,n),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(a.endpoint===``)n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}.`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.un}'.`),e.un);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(o)}. The library uses 1.`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1. The value is ${String(t)}. The library uses 1.`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),j(t,n),a}function j(t,n){let r=new Set([...Object.keys(e.j),...e.cn]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.ln[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function M(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var ee=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},N=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.at} The onDiagnostic handler threw an error.`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},P={maxAgeMs:e.tt,endOnOwnerClose:!1,urlParam:e.rt};function F(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function I(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function L(e){if(typeof e!=`object`||!e)return null;let t=F(e,`id`),n=F(e,`name`),r=I(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:F(e,`parentId`),ownerContextId:F(e,`ownerContextId`)??``}}function R(e){if(typeof e!=`object`||!e)return null;let t=F(e,`i`),n=F(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:I(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function z(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}var B=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.a){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.nt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.c(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=z(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=L(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return R(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.nt):this.stores.session().setItem(e.nt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=i,r.t(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.nt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.i(r.call(n),e.ht)))?.customData?.[e.mt];return typeof i==`string`?i:null}};function V(e){return e}var H=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.it[t]>=e.it[n.minLevel]:!1}build(r){let{config:i,diagnostics:a,tracing:o,journey:s,sequence:c,limits:l}=this.deps;if(!this.isEnabled(r.level))return a.count(`record.dropped_by_level`),{record:null,dropped:`level`};let u=o.resolve(),d=s.current();if(!t.r({level:r.level,type:r.type,namespace:r.namespace,journeyId:d?.id??``,traceId:u.traceId},i))return a.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let f=c.next(),p=n.t(a),m=i.capture.fullUrls?p:n.r(p),h,g=0;try{let e=t.m(this.deps.context.getAll(),l,a),n=t.m(r.scoped??{},l,a),i=t.m(r.payload??{},l,a);g=e.bytes+n.bytes+i.bytes,h={...V(e.value),...V(n.value),...V(i.value)}}catch(t){a.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),h={[e.d]:!0}}h[e.l]=r.type,h[e.c]=f,h[e.n]=r.namespace,h[e.u]=m,d&&(h[e.a]=d.id,h[e.o]=d.name,d.parentId!==void 0&&(h[e.s]=d.parentId));let _=t.h(r.body,l.maxBodyChars);_!==r.body&&a.count(`record.truncated`);let v={timeUnixNano:t._(),traceId:u.traceId,spanId:u.spanId,traceFlags:u.traceFlags,severityNumber:e.Gt[r.level],severityText:r.level,body:_,attributes:h,resource:this.resource()},y=i.redact;if(y){let e=a.guard(`record.sanitize_failed`,`The redact hook threw an error.`,()=>y(v));if(e===null)return a.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==v){if(t.g(e)){let n=t.m(e.attributes,l,a);v={...e,attributes:V(n.value)},g=n.bytes}else a.report(`record.sanitize_failed`,`The redact hook returned a value that is not a record. The library keeps the original record.`)}}if(g>l.maxRecordBytes){a.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped them.`,{bytes:g,body:v.body});let t={[e.l]:r.type,[e.c]:f,[e.n]:r.namespace,[e.u]:m,[e.i]:!0,[e.r]:g};d&&(t[e.a]=d.id,t[e.o]=d.name),v.attributes=t}return{record:v}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Ot]:t.serviceName,[e.kt]:t.serviceVersion,[e.wt]:t.environment,[e.Nt]:e.rn,[e.Pt]:e.in,[e.Mt]:e.nn,[e.Tt]:r.platform,[e.At]:n.sessionId,[e.jt]:n.tabId,[e.Ct]:n.contextId,[e.St]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Dt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Et]:r.openfinName}},this.resourceCache}},U={errors:async()=>(await Promise.resolve().then(()=>require("./errors-CUdShXe7.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-DBNvxCE3.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-BMNPQ3WH.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-B2FYsEAU.cjs"))).WebVitalsCapture},W=Symbol.for(e.Rt),G=Symbol.for(e.zt),K=class r{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new ee;breadcrumbs;tracing;sequence=new m;journey;builder;console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(r){this.diagnostics=new N(r.onDiagnostic),this.platform=n.n(this.diagnostics),this.config=A(r,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.s():t.a,this.identity=t.d(this.diagnostics,this.stores),this.sessionTouch=new t.o(this.diagnostics,this.stores),this.breadcrumbs=new w(50),this.tracing=new C(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new p(this.config.console,this.diagnostics),this.journey=new B(P,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new H({config:this.config,limits:e.bt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{n.acceptDirect(e,t)})})};static current(){return globalThis[W]??null}static stopped(){return globalThis[G]??null}isDestroyed(){return this.destroyed}static configure(e){let t=r.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let n=new r(e);return globalThis[W]=n,Reflect.deleteProperty(globalThis,G),n.init(),n}reconfigure(e){let t=this.keepEndpoint(e);M(this.config,A(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup. It stays ${e}.`,{requested:this.config.storage}),this.config.storage=e)}keepEndpoint(e){return this.senderLoad===void 0||e.endpoint!==null&&e.endpoint!==``?e:(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),{...e,endpoint:void 0})}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}await e}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-DeZzr2bx.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.config.endpoint||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-iOjzcueM.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new d(()=>this,e.C),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${e.name} capture.`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,U[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,r.current()===this&&(Reflect.deleteProperty(globalThis,W),globalThis[G]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad&&this.pushCapped(this.pendingRecords,e)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let n of e)t.g(n)?t.n(n,this.config)?this.deliver(n):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new d(()=>this,e.Yt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.c(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,t.l(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}},q=new Map;function J(){return(K.current()??K.stopped())||K.configure({})}function Y(e){K.configure(e)}function X(e,t){if(t)return new d(J,e,t);let n=q.get(e);return n||(n=new d(J,e),q.set(e,n)),n}function Z(){return X(`app`)}function Q(e,t){Z().trace(e,t)}function te(e,t){Z().debug(e,t)}function ne(e,t){Z().info(e,t)}function re(e,t){Z().warn(e,t)}function ie(e,t,n){Z().error(e,t,n)}function ae(e,t){Z().logAction(e,t)}function oe(e,t){Z().logEvent(e,t)}function se(e,t,n,r,i){Z().logMetric(e,t,n,r,i)}function ce(e,t,n){return Z().timeSync(e,t,n)}function le(e,t,n){return Z().timeAsync(e,t,n)}function ue(e,t){J().context.set(e,t)}function de(e){J().context.setMany(e)}function fe(e){J().context.remove(e)}function pe(e,t){return J().journey.start(e,t)}function $(){J().journey.end()}function me(){return J().journey.current()}function he(){return J().journey.getToken()}function ge(e){return J().journey.adopt(e,`manual`,!0)}function _e(e){J().registerWorker(e)}function ve(){J().tracing.rotate(`explicit`)}function ye(){return J().tracing.headers()}function be(){return J().flush()}function xe(){return J().queueDepth()}function Se(){return J().diagnostics.snapshot()}async function Ce(){await K.current()?.destroy()}exports.OneLogger=d,exports.adoptJourney=ge,exports.configure=Y,exports.currentJourney=me,exports.debug=te,exports.endJourney=$,exports.error=ie,exports.flush=be,exports.getDiagnosticCounters=Se,exports.getJourneyToken=he,exports.getLogger=X,exports.getQueueDepth=xe,exports.getTraceHeaders=ye,exports.info=ne,exports.logAction=ae,exports.logEvent=oe,exports.logMetric=se,exports.registerWorker=_e,exports.removeContext=fe,exports.setContext=ue,exports.setContextMap=de,exports.shutdown=Ce,exports.startJourney=pe,exports.startTrace=ve,exports.timeAsync=le,exports.timeSync=ce,exports.trace=Q,exports.warn=re;
2
2
  //# sourceMappingURL=index.cjs.map