@utk09/ui-observability 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +189 -25
- package/dist/bus/bus.d.ts +30 -0
- package/dist/bus-CUXRY0JR.cjs +2 -0
- package/dist/bus-CUXRY0JR.cjs.map +1 -0
- package/dist/{bus-BTMuVkDk.js → bus-DPDrlUBY.js} +96 -50
- package/dist/bus-DPDrlUBY.js.map +1 -0
- package/dist/capture/console.d.ts +37 -0
- package/dist/capture/errors.d.ts +2 -4
- package/dist/capture/long-frames.d.ts +31 -0
- package/dist/capture/storm.d.ts +17 -0
- package/dist/capture/types.d.ts +2 -0
- package/dist/console-CNljJict.js +81 -0
- package/dist/console-CNljJict.js.map +1 -0
- package/dist/console-PKzc-FmR.cjs +2 -0
- package/dist/console-PKzc-FmR.cjs.map +1 -0
- package/dist/constants-B28fDv2F.cjs +2 -0
- package/dist/constants-B28fDv2F.cjs.map +1 -0
- package/dist/constants-Bu49bm39.js +93 -0
- package/dist/constants-Bu49bm39.js.map +1 -0
- package/dist/constants.d.ts +35 -5
- package/dist/core/breadcrumbs.d.ts +1 -1
- package/dist/core/pipeline.d.ts +2 -2
- package/dist/core/record.d.ts +3 -0
- package/dist/core/remote-rules.d.ts +17 -0
- package/dist/core/remote-sampling.d.ts +65 -0
- package/dist/core/runtime.d.ts +10 -4
- package/dist/core/sampling.d.ts +5 -2
- package/dist/core/sender.d.ts +3 -0
- package/dist/errors-C78ZTjet.cjs +3 -0
- package/dist/errors-C78ZTjet.cjs.map +1 -0
- package/dist/{errors-Dwm2SzBa.js → errors-Dnc-X4Ec.js} +19 -20
- package/dist/errors-Dnc-X4Ec.js.map +1 -0
- package/dist/global-scope-BN-Io_yv.cjs +2 -0
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
- package/dist/global-scope-dp2jADRl.js +19 -0
- package/dist/global-scope-dp2jADRl.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +307 -241
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
- package/dist/{indexeddb-storage-B5dwq4hW.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
- package/dist/{indexeddb-storage-DjY4Ml6t.js → indexeddb-storage-uD4oaRMc.js} +10 -10
- package/dist/{indexeddb-storage-DjY4Ml6t.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
- package/dist/{interactions-DVom6eYn.cjs → interactions-CsE2y_fQ.cjs} +2 -2
- package/dist/{interactions-DVom6eYn.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
- package/dist/{interactions-DZmLu7l2.js → interactions-igKTAJvj.js} +2 -2
- package/dist/{interactions-DZmLu7l2.js.map → interactions-igKTAJvj.js.map} +1 -1
- package/dist/library-request-Br_T09Bn.cjs +2 -0
- package/dist/library-request-Br_T09Bn.cjs.map +1 -0
- package/dist/library-request-Dt0fXhcn.js +14 -0
- package/dist/library-request-Dt0fXhcn.js.map +1 -0
- package/dist/long-frames-6pnjWSSR.js +65 -0
- package/dist/long-frames-6pnjWSSR.js.map +1 -0
- package/dist/long-frames-DahhqM6u.cjs +2 -0
- package/dist/long-frames-DahhqM6u.cjs.map +1 -0
- package/dist/models/bus.d.ts +16 -0
- package/dist/models/config.d.ts +120 -6
- package/dist/network-CZ0aFUsy.cjs +2 -0
- package/dist/network-CZ0aFUsy.cjs.map +1 -0
- package/dist/{network-C4d2uw2Z.js → network-aSNbwpue.js} +16 -15
- package/dist/network-aSNbwpue.js.map +1 -0
- package/dist/{platform-CY8S3hUs.js → platform-BwbMRwHm.js} +7 -7
- package/dist/{platform-CY8S3hUs.js.map → platform-BwbMRwHm.js.map} +1 -1
- package/dist/{platform-CXio0W2n.cjs → platform-D_XkVIF6.cjs} +2 -2
- package/dist/{platform-CXio0W2n.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
- package/dist/remote-rules-5UA23alm.js +86 -0
- package/dist/remote-rules-5UA23alm.js.map +1 -0
- package/dist/remote-rules-rJJZKVG8.cjs +2 -0
- package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
- package/dist/sampling-E4x92Nn2.cjs +2 -0
- package/dist/sampling-E4x92Nn2.cjs.map +1 -0
- package/dist/sampling-J1eahbfT.js +160 -0
- package/dist/sampling-J1eahbfT.js.map +1 -0
- package/dist/sanitize-BMhh8ghJ.cjs +2 -0
- package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
- package/dist/sanitize-UJ-4Lb0n.js +114 -0
- package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
- package/dist/sender-B6ufz26f.cjs +3 -0
- package/dist/sender-B6ufz26f.cjs.map +1 -0
- package/dist/{sender-dpvR_bHM.js → sender-G6v4Uqi4.js} +304 -219
- package/dist/sender-G6v4Uqi4.js.map +1 -0
- package/dist/storm-BtzgLOCX.cjs +2 -0
- package/dist/storm-BtzgLOCX.cjs.map +1 -0
- package/dist/storm-DJkEZP_8.js +10 -0
- package/dist/storm-DJkEZP_8.js.map +1 -0
- package/dist/transport/custom-transport.d.ts +20 -0
- package/dist/transport/errors.d.ts +2 -1
- package/dist/transport/exit-flush.d.ts +15 -0
- package/dist/transport/http-transport.d.ts +2 -24
- package/dist/transport/memory-transport.d.ts +30 -0
- package/dist/transport/retry-engine.d.ts +2 -2
- package/dist/transport/serializers/select.d.ts +12 -1
- package/dist/transport/status-transport.d.ts +72 -0
- package/dist/utils/console.d.ts +7 -6
- package/dist/utils/deadline.d.ts +7 -0
- package/dist/utils/global-scope.d.ts +20 -0
- package/dist/utils/library-console.d.ts +11 -0
- package/dist/utils/library-request.d.ts +12 -0
- package/package.json +4 -2
- package/dist/bus-BTMuVkDk.js.map +0 -1
- package/dist/bus-ChIXDAWD.cjs +0 -2
- package/dist/bus-ChIXDAWD.cjs.map +0 -1
- package/dist/constants-0-YchbAL.js +0 -75
- package/dist/constants-0-YchbAL.js.map +0 -1
- package/dist/constants-TUFcy95w.cjs +0 -2
- package/dist/constants-TUFcy95w.cjs.map +0 -1
- package/dist/errors-DRXBRqvm.cjs +0 -3
- package/dist/errors-DRXBRqvm.cjs.map +0 -1
- package/dist/errors-Dwm2SzBa.js.map +0 -1
- package/dist/indexeddb-storage-B5dwq4hW.cjs +0 -2
- package/dist/network-C4d2uw2Z.js.map +0 -1
- package/dist/network-CuqWadNn.cjs +0 -2
- package/dist/network-CuqWadNn.cjs.map +0 -1
- package/dist/sampling-CEthcmEX.cjs +0 -2
- package/dist/sampling-CEthcmEX.cjs.map +0 -1
- package/dist/sampling-CJsI_24L.js +0 -251
- package/dist/sampling-CJsI_24L.js.map +0 -1
- package/dist/sender-ByFAkXVd.cjs +0 -3
- package/dist/sender-ByFAkXVd.cjs.map +0 -1
- package/dist/sender-dpvR_bHM.js.map +0 -1
package/dist/core/runtime.d.ts
CHANGED
|
@@ -40,6 +40,8 @@ export declare class ObservabilityRuntime {
|
|
|
40
40
|
readonly journey: JourneyEngine;
|
|
41
41
|
/** Record builder assembling structured log records. */
|
|
42
42
|
readonly builder: RecordBuilder;
|
|
43
|
+
/** Slot of the remote sampling rules. The sender or the bus fills it. */
|
|
44
|
+
private readonly remote;
|
|
43
45
|
/** Console sink for local developer output. */
|
|
44
46
|
readonly console: ConsoleSink;
|
|
45
47
|
/**
|
|
@@ -73,6 +75,8 @@ export declare class ObservabilityRuntime {
|
|
|
73
75
|
private forwardScheduled;
|
|
74
76
|
/** Indicates whether startup has decided the bus role. A sender load waits for it. */
|
|
75
77
|
private roleResolved;
|
|
78
|
+
/** Resolves when startup releases the boot records. flush() waits for it. init() sets it. */
|
|
79
|
+
private started;
|
|
76
80
|
/** Indicates whether asynchronous initialization has completed. */
|
|
77
81
|
private ready;
|
|
78
82
|
/** Indicates whether shutdown stopped the runtime. */
|
|
@@ -122,12 +126,12 @@ export declare class ObservabilityRuntime {
|
|
|
122
126
|
*/
|
|
123
127
|
private keepBuiltStorage;
|
|
124
128
|
/**
|
|
125
|
-
* Refuses
|
|
126
|
-
* the retry engine removes each stored batch as delivered.
|
|
129
|
+
* Refuses a change that would leave the built delivery stack with nowhere to send.
|
|
130
|
+
* Without a destination, the retry engine removes each stored batch as delivered.
|
|
127
131
|
* @param input Partial configuration to merge.
|
|
128
|
-
* @returns Input
|
|
132
|
+
* @returns Input without the refused changes.
|
|
129
133
|
*/
|
|
130
|
-
private
|
|
134
|
+
private keepDestination;
|
|
131
135
|
/**
|
|
132
136
|
* Restores the identity strategy from startup. The ids exist from startup.
|
|
133
137
|
* A later change cannot move them to another store.
|
|
@@ -135,6 +139,8 @@ export declare class ObservabilityRuntime {
|
|
|
135
139
|
private keepBuiltIdentity;
|
|
136
140
|
/** Initializes asynchronous subsystems and flushes the boot buffer. */
|
|
137
141
|
private init;
|
|
142
|
+
/** Resolves the bus role, loads the delivery stack and releases the boot records. It never rejects. */
|
|
143
|
+
private boot;
|
|
138
144
|
/**
|
|
139
145
|
* Starts the load of the bus one time.
|
|
140
146
|
* @returns Promise resolving to the started bus, or null if it did not load.
|
package/dist/core/sampling.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ResolvedConfig } from "../models/config";
|
|
2
2
|
import type { LogRecord } from "../models/log-record";
|
|
3
|
+
import type { RemoteRules } from "./remote-sampling";
|
|
3
4
|
/** Fields that sampling reads. The caller knows all of them before it builds a record. */
|
|
4
5
|
export interface SampleInput {
|
|
5
6
|
/** Severity level of the entry. */
|
|
@@ -18,17 +19,19 @@ export interface SampleInput {
|
|
|
18
19
|
* This lets the caller drop an entry before the attribute walk runs.
|
|
19
20
|
* @param input Fields the sampling decision reads.
|
|
20
21
|
* @param config Active configuration instance.
|
|
22
|
+
* @param remote Remote rules in force, or null.
|
|
21
23
|
* @returns True if the runtime keeps and sends the entry.
|
|
22
24
|
*/
|
|
23
|
-
export declare function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean;
|
|
25
|
+
export declare function shouldSampleInput(input: SampleInput, config: ResolvedConfig, remote: RemoteRules | null): boolean;
|
|
24
26
|
/**
|
|
25
27
|
* Decides if sampling keeps a built log record. The runtime uses it for records
|
|
26
28
|
* that a child context sends over the bus.
|
|
27
29
|
* @param record Record to evaluate.
|
|
28
30
|
* @param config Active configuration instance.
|
|
31
|
+
* @param remote Remote rules in force, or null.
|
|
29
32
|
* @returns True if the runtime keeps and sends the record.
|
|
30
33
|
*/
|
|
31
|
-
export declare function shouldSample(record: LogRecord, config: ResolvedConfig): boolean;
|
|
34
|
+
export declare function shouldSample(record: LogRecord, config: ResolvedConfig, remote?: RemoteRules | null): boolean;
|
|
32
35
|
/**
|
|
33
36
|
* Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.
|
|
34
37
|
*
|
package/dist/core/sender.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { ResolvedConfig } from "../models/config";
|
|
|
2
2
|
import type { LogRecord } from "../models/log-record";
|
|
3
3
|
import type { GapReporter } from "../models/storage";
|
|
4
4
|
import type { Diagnostics } from "./diagnostics";
|
|
5
|
+
import type { RemoteSlot } from "./remote-sampling";
|
|
5
6
|
/** Inputs to build the delivery stack. */
|
|
6
7
|
export interface SenderDeps {
|
|
7
8
|
/** Active configuration instance. */
|
|
@@ -10,6 +11,8 @@ export interface SenderDeps {
|
|
|
10
11
|
diagnostics: Diagnostics;
|
|
11
12
|
/** Receives a report when storage drops batches before delivery. */
|
|
12
13
|
onGap: GapReporter;
|
|
14
|
+
/** Slot of the runtime for the sampling rules from the ingest server. */
|
|
15
|
+
remote: RemoteSlot;
|
|
13
16
|
}
|
|
14
17
|
/** Delivery stack for one sender runtime. */
|
|
15
18
|
export declare class Sender {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
require("./constants-B28fDv2F.cjs");const e=require("./platform-D_XkVIF6.cjs"),t=require("./storm-BtzgLOCX.cjs");var n=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count:0};constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=t=>{let n=t.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let t=this.ctx.config.capture.fullUrls?r:e.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${t}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":t,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=t,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(e,n,r){if(!t.t(this.window,20,this.ctx.diagnostics,`errors`))return;let i=Date.now(),a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
|
|
2
|
+
`)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?e:a.message,a,{...r,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=n;
|
|
3
|
+
//# sourceMappingURL=errors-C78ZTjet.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-C78ZTjet.cjs","names":["stripUrlQuery","allowInWindow","require_platform","require_storm","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless 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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\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":"iHAsBA,IAAaI,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qBAAsB,KAAK,WAAW,EACzD,CAGA,WAAkB,CACX,KAAK,YAGV,KAAK,UAAY,GAEjB,oBAAoB,QAAS,KAAK,QAAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CAGA,QAA4B,GAAoC,CAC9D,IAAMC,EAASC,EAAM,OACfC,EAAcF,GAAQ,KAAOA,GAAQ,MAAQ,GAGnD,GACEA,IAAW,MACXA,IAAY,YACZE,IAAgB,GAChB,CACA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,eAC3B,OAKF,IAAMC,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAWD,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,GAAI,CAACN,EAAAA,EAAc,KAAK,OAAA,GAAoC,KAAK,IAAI,YAAa,QAAQ,EACxF,OAGF,IAAMY,EAAM,KAAK,IAAI,EACfC,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,13 +1,16 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { r as
|
|
1
|
+
import "./constants-Bu49bm39.js";
|
|
2
|
+
import { r as e } from "./platform-BwbMRwHm.js";
|
|
3
|
+
import { t } from "./storm-DJkEZP_8.js";
|
|
3
4
|
//#region src/capture/errors.ts
|
|
4
5
|
var n = class {
|
|
5
6
|
ctx;
|
|
6
7
|
name = "errors";
|
|
7
8
|
installed = !1;
|
|
8
9
|
seen = /* @__PURE__ */ new Map();
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
window = {
|
|
11
|
+
start: 0,
|
|
12
|
+
count: 0
|
|
13
|
+
};
|
|
11
14
|
constructor(e) {
|
|
12
15
|
this.ctx = e;
|
|
13
16
|
}
|
|
@@ -17,24 +20,24 @@ var n = class {
|
|
|
17
20
|
uninstall() {
|
|
18
21
|
this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
|
|
19
22
|
}
|
|
20
|
-
onError = (
|
|
21
|
-
let n =
|
|
23
|
+
onError = (t) => {
|
|
24
|
+
let n = t.target, r = n?.src ?? n?.href ?? "";
|
|
22
25
|
if (n !== null && n !== globalThis && r !== "") {
|
|
23
26
|
if (!this.ctx.config.capture.resourceErrors) return;
|
|
24
|
-
let
|
|
27
|
+
let t = this.ctx.config.capture.fullUrls ? r : e(r);
|
|
25
28
|
this.ctx.breadcrumbs.push({
|
|
26
29
|
t: Date.now(),
|
|
27
30
|
category: "http",
|
|
28
|
-
message: `resource failed: ${
|
|
31
|
+
message: `resource failed: ${t}`
|
|
29
32
|
}), this.ctx.logger.warn("resource failed to load", {
|
|
30
33
|
"error.type": "resource",
|
|
31
|
-
"resource.url":
|
|
34
|
+
"resource.url": t,
|
|
32
35
|
"resource.tag": n.tagName.toLowerCase()
|
|
33
36
|
});
|
|
34
37
|
return;
|
|
35
38
|
}
|
|
36
39
|
if (!this.ctx.config.capture.errors) return;
|
|
37
|
-
let i =
|
|
40
|
+
let i = t, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
|
|
38
41
|
this.report("window.onerror", o, {
|
|
39
42
|
"error.source": i.filename,
|
|
40
43
|
"error.line": i.lineno,
|
|
@@ -44,13 +47,9 @@ var n = class {
|
|
|
44
47
|
onRejection = (e) => {
|
|
45
48
|
this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
|
|
46
49
|
};
|
|
47
|
-
report(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
this.ctx.diagnostics.report("capture.rate_limited", `More than 20 errors occurred in ${String(e)} ms. The library ignores the other errors in this window.`);
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
let a = n instanceof Error ? n : Error(String(n)), o = (a.stack ?? "").split("\n")[1] ?? "", s = `${a.name}|${a.message}|${o}`, c = this.seen.get(s);
|
|
50
|
+
report(e, n, r) {
|
|
51
|
+
if (!t(this.window, 20, this.ctx.diagnostics, "errors")) return;
|
|
52
|
+
let i = Date.now(), a = n instanceof Error ? n : Error(String(n)), o = (a.stack ?? "").split("\n")[1] ?? "", s = `${a.name}|${a.message}|${o}`, c = this.seen.get(s);
|
|
54
53
|
if (c && i - c.at < 5e3) {
|
|
55
54
|
c.count++, c.at = i;
|
|
56
55
|
return;
|
|
@@ -63,9 +62,9 @@ var n = class {
|
|
|
63
62
|
let [e] = this.seen.keys();
|
|
64
63
|
this.seen.delete(e);
|
|
65
64
|
}
|
|
66
|
-
this.ctx.logger.error(a.message === "" ?
|
|
65
|
+
this.ctx.logger.error(a.message === "" ? e : a.message, a, {
|
|
67
66
|
...r,
|
|
68
|
-
"error.captured_by":
|
|
67
|
+
"error.captured_by": e,
|
|
69
68
|
"error.suppressed_count": l
|
|
70
69
|
});
|
|
71
70
|
}
|
|
@@ -73,4 +72,4 @@ var n = class {
|
|
|
73
72
|
//#endregion
|
|
74
73
|
export { n as ErrorCapture };
|
|
75
74
|
|
|
76
|
-
//# sourceMappingURL=errors-
|
|
75
|
+
//# sourceMappingURL=errors-Dnc-X4Ec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-Dnc-X4Ec.js","names":["stripUrlQuery","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","allowInWindow","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 MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless 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 if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;AAsBA,IAAaC,IAAb,MAA6C;CAgBd;CAd7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK,KAAK,MAAM;CAClB;CAGA,WAA4B,MAAoC;EAC9D,IAAMC,IAASC,EAAM,QACfC,IAAcF,GAAQ,OAAOA,GAAQ,QAAQ;EAGnD,IACEA,MAAW,QACXA,MAAY,cACZE,MAAgB,IAChB;GACA,IAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,gBAC3B;GAKF,IAAMC,IAAM,KAAK,IAAI,OAAO,QAAQ,WAAWD,IAAcL,EAAcK,CAAW;GAOtF,AALA,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,oBAAoBC;GAC/B,CAAC,GACD,KAAK,IAAI,OAAO,KAAK,2BAA2B;IAC9C,cAAc;IACd,gBAAgBA;IAChB,gBAAgBH,EAAO,QAAQ,YAAY;GAC7C,CAAC;GACD;EACF;EAEA,IAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,QAC3B;EAGF,IAAMI,IAAaH,GACbI,IAAWD,EAAW,YAAY,KAAK,kBAAkBA,EAAW,SAEpEE,IADkBF,EAAW,SACP,MAAMC,CAAQ;EAE1C,KAAK,OAAO,kBAAkBC,GAAO;GACnC,gBAAgBF,EAAW;GAC3B,cAAcA,EAAW;GACzB,gBAAgBA,EAAW;EAC7B,CAAC;CACH;CAGA,eAAgC,MAAuC;EACrE,AAAK,KAAK,IAAI,OAAO,QAAQ,cAI7B,KAAK,OAAO,sBAAsBH,EAAM,QAAQ,EAC9C,cAAc,qBAChB,CAAC;CACH;CAQA,OAAe,GAAgB,GAAgB,GAAsC;EACnF,IAAI,CAACM,EAAc,KAAK,QAAA,IAAoC,KAAK,IAAI,aAAa,QAAQ,GACxF;EAGF,IAAMC,IAAM,KAAK,IAAI,GACfC,IAAUH,aAAiB,QAAQA,IAAY,MAAM,OAAOA,CAAK,CAAC,GAClEI,KAASD,EAAQ,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM,IAChDE,IAAM,GAAGF,EAAQ,KAAK,GAAGA,EAAQ,QAAQ,GAAGC,KAC5CE,IAAW,KAAK,KAAK,IAAID,CAAG;EAElC,IAAIC,KAAYJ,IAAMI,EAAS,KAAA,KAAsB;GAEnD,AADA,EAAS,SACT,EAAS,KAAKJ;GACd;EACF;EAIA,IAAMK,IAAaD,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOD,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIH;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACM,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,YAAY,KAAKM,IAASN,EAAQ,SAASA,GAAS;GAChF,GAAGO;GACH,qBAAqBD;GACrB,0BAA0BF;EAC5B,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests whether a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/utils/global-scope.ts
|
|
2
|
+
function e(e) {
|
|
3
|
+
let t = Symbol.for(e), n = globalThis, r = () => n[t] ?? 0;
|
|
4
|
+
return {
|
|
5
|
+
run(e) {
|
|
6
|
+
n[t] = r() + 1;
|
|
7
|
+
try {
|
|
8
|
+
return e();
|
|
9
|
+
} finally {
|
|
10
|
+
n[t] = r() - 1;
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
open: () => r() > 0
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { e as t };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=global-scope-dp2jADRl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global-scope-dp2jADRl.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests whether a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
|
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-B28fDv2F.cjs"),t=require("./sampling-E4x92Nn2.cjs"),n=require("./sanitize-BMhh8ghJ.cjs"),r=require("./platform-D_XkVIF6.cjs"),i=require("./unref-CU9Nyz_9.cjs");function a(t){return Math.round((performance.now()-t)*e.F)/e.F}function o(e,t,n,r,i){e.logMetric(`${t}.duration`,a(n),`ms`,`histogram`,{status:r,...i})}function s(e,t,n,r,i){e.error(`${t} failed`,r,{"action.duration_ms":a(n),status:`FAILURE`,...i})}function c(e,t,n,r){let i=performance.now();try{let a=n();return o(e,t,i,`SUCCESS`,r),a}catch(n){throw s(e,t,i,n,r),n}}async function l(e,t,n,r){let i=performance.now();try{let a=await n();return o(e,t,i,`SUCCESS`,r),a}catch(n){throw s(e,t,i,n,r),n}}function u(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 d(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 f=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)=>c(this,e,t,n);timeAsync=(e,t,n)=>l(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&&d(n),s=o?n:r,c=o||n===void 0?void 0:u(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:l}=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,l),i.emit(l)}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)}},p={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},m=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.at[t]>=e.at[this.settings.level]}write(t,r,i,a,o){if(!this.accepts(r)||typeof console>`u`||n.a())return;let s=`%c[%s]%c[${r}]%c`,{styles:c}=this.settings,l=p[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(n.n(a,e.Ct,this.diagnostics)),n.o(()=>{console[l](s,c.namespace,t,c[r],``,i,...u)})})}},h=class{value=0;next(){return++this.value}reset(){this.value=0}},g=/^[0-9a-f]{32}$/,_=/^[0-9a-f]{16}$/,v=/[1-9a-f]/;function y(e){return g.test(e.traceId)&&v.test(e.traceId)&&_.test(e.spanId)&&v.test(e.spanId)}function b(){return t.d(16)}function x(){return t.d(8)}function S(){return{traceId:b(),spanId:x(),traceFlags:1,startedAt:Date.now()}}function C(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var w=class{diagnostics;maxAgeMs;load;ambient=S();otel;constructor(t,n=e.fn,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`),C(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(y(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=S(),C(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.dn]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},T=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 E(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function D(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||E(t)?t:(r.report(`config.invalid`,`serializer must be "${e.qt}", "ecs" or an implementation. The library uses "${e.qt}".`),e.qt)}var O=new Set(Object.keys(e.D));function k(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)O.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 A(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,...k(t.styles,r)}}}function j(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:D(t.serializer,r?.serializer,n),console:A(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.transport!==void 0&&typeof a.transport!=`function`&&(n.report(`config.invalid`,`transport must be a function. The library ignores the value.`),a.transport=i.transport),a.transportOnExit!==void 0&&typeof a.transportOnExit!=`function`&&(n.report(`config.invalid`,`transportOnExit must be a function. The library ignores the value.`),a.transportOnExit=i.transportOnExit),a.endpoint===``)a.transport===void 0&&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.gn}'.`),e.gn);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=a.sampling.remoteMaxRate;(typeof s!=`number`||!(s>=0&&s<=1))&&(n.report(`config.invalid`,`sampling.remoteMaxRate must be 0..1. The value is ${String(s)}. The library uses 1.`),a.sampling.remoteMaxRate=1);let c=Object.entries(a.sampling.rates);for(let[e,t]of c)(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]),M(t,n),a}function M(t,n){let r=new Set([...Object.keys(e.j),...e.mn]);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.hn[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 N(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 P=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)}},ee=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,r,i,a){let o=this.count(t),s=Date.now();if(s-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,s);let c={code:t,message:r,detail:i,cause:a,at:s,count:o},{handler:l}=this;if(l)try{n.o(()=>{l(c)})}catch(t){this.count(`handler.threw`),typeof console<`u`&&n.o(()=>{console.warn(`${e.st} 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()}},te={maxAgeMs:e.nt,endOnOwnerClose:!1,urlParam:e.it};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.o){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.rt));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.l(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.rt):this.stores.session().setItem(e.rt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=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=r,i.t(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.rt)})}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.a(r.call(n),e.vt)))?.customData?.[e._t];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;if(!n.enabled)return!1;let r=this.deps.remote.sampling?.minLevel()??n.minLevel;return e.at[t]>=e.at[r]}build(i){let{config:a,diagnostics:o,tracing:s,journey:c,sequence:l,limits:u,remote:d}=this.deps;if(!this.isEnabled(i.level))return o.count(`record.dropped_by_level`),{record:null,dropped:`level`};let f=s.resolve(),p=c.current();if(!t.r({level:i.level,type:i.type,namespace:i.namespace,journeyId:p?.id??``,traceId:f.traceId},a,d.sampling?.current()??null))return o.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let m=l.next(),h=r.t(o),g=a.capture.fullUrls?h:r.r(h),_,v=0;try{let e=n.r(this.deps.context.getAll(),u,o),t=n.r(i.scoped??{},u,o),r=n.r(i.payload??{},u,o);v=e.bytes+t.bytes+r.bytes,_={...V(e.value),...V(t.value),...V(r.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),_={[e.d]:!0}}_[e.l]=i.type,_[e.c]=m,_[e.n]=i.namespace,_[e.u]=g,p&&(_[e.a]=p.id,_[e.o]=p.name,p.parentId!==void 0&&(_[e.s]=p.parentId));let y=n.i(i.body,u.maxBodyChars);y!==i.body&&o.count(`record.truncated`);let b={timeUnixNano:t.m(),traceId:f.traceId,spanId:f.spanId,traceFlags:f.traceFlags,severityNumber:e.Zt[i.level],severityText:i.level,body:y,attributes:_,resource:this.resource()},x=a.redact;if(x){let e=o.guard(`record.sanitize_failed`,`The redact hook threw an error.`,()=>x(b));if(e===null)return o.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==b){if(t.p(e)){let t=n.r(e.attributes,u,o);b={...e,attributes:V(t.value)},v=t.bytes}else o.report(`record.sanitize_failed`,`The redact hook returned a value that is not a record. The library keeps the original record.`)}}if(v>u.maxRecordBytes){o.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped them.`,{bytes:v,body:b.body});let t={[e.l]:i.type,[e.c]:m,[e.n]:i.namespace,[e.u]:g,[e.i]:!0,[e.r]:v};p&&(t[e.a]=p.id,t[e.o]=p.name),b.attributes=t}return{record:b}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Pt]:t.serviceName,[e.Ft]:t.serviceVersion,[e.At]:t.environment,[e.zt]:e.ln,[e.Bt]:e.un,[e.Rt]:e.cn,[e.jt]:r.platform,[e.It]:n.sessionId,[e.Lt]:n.tabId,[e.kt]:n.contextId,[e.Ot]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Nt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Mt]:r.openfinName}},this.resourceCache}},U={errors:async()=>(await Promise.resolve().then(()=>require("./errors-C78ZTjet.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-CZ0aFUsy.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-CsE2y_fQ.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-B2FYsEAU.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-DahhqM6u.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-PKzc-FmR.cjs"))).ConsoleCapture},W=Symbol.for(e.Wt),G=Symbol.for(e.Gt),K=class n{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new P;breadcrumbs;tracing;sequence=new h;journey;builder;remote={sampling:null};console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;started=Promise.resolve();ready=!1;destroyed=!1;lastGapAt=0;constructor(n){this.diagnostics=new ee(n.onDiagnostic),this.platform=r.n(this.diagnostics),this.config=j(n,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.c():t.o,this.identity=t.f(this.diagnostics,this.stores),this.sessionTouch=new t.s(this.diagnostics,this.stores),this.breadcrumbs=new T(50),this.tracing=new w(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new m(this.config.console,this.diagnostics),this.journey=new B(te,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new H({remote:this.remote,config:this.config,limits:e.Ct,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=n.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let r=new n(e);return globalThis[W]=r,Reflect.deleteProperty(globalThis,G),r.init(),r}reconfigure(e){let t=this.keepDestination(e);N(this.config,j(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)}keepDestination(e){if(this.senderLoad===void 0)return e;let t=e;return`transport`in e&&e.transport===void 0!=(this.config.transport===void 0)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove transport after the delivery stack loads. The transport in force stays.`),t={...t},delete t.transport),(t.endpoint===null||t.endpoint===``)&&this.config.transport===void 0&&(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),t={...t,endpoint:void 0}),t}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();this.started=this.boot(),await this.started,await e}async boot(){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()}}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-CUXRY0JR.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()},remote:this.remote});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.config.transport!==void 0)||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-B6ufz26f.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,remote:this.remote});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`),n.longFrames&&r.push(`longFrames`),(Array.isArray(n.console)?n.console.length>0:n.console)&&r.push(`console`);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 f(()=>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,n.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.p(n)?t.n(n,this.config,this.remote.sampling?.current()??null)?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 f(()=>this,e.tn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.l(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.u(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.ready||await this.started,this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}};function q(){let e=[],t=[],n={status:200};return{transport:r=>(e.push(r),n.status>=200&&n.status<300&&t.push(r),Promise.resolve({...n})),records:()=>t.flatMap(e=>[...e.records]),batches:()=>[...e],clear:()=>{e.length=0,t.length=0},respondWith:(e,t)=>{n=t===void 0?{status:e}:{status:e,retryAfterMs:t}}}}var J=new Map;function Y(){return(K.current()??K.stopped())||K.configure({})}function X(e){K.configure(e)}function Z(e,t){if(t)return new f(Y,e,t);let n=J.get(e);return n||(n=new f(Y,e),J.set(e,n)),n}function Q(){return Z(`app`)}function ne(e,t){Q().trace(e,t)}function re(e,t){Q().debug(e,t)}function ie(e,t){Q().info(e,t)}function ae(e,t){Q().warn(e,t)}function oe(e,t,n){Q().error(e,t,n)}function se(e,t){Q().logAction(e,t)}function ce(e,t){Q().logEvent(e,t)}function le(e,t,n,r,i){Q().logMetric(e,t,n,r,i)}function ue(e,t,n){return Q().timeSync(e,t,n)}function de(e,t,n){return Q().timeAsync(e,t,n)}function fe(e,t){Y().context.set(e,t)}function pe(e){Y().context.setMany(e)}function me(e){Y().context.remove(e)}function he(e,t){return Y().journey.start(e,t)}function ge(){Y().journey.end()}function _e(){return Y().journey.current()}function ve(){return Y().journey.getToken()}function ye(e){return Y().journey.adopt(e,`manual`,!0)}function be(e){Y().registerWorker(e)}function $(){Y().tracing.rotate(`explicit`)}function xe(){return Y().tracing.headers()}function Se(){return Y().flush()}function Ce(){return Y().queueDepth()}function we(){return Y().diagnostics.snapshot()}async function Te(){await K.current()?.destroy()}exports.OneLogger=f,exports.adoptJourney=ye,exports.configure=X,exports.createMemoryTransport=q,exports.currentJourney=_e,exports.debug=re,exports.endJourney=ge,exports.error=oe,exports.flush=Se,exports.getDiagnosticCounters=we,exports.getJourneyToken=ve,exports.getLogger=Z,exports.getQueueDepth=Ce,exports.getTraceHeaders=xe,exports.info=ie,exports.logAction=se,exports.logEvent=ce,exports.logMetric=le,exports.registerWorker=be,exports.removeContext=me,exports.setContext=fe,exports.setContextMap=pe,exports.shutdown=Te,exports.startJourney=he,exports.startTrace=$,exports.timeAsync=de,exports.timeSync=ue,exports.trace=ne,exports.warn=ae;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|