@utk09/ui-observability 0.9.3 → 0.9.5
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 +90 -0
- package/README.md +199 -96
- package/dist/batch-BQFtb3i5.cjs +2 -0
- package/dist/batch-BQFtb3i5.cjs.map +1 -0
- package/dist/{batch-DDgxg16_.js → batch-BUJh-1jZ.js} +6 -4
- package/dist/batch-BUJh-1jZ.js.map +1 -0
- package/dist/bus/bus.d.ts +76 -2
- package/dist/bus/links.d.ts +9 -2
- package/dist/bus/validation.d.ts +7 -0
- package/dist/bus-BW6N-pY8.cjs +2 -0
- package/dist/bus-BW6N-pY8.cjs.map +1 -0
- package/dist/bus-DeOPHWaD.js +647 -0
- package/dist/bus-DeOPHWaD.js.map +1 -0
- package/dist/capture/network.d.ts +1 -0
- package/dist/capture/storm.d.ts +2 -1
- package/dist/capture/types.d.ts +5 -0
- package/dist/capture/web-socket.d.ts +40 -0
- package/dist/{console-BSusX_M-.cjs → console-Ce6heqZZ.cjs} +2 -2
- package/dist/console-Ce6heqZZ.cjs.map +1 -0
- package/dist/{console-Dv5GfaNn.js → console-DbAZYJuy.js} +4 -4
- package/dist/console-DbAZYJuy.js.map +1 -0
- package/dist/constants-CN7GE1Lt.js +246 -0
- package/dist/constants-CN7GE1Lt.js.map +1 -0
- package/dist/constants-CW-MlHdY.cjs +2 -0
- package/dist/constants-CW-MlHdY.cjs.map +1 -0
- package/dist/constants.d.ts +63 -11
- package/dist/context-storage-BjzeBSxH.cjs +2 -0
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
- package/dist/context-storage-DxZf4Gfh.js +52 -0
- package/dist/context-storage-DxZf4Gfh.js.map +1 -0
- package/dist/core/breadcrumbs.d.ts +10 -3
- package/dist/core/context.d.ts +2 -0
- package/dist/core/diagnostics.d.ts +11 -3
- package/dist/core/journey.d.ts +7 -0
- package/dist/core/meter.d.ts +25 -2
- package/dist/core/pipeline.d.ts +41 -6
- package/dist/core/record.d.ts +42 -9
- package/dist/core/remote-sampling.d.ts +7 -3
- package/dist/core/runtime.d.ts +153 -6
- package/dist/core/sampling.d.ts +35 -2
- package/dist/core/sender.d.ts +43 -1
- package/dist/core/spans.d.ts +34 -0
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/emergency-queue-BYUyDHGD.js +69 -0
- package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
- package/dist/{errors-DCZWcHkd.js → errors-BhC7HTSt.js} +8 -9
- package/dist/errors-BhC7HTSt.js.map +1 -0
- package/dist/errors-CgY633cG.cjs +3 -0
- package/dist/errors-CgY633cG.cjs.map +1 -0
- package/dist/factory-C5TujXlU.js +280 -0
- package/dist/factory-C5TujXlU.js.map +1 -0
- package/dist/factory-CNj4DH3n.cjs +2 -0
- package/dist/factory-CNj4DH3n.cjs.map +1 -0
- package/dist/fixed-window-CtaFHanJ.js +12 -0
- package/dist/fixed-window-CtaFHanJ.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs +2 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
- package/dist/identity-8vKkyAWm.js +103 -0
- package/dist/identity-8vKkyAWm.js.map +1 -0
- package/dist/identity-Da9TkuKd.cjs +2 -0
- package/dist/identity-Da9TkuKd.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +66 -6
- package/dist/index.js +1253 -595
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
- package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
- package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-CCA1LvtO.js} +45 -30
- package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
- package/dist/{interactions-BLH_tX87.js → interactions-BUDLxbv1.js} +16 -12
- package/dist/interactions-BUDLxbv1.js.map +1 -0
- package/dist/interactions-NHbLKrqe.cjs +2 -0
- package/dist/interactions-NHbLKrqe.cjs.map +1 -0
- package/dist/{journey-yALMEWF7.js → journey-BUJ4WJxP.js} +37 -34
- package/dist/journey-BUJ4WJxP.js.map +1 -0
- package/dist/journey-B_tTnvac.cjs +2 -0
- package/dist/journey-B_tTnvac.cjs.map +1 -0
- package/dist/keys-BHhw_0Wh.cjs +2 -0
- package/dist/keys-BHhw_0Wh.cjs.map +1 -0
- package/dist/keys-D5r_GH9q.js +17 -0
- package/dist/keys-D5r_GH9q.js.map +1 -0
- package/dist/{library-request-CQD4HUiP.js → library-request-BKOcaKtQ.js} +3 -3
- package/dist/{library-request-CQD4HUiP.js.map → library-request-BKOcaKtQ.js.map} +1 -1
- package/dist/{library-request-BcAxuwsf.cjs → library-request-BaZOi4eg.cjs} +2 -2
- package/dist/{library-request-BcAxuwsf.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
- package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-CF3qiSAX.cjs} +2 -2
- package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
- package/dist/{long-frames-DD_Um9_4.js → long-frames-DI5ypfAF.js} +5 -5
- package/dist/long-frames-DI5ypfAF.js.map +1 -0
- package/dist/models/batch.d.ts +4 -0
- package/dist/models/bus.d.ts +32 -9
- package/dist/models/config.d.ts +401 -12
- package/dist/models/drop.d.ts +1 -1
- package/dist/models/health.d.ts +27 -0
- package/dist/models/log-record.d.ts +1 -1
- package/dist/models/plugin.d.ts +47 -0
- package/dist/models/stats.d.ts +11 -0
- package/dist/models/storage.d.ts +13 -0
- package/dist/network-CF8UO5PK.cjs +2 -0
- package/dist/network-CF8UO5PK.cjs.map +1 -0
- package/dist/{network--GoE7_Or.js → network-DdzXDI3J.js} +47 -31
- package/dist/network-DdzXDI3J.js.map +1 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{platform-GaM6h7XM.js → platform-Bw1btWCT.js} +21 -10
- package/dist/platform-Bw1btWCT.js.map +1 -0
- package/dist/platform-DBSKTvFn.cjs +2 -0
- package/dist/platform-DBSKTvFn.cjs.map +1 -0
- package/dist/remote-rules-DIcC5vVC.js +91 -0
- package/dist/remote-rules-DIcC5vVC.js.map +1 -0
- package/dist/remote-rules-DpFmOef2.cjs +2 -0
- package/dist/remote-rules-DpFmOef2.cjs.map +1 -0
- package/dist/sampling-BVjspJWu.cjs +2 -0
- package/dist/sampling-BVjspJWu.cjs.map +1 -0
- package/dist/sampling-Cm3WhI0a.js +76 -0
- package/dist/sampling-Cm3WhI0a.js.map +1 -0
- package/dist/{sanitize-DP0xDPrt.js → sanitize-C-ahCFsG.js} +2 -2
- package/dist/{sanitize-DP0xDPrt.js.map → sanitize-C-ahCFsG.js.map} +1 -1
- package/dist/{sanitize--_e4oOPX.cjs → sanitize-DHucKGdi.cjs} +2 -2
- package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
- package/dist/sender-D3fRCR8d.cjs +3 -0
- package/dist/sender-D3fRCR8d.cjs.map +1 -0
- package/dist/sender-DUUmSglb.js +1163 -0
- package/dist/sender-DUUmSglb.js.map +1 -0
- package/dist/storage/context-storage.d.ts +89 -0
- package/dist/storage/emergency-queue.d.ts +9 -1
- package/dist/storage/factory.d.ts +7 -1
- package/dist/storage/idb-driver.d.ts +13 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -0
- package/dist/storage/local-storage.d.ts +21 -1
- package/dist/storage/memory-storage.d.ts +13 -0
- package/dist/storage-BA9RqRO-.cjs +2 -0
- package/dist/storage-BA9RqRO-.cjs.map +1 -0
- package/dist/storage-w7Tslvlq.js +17 -0
- package/dist/storage-w7Tslvlq.js.map +1 -0
- package/dist/storm-CNZjsw4T.cjs +2 -0
- package/dist/storm-CNZjsw4T.cjs.map +1 -0
- package/dist/storm-Daq2jGHU.js +10 -0
- package/dist/storm-Daq2jGHU.js.map +1 -0
- package/dist/transport/exit-flush.d.ts +6 -0
- package/dist/transport/http-transport.d.ts +2 -1
- package/dist/transport/retry-engine.d.ts +7 -2
- package/dist/transport/serializers/otlp-traces.d.ts +3 -0
- package/dist/transport/serializers/select.d.ts +8 -5
- package/dist/transport/status-transport.d.ts +24 -0
- package/dist/types-BR9t_w28.js +8 -0
- package/dist/types-BR9t_w28.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs +2 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -0
- package/dist/utils/fixed-window.d.ts +9 -0
- package/dist/utils/identity.d.ts +20 -2
- package/dist/utils/lock.d.ts +8 -0
- package/dist/utils/openfin.d.ts +1 -1
- package/dist/utils/platform.d.ts +10 -0
- package/dist/utils/tracing.d.ts +82 -4
- package/dist/web-socket-BacvKOvD.cjs +2 -0
- package/dist/web-socket-BacvKOvD.cjs.map +1 -0
- package/dist/web-socket-CpsD8WAa.js +105 -0
- package/dist/web-socket-CpsD8WAa.js.map +1 -0
- package/package.json +1 -1
- package/dist/batch-D5qvsMQ_.cjs +0 -2
- package/dist/batch-D5qvsMQ_.cjs.map +0 -1
- package/dist/batch-DDgxg16_.js.map +0 -1
- package/dist/bus-C6RwKzPW.js +0 -478
- package/dist/bus-C6RwKzPW.js.map +0 -1
- package/dist/bus-WPVDFw2y.cjs +0 -2
- package/dist/bus-WPVDFw2y.cjs.map +0 -1
- package/dist/console-BSusX_M-.cjs.map +0 -1
- package/dist/console-Dv5GfaNn.js.map +0 -1
- package/dist/constants-Cb92egPS.cjs +0 -2
- package/dist/constants-Cb92egPS.cjs.map +0 -1
- package/dist/constants-DhH6VI5a.js +0 -144
- package/dist/constants-DhH6VI5a.js.map +0 -1
- package/dist/deadline-CUrH0Hd8.cjs +0 -2
- package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
- package/dist/deadline-DeqXEliN.js +0 -31
- package/dist/deadline-DeqXEliN.js.map +0 -1
- package/dist/errors-DCZWcHkd.js.map +0 -1
- package/dist/errors-ERu-su8m.cjs +0 -3
- package/dist/errors-ERu-su8m.cjs.map +0 -1
- package/dist/fixed-window-BR0bu32Y.cjs +0 -2
- package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
- package/dist/fixed-window-Re7jIRJH.js +0 -9
- package/dist/fixed-window-Re7jIRJH.js.map +0 -1
- package/dist/identity-C1WLItSl.cjs +0 -2
- package/dist/identity-C1WLItSl.cjs.map +0 -1
- package/dist/identity-Di-QXGCC.js +0 -88
- package/dist/identity-Di-QXGCC.js.map +0 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +0 -2
- package/dist/indexeddb-storage-DX18p39D.cjs.map +0 -1
- package/dist/indexeddb-storage-T9YIYVYC.js.map +0 -1
- package/dist/interactions-BLH_tX87.js.map +0 -1
- package/dist/interactions-_hfOerfC.cjs +0 -2
- package/dist/interactions-_hfOerfC.cjs.map +0 -1
- package/dist/journey-BRUj0hqD.cjs +0 -2
- package/dist/journey-BRUj0hqD.cjs.map +0 -1
- package/dist/journey-yALMEWF7.js.map +0 -1
- package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
- package/dist/long-frames-DD_Um9_4.js.map +0 -1
- package/dist/network--GoE7_Or.js.map +0 -1
- package/dist/network-DcuS2H1P.cjs +0 -2
- package/dist/network-DcuS2H1P.cjs.map +0 -1
- package/dist/platform-GaM6h7XM.js.map +0 -1
- package/dist/platform-kIL5AZB7.cjs +0 -2
- package/dist/platform-kIL5AZB7.cjs.map +0 -1
- package/dist/remote-rules-6ePq8CrI.js +0 -84
- package/dist/remote-rules-6ePq8CrI.js.map +0 -1
- package/dist/remote-rules-CI3gbRCL.cjs +0 -2
- package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
- package/dist/sampling-C-M8p3FK.cjs +0 -2
- package/dist/sampling-C-M8p3FK.cjs.map +0 -1
- package/dist/sampling-Ud_WiuU9.js +0 -65
- package/dist/sampling-Ud_WiuU9.js.map +0 -1
- package/dist/sender-BESHz6my.cjs +0 -3
- package/dist/sender-BESHz6my.cjs.map +0 -1
- package/dist/sender-BUBWLn5i.js +0 -1244
- package/dist/sender-BUBWLn5i.js.map +0 -1
- package/dist/storm-DhHGHhOc.cjs +0 -2
- package/dist/storm-DhHGHhOc.cjs.map +0 -1
- package/dist/storm-OD5J6Ylm.js +0 -10
- package/dist/storm-OD5J6Ylm.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-CF8UO5PK.cjs","names":["isErrorLike","isLibraryRequest","matchesAny","patch","recordedUrl","isTransportPending","require_error_like","require_library_request","require_platform","require_patch","require_types","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","span","endMs","rounded","xhr"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n )\n return;\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":"kMAgBA,IAAMW,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIC,EAAKH,CAAI,CAAC,CAAC,QACvC,EAEA,GAAII,IAAW,EAAG,CAEhB,IAAMC,EAAOnB,EAAAA,EAAYoB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS,GAAK,SAAWA,EAC7CJ,CACT,CAOA,MALA,GAAW,6BAA+BG,EACtCA,GAAU,MACZ,EAAW,cAAgB,OAAOA,CAAM,GAGnCH,CACT,CA4BA,SAASM,GAAyB,CAChC,OAAO,eAAe,SACxB,CAyBA,SAASC,EAAQ,EAAwB,CACvC,GAAI,OAAOC,GAAU,SACnB,OAAOA,EAGT,GAAIA,aAAiB,IACnB,OAAOA,EAAM,KAGf,GAAI,OAAOA,GAAU,UAAYA,EAAgB,CAC/C,GAAM,CAAE,OAAQA,EAChB,GAAI,OAAON,GAAQ,SACjB,OAAOA,CAEX,CAGA,OAAO,OAAOM,CAAK,CACrB,CAQA,SAASC,EAAgB,EAAgB,EAAuC,CAC9E,IAAIC,EAAqBC,GAAM,OAM/B,OAJID,IAAc,IAAA,IAAa,OAAOF,GAAU,UAAYA,IAC1D,EAAaA,EAA+B,QAGvCI,EAASF,GAAa,KAAK,CACpC,CAQA,SAASG,EAAe,EAAyB,CAC/C,OAAO,OAAOL,GAAU,UAAY,EAAEA,aAAiB,MAAQ,EAAEA,aAAiB,QACpF,CAOA,SA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1,8 @@
|
|
|
1
1
|
import { r as e } from "./error-like-Ywo5uRHo.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { n as t, t as n } from "./library-request-BKOcaKtQ.js";
|
|
3
|
+
import { i as r } from "./platform-Bw1btWCT.js";
|
|
4
4
|
import { t as i } from "./patch-CCWfuEY7.js";
|
|
5
|
-
|
|
6
|
-
function a(e, t) {
|
|
7
|
-
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
8
|
-
}
|
|
9
|
-
//#endregion
|
|
5
|
+
import { t as a } from "./types-BR9t_w28.js";
|
|
10
6
|
//#region src/capture/network.ts
|
|
11
7
|
var o = 1e3, s = {
|
|
12
8
|
name: "http.client.request.duration",
|
|
@@ -81,7 +77,7 @@ var m = class {
|
|
|
81
77
|
}
|
|
82
78
|
}
|
|
83
79
|
ignored(e) {
|
|
84
|
-
return
|
|
80
|
+
return n() || a(e, this.ctx.config.capture.ignoreUrls);
|
|
85
81
|
}
|
|
86
82
|
propagates(e) {
|
|
87
83
|
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
@@ -91,8 +87,8 @@ var m = class {
|
|
|
91
87
|
}
|
|
92
88
|
installFetch() {
|
|
93
89
|
if (typeof globalThis.fetch != "function") return;
|
|
94
|
-
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r
|
|
95
|
-
this.record(e, t, n, r,
|
|
90
|
+
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r) => {
|
|
91
|
+
this.record(e.method, e.url, t, n, r, e.span, e.routingContextId);
|
|
96
92
|
}, r = i(globalThis, "fetch", (r) => {
|
|
97
93
|
let i = r.bind(globalThis);
|
|
98
94
|
return async function(r, a) {
|
|
@@ -101,9 +97,9 @@ var m = class {
|
|
|
101
97
|
let s = performance.now();
|
|
102
98
|
try {
|
|
103
99
|
let e = await i(o.input, o.init);
|
|
104
|
-
return n(o
|
|
100
|
+
return n(o, e.status, performance.now() - s, void 0), e;
|
|
105
101
|
} catch (e) {
|
|
106
|
-
throw n(o
|
|
102
|
+
throw n(o, 0, performance.now() - s, e), e;
|
|
107
103
|
}
|
|
108
104
|
};
|
|
109
105
|
});
|
|
@@ -125,23 +121,25 @@ var m = class {
|
|
|
125
121
|
method: r,
|
|
126
122
|
url: i,
|
|
127
123
|
input: e,
|
|
128
|
-
init: t
|
|
124
|
+
init: t,
|
|
125
|
+
routingContextId: this.ctx.config.securityContext.id
|
|
129
126
|
};
|
|
130
127
|
if (!n.propagate || f(e)) return a;
|
|
131
128
|
try {
|
|
132
|
-
let n =
|
|
129
|
+
let n = this.ctx.tracing.request(), r = Object.entries(n.headers);
|
|
133
130
|
if (e instanceof Request) {
|
|
134
131
|
let t = new Headers(e.headers);
|
|
135
|
-
for (let [e,
|
|
132
|
+
for (let [e, n] of r) t.set(e, n);
|
|
136
133
|
a.input = new Request(e, { headers: t });
|
|
137
134
|
} else {
|
|
138
135
|
let e = new Headers(t?.headers);
|
|
139
|
-
for (let [t,
|
|
136
|
+
for (let [t, n] of r) e.set(t, n);
|
|
140
137
|
a.init = {
|
|
141
138
|
...t,
|
|
142
139
|
headers: e
|
|
143
140
|
};
|
|
144
141
|
}
|
|
142
|
+
a.span = n.span;
|
|
145
143
|
} catch (n) {
|
|
146
144
|
a.input = e, a.init = t, this.ctx.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: i }, n);
|
|
147
145
|
}
|
|
@@ -149,8 +147,8 @@ var m = class {
|
|
|
149
147
|
}
|
|
150
148
|
installXhr() {
|
|
151
149
|
if (typeof XMLHttpRequest > "u") return;
|
|
152
|
-
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n
|
|
153
|
-
this.record(e, t, n,
|
|
150
|
+
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n) => {
|
|
151
|
+
this.record(e.method, e.url, t, n, void 0, e.span, e.routingContextId);
|
|
154
152
|
}, o = l(), s = i(o, "open", (n) => function(r, i, ...a) {
|
|
155
153
|
e && t.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
156
154
|
this.__uiobs = {
|
|
@@ -166,46 +164,64 @@ var m = class {
|
|
|
166
164
|
}), c = i(o, "send", (i) => function(...o) {
|
|
167
165
|
let s = e ? this.__uiobs : void 0;
|
|
168
166
|
s && t.diagnostics.guard("capture.record_failed", `The library could not record ${s.method} ${s.url}.`, () => {
|
|
169
|
-
n(s.url) || (s.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
170
|
-
a(s
|
|
171
|
-
}), r(s.url) && h(this, s.url, t));
|
|
167
|
+
n(s.url) || (s.startedAt = performance.now(), s.routingContextId = t.config.securityContext.id, this.addEventListener("loadend", () => {
|
|
168
|
+
a(s, this.status, performance.now() - s.startedAt);
|
|
169
|
+
}, { once: !0 }), r(s.url) && (s.span = h(this, s.url, t)));
|
|
172
170
|
}), i.apply(this, o);
|
|
173
171
|
});
|
|
174
172
|
this.restores.push(() => {
|
|
175
173
|
e = !1, s(), c();
|
|
176
174
|
});
|
|
177
175
|
}
|
|
178
|
-
record(e,
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
176
|
+
record(e, n, i, a, l, u, d) {
|
|
177
|
+
if (this.ctx.isActive?.() === !1 || this.ctx.config.securityContext.isolation && d !== void 0 && d !== this.ctx.config.securityContext.id) return;
|
|
178
|
+
let f = r(n, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics);
|
|
179
|
+
!this.warnedTransport && t() && (this.warnedTransport = !0, this.ctx.diagnostics.report("capture.transport_request", `Network capture saw ${e} ${f} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)), this.ctx.config.capture.httpMetrics && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the duration of ${e} ${f}.`, () => {
|
|
180
|
+
let t = c(e, n, i, l);
|
|
182
181
|
this.ctx.recordMetric(s, a / o, t);
|
|
183
|
-
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${
|
|
182
|
+
}), u && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the span of ${e} ${f}.`, () => {
|
|
183
|
+
let t = Date.now();
|
|
184
|
+
this.ctx.recordSpan({
|
|
185
|
+
...u,
|
|
186
|
+
name: e,
|
|
187
|
+
kind: "client",
|
|
188
|
+
startMs: t - a,
|
|
189
|
+
endMs: t,
|
|
190
|
+
error: i === 0 || i >= 400,
|
|
191
|
+
attributes: {
|
|
192
|
+
...c(e, n, i, l),
|
|
193
|
+
"url.full": f
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${f}.`, () => {
|
|
184
197
|
let t = Math.round(a);
|
|
185
198
|
this.ctx.breadcrumbs.push({
|
|
186
199
|
t: Date.now(),
|
|
187
200
|
category: "http",
|
|
188
|
-
message: `${e} ${
|
|
201
|
+
message: `${e} ${f} ${i === 0 ? "failed" : String(i)}`,
|
|
189
202
|
data: { durationMs: t }
|
|
190
203
|
});
|
|
191
204
|
let n = {
|
|
192
205
|
"http.request.method": e,
|
|
193
|
-
"url.full":
|
|
206
|
+
"url.full": f,
|
|
194
207
|
"http.response.status_code": i,
|
|
195
208
|
"http.duration_ms": t
|
|
196
209
|
};
|
|
197
|
-
i === 0 ? this.ctx.logger.error(`${e} ${
|
|
210
|
+
i === 0 ? this.ctx.logger.error(`${e} ${f} failed`, l, n) : i >= 400 ? this.ctx.logger.warn(`${e} ${f} returned ${String(i)}`, n) : this.ctx.logger.debug(`${e} ${f}`, n);
|
|
198
211
|
});
|
|
199
212
|
}
|
|
200
213
|
};
|
|
201
214
|
function h(e, t, n) {
|
|
202
215
|
try {
|
|
203
|
-
|
|
216
|
+
let t = n.tracing.request();
|
|
217
|
+
for (let [n, r] of Object.entries(t.headers)) e.setRequestHeader(n, r);
|
|
218
|
+
return t.span;
|
|
204
219
|
} catch (e) {
|
|
205
220
|
n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
|
|
221
|
+
return;
|
|
206
222
|
}
|
|
207
223
|
}
|
|
208
224
|
//#endregion
|
|
209
225
|
export { m as NetworkCapture };
|
|
210
226
|
|
|
211
|
-
//# sourceMappingURL=network
|
|
227
|
+
//# sourceMappingURL=network-DdzXDI3J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-DdzXDI3J.js","names":["isErrorLike","isTransportPending","isLibraryRequest","recordedUrl","patch","matchesAny","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","span","endMs","rounded"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n )\n return;\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAMM,IAAgB,KAM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/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":";AAsDA,SAAgBA,IAA8B;CAC5C,OAAQ,WAAiC;AAC3C"}
|
|
1
|
+
{"version":3,"file":"openfin-BwEN0uj4.js","names":["getFin"],"sources":["../src/utils/openfin.ts"],"sourcesContent":["// src/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown, uuid?: string, name?: string) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":";AAsDA,SAAgBA,IAA8B;CAC5C,OAAQ,WAAiC;AAC3C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openfin-DtH2f7zX.cjs","names":["getFin"],"sources":["../src/utils/openfin.ts"],"sourcesContent":["// src/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":"AAsDA,SAAgBA,GAA8B,CAC5C,OAAQ,WAAiC,GAC3C"}
|
|
1
|
+
{"version":3,"file":"openfin-DtH2f7zX.cjs","names":["getFin"],"sources":["../src/utils/openfin.ts"],"sourcesContent":["// src/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown, uuid?: string, name?: string) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":"AAsDA,SAAgBA,GAA8B,CAC5C,OAAQ,WAAiC,GAC3C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Et as e,
|
|
1
|
+
import { Et as e, jt as t, n, st as r, xt as i } from "./constants-CN7GE1Lt.js";
|
|
2
2
|
import { t as a } from "./openfin-BwEN0uj4.js";
|
|
3
3
|
//#region src/utils/platform.ts
|
|
4
4
|
var o = null;
|
|
@@ -6,10 +6,10 @@ function s(e, t) {
|
|
|
6
6
|
let n = e[t];
|
|
7
7
|
return n !== void 0 && e instanceof n;
|
|
8
8
|
}
|
|
9
|
-
function c(
|
|
9
|
+
function c(e) {
|
|
10
10
|
if (o) return o;
|
|
11
11
|
let n = globalThis, r = n.navigator?.userAgent ?? "", i = "browser", c, d, f = !1, p = a()?.me;
|
|
12
|
-
return s(n, "ServiceWorkerGlobalScope") ? (i = "service_worker", f = !0) : s(n, "SharedWorkerGlobalScope") ? (i = "shared_worker", f = !0) : s(n, "WorkerGlobalScope") ? (i = "web_worker", f = !0) : p === void 0 ? n.Capacitor !== void 0 || n.Ionic !== void 0 ? i = "ionic" : n.cordova !== void 0 || l(r) ? i = "mobile_webview" : typeof document > "u" && typeof process < "u" && (i = "node") : (i =
|
|
12
|
+
return s(n, "ServiceWorkerGlobalScope") ? (i = "service_worker", f = !0) : s(n, "SharedWorkerGlobalScope") ? (i = "shared_worker", f = !0) : s(n, "WorkerGlobalScope") ? (i = "web_worker", f = !0) : p === void 0 ? n.Capacitor !== void 0 || n.Ionic !== void 0 ? i = "ionic" : n.cordova !== void 0 || l(r) ? i = "mobile_webview" : typeof document > "u" && typeof process < "u" && (i = "node") : (i = t.test(r) ? "openfin" : "openfin_web", e.guard("openfin.unavailable", "The library could not read fin.me.identity.", () => {
|
|
13
13
|
let e = p.identity;
|
|
14
14
|
c = e?.uuid, d = e?.name;
|
|
15
15
|
})), o = {
|
|
@@ -18,11 +18,11 @@ function c(t) {
|
|
|
18
18
|
openfinName: d,
|
|
19
19
|
userAgent: r,
|
|
20
20
|
isWorker: f,
|
|
21
|
-
isTopLevelDocument: u(
|
|
21
|
+
isTopLevelDocument: u(e)
|
|
22
22
|
}, o;
|
|
23
23
|
}
|
|
24
|
-
function l(
|
|
25
|
-
return
|
|
24
|
+
function l(t) {
|
|
25
|
+
return n.test(t) ? !0 : (r.test(t) || i.test(t) && e.test(t)) && t.includes("AppleWebKit") && !t.includes("Safari/");
|
|
26
26
|
}
|
|
27
27
|
function u(e) {
|
|
28
28
|
if (typeof window > "u") return !1;
|
|
@@ -39,14 +39,25 @@ function d(e) {
|
|
|
39
39
|
return e.count("platform.api_blocked"), "";
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
|
-
|
|
42
|
+
var f = /^([a-z][a-z\d+.-]*:\/\/)[^/?#]*@/i;
|
|
43
|
+
function p(e, t, n, r) {
|
|
44
|
+
if (n) try {
|
|
45
|
+
let t = n(e);
|
|
46
|
+
return typeof t == "string" ? t : "";
|
|
47
|
+
} catch (e) {
|
|
48
|
+
return r?.report("capture.record_failed", "capture.urlTransform threw an error. The library records an empty URL.", void 0, e), "";
|
|
49
|
+
}
|
|
50
|
+
let i = e.replace(f, "$1");
|
|
51
|
+
return t ? i : m(i);
|
|
52
|
+
}
|
|
53
|
+
function m(e) {
|
|
43
54
|
let t = e.search(/[?#]/);
|
|
44
55
|
return t === -1 ? e : e.slice(0, t);
|
|
45
56
|
}
|
|
46
|
-
function
|
|
57
|
+
function h() {
|
|
47
58
|
return globalThis.navigator?.onLine !== !1;
|
|
48
59
|
}
|
|
49
60
|
//#endregion
|
|
50
|
-
export {
|
|
61
|
+
export { p as i, c as n, h as r, d as t };
|
|
51
62
|
|
|
52
|
-
//# sourceMappingURL=platform-
|
|
63
|
+
//# sourceMappingURL=platform-Bw1btWCT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-Bw1btWCT.js","names":["MOBILE_UA_PATTERN","OPENFIN_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","getFin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","ANDROID_WEBVIEW_UA_PATTERN","currentUrl","USER_INFO_PATTERN","recordedUrl","transform","value","url","error","bare","fullUrls","stripUrlQuery","cut","isOnline"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { getFin } from \"./openfin\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = getFin()?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @param transform Value of `capture.urlTransform`. It replaces the default rule.\n * @param diagnostics Diagnostics reporter for a transform that throws.\n * @returns The URL to record.\n */\nexport function recordedUrl(\n url: string,\n fullUrls: boolean,\n transform?: (url: string) => string | null,\n diagnostics?: Diagnostics,\n): string {\n if (transform) {\n try {\n const value = transform(url);\n return typeof value === \"string\" ? value : \"\";\n } catch (error) {\n // Report the fault. Without a report, each recorded URL is empty with no visible cause.\n diagnostics?.report(\n \"capture.record_failed\",\n \"capture.urlTransform threw an error. The library records an empty URL.\",\n undefined,\n error,\n );\n return \"\";\n }\n }\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;;AAkDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAOA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAAQZ,EAAO,CAAC,EAAE;CAkCxB,OAhCIE,EAAcE,GAAG,0BAA0B,KA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KAAU,WAAWA,IAAQ;CAC7C,SAASE,GAAO;EAQd,OANAV,GAAa,OACX,yBACA,0EACA,KAAA,GACAU,CACF,GACO;CACT;CAEF,IAAMC,IAAOF,EAAI,QAAQJ,GAAmB,IAAI;CAChD,OAAOO,IAAWD,IAAOE,EAAcF,CAAI;AAC7C;AAQA,SAAgBE,EAAc,GAAqB;CACjD,IAAMC,IAAML,EAAI,OAAO,MAAM;CAE7B,OAAOK,MAAQ,KAAKL,IAAMA,EAAI,MAAM,GAAGK,CAAG;AAC5C;AAMA,SAAgBC,IAAoB;CAClC,OAAQ,WAAoD,WAAW,WAAW;AACpF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-CW-MlHdY.cjs"),t=require("./openfin-DtH2f7zX.cjs");var n=null;function r(e,t){let n=e[t];return n!==void 0&&e instanceof n}function i(i){if(n)return n;let s=globalThis,c=s.navigator?.userAgent??``,l=`browser`,u,d,f=!1,p=t.t()?.me;return r(s,`ServiceWorkerGlobalScope`)?(l=`service_worker`,f=!0):r(s,`SharedWorkerGlobalScope`)?(l=`shared_worker`,f=!0):r(s,`WorkerGlobalScope`)?(l=`web_worker`,f=!0):p===void 0?s.Capacitor!==void 0||s.Ionic!==void 0?l=`ionic`:s.cordova!==void 0||a(c)?l=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(l=`node`):(l=e.jt.test(c)?`openfin`:`openfin_web`,i.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=p.identity;u=e?.uuid,d=e?.name})),n={platform:l,openfinUuid:u,openfinName:d,userAgent:c,isWorker:f,isTopLevelDocument:o(i)},n}function a(t){return e.n.test(t)?!0:(e.st.test(t)||e.xt.test(t)&&e.Et.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function o(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function s(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}var c=/^([a-z][a-z\d+.-]*:\/\/)[^/?#]*@/i;function l(e,t,n,r){if(n)try{let t=n(e);return typeof t==`string`?t:``}catch(e){return r?.report(`capture.record_failed`,`capture.urlTransform threw an error. The library records an empty URL.`,void 0,e),``}let i=e.replace(c,`$1`);return t?i:u(i)}function u(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function d(){return globalThis.navigator?.onLine!==!1}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
+
//# sourceMappingURL=platform-DBSKTvFn.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-DBSKTvFn.cjs","names":["getFin","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","require_openfin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","USER_INFO_PATTERN","recordedUrl","transform","value","url","error","bare","fullUrls","stripUrlQuery","cut","isOnline"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { getFin } from \"./openfin\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = getFin()?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @param transform Value of `capture.urlTransform`. It replaces the default rule.\n * @param diagnostics Diagnostics reporter for a transform that throws.\n * @returns The URL to record.\n */\nexport function recordedUrl(\n url: string,\n fullUrls: boolean,\n transform?: (url: string) => string | null,\n diagnostics?: Diagnostics,\n): string {\n if (transform) {\n try {\n const value = transform(url);\n return typeof value === \"string\" ? value : \"\";\n } catch (error) {\n // Report the fault. Without a report, each recorded URL is empty with no visible cause.\n diagnostics?.report(\n \"capture.record_failed\",\n \"capture.urlTransform threw an error. The library records an empty URL.\",\n undefined,\n error,\n );\n return \"\";\n }\n }\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"gFAkDA,IAAIQ,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,E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AAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAGA,IAAMI,EAAoB,oCAW1B,SAAgBC,EACd,EACA,EACA,EACA,EACQ,CACR,GAAIC,EACF,GAAI,CACF,IAAMC,EAAQD,EAAUE,CAAG,EAC3B,OAAO,OAAOD,GAAU,SAAWA,EAAQ,EAC7C,OAASE,EAAO,CAQd,OANAT,GAAa,OACX,wBACA,yEACA,IAAA,GACAS,CACF,EACO,EACT,CAEF,IAAMC,EAAOF,EAAI,QAAQJ,EAAmB,IAAI,EAChD,OAAOO,EAAWD,EAAOE,EAAcF,CAAI,CAC7C,CAQA,SAAgBE,EAAc,EAAqB,CACjD,IAAMC,EAAML,EAAI,OAAO,MAAM,EAE7B,OAAOK,IAAQ,GAAKL,EAAMA,EAAI,MAAM,EAAGK,CAAG,CAC5C,CAMA,SAAgBC,GAAoB,CAClC,OAAQ,WAAoD,WAAW,SAAW,EACpF"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { It as e, Lt as t, mt as n } from "./constants-CN7GE1Lt.js";
|
|
2
|
+
import { n as r, r as i, u as a } from "./sampling-Cm3WhI0a.js";
|
|
3
|
+
//#region src/core/remote-sampling.ts
|
|
4
|
+
var o = class {
|
|
5
|
+
config;
|
|
6
|
+
rules = null;
|
|
7
|
+
receivedAt = 0;
|
|
8
|
+
until = 0;
|
|
9
|
+
constructor(e) {
|
|
10
|
+
this.config = e;
|
|
11
|
+
}
|
|
12
|
+
apply(e) {
|
|
13
|
+
if (!e) {
|
|
14
|
+
this.rules = null;
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
let t = Date.now();
|
|
18
|
+
this.rules = e.rules, this.receivedAt = t, this.until = t + e.ttlMs;
|
|
19
|
+
}
|
|
20
|
+
current() {
|
|
21
|
+
if (!this.rules) return null;
|
|
22
|
+
let e = Date.now();
|
|
23
|
+
return !this.config.sampling.remote || e < this.receivedAt || e >= this.until ? (this.rules = null, null) : this.rules;
|
|
24
|
+
}
|
|
25
|
+
minLevelFor(e) {
|
|
26
|
+
let t = r(e, this.config), a = this.current(), o = i(e, a?.minLevels ?? {})?.value ?? a?.minLevel;
|
|
27
|
+
return o !== void 0 && n[o] < n[t] ? o : t;
|
|
28
|
+
}
|
|
29
|
+
wire() {
|
|
30
|
+
let e = this.current();
|
|
31
|
+
return e ? {
|
|
32
|
+
...e,
|
|
33
|
+
v: 1,
|
|
34
|
+
ttlMs: this.until - Date.now()
|
|
35
|
+
} : null;
|
|
36
|
+
}
|
|
37
|
+
}, s = class extends Error {};
|
|
38
|
+
function c(e) {
|
|
39
|
+
return typeof e == "number" && e >= 0 && e <= 1;
|
|
40
|
+
}
|
|
41
|
+
function l(t) {
|
|
42
|
+
if (t.length > 4096) throw new s(`The header is longer than ${String(e)} characters.`);
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(t);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new s("The header is not valid JSON.");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function u(e) {
|
|
50
|
+
if (e === void 0) return {};
|
|
51
|
+
let t = "rates must be an object with at most 100 rates from 0 to 1.";
|
|
52
|
+
if (!a(e)) throw new s(t);
|
|
53
|
+
let n = Object.entries(e);
|
|
54
|
+
if (n.length > 100 || !n.every(([, e]) => c(e))) throw new s(t);
|
|
55
|
+
return Object.fromEntries(n);
|
|
56
|
+
}
|
|
57
|
+
function d(e) {
|
|
58
|
+
let t = "minLevels must be an object with at most 100 level names.";
|
|
59
|
+
if (!a(e)) throw new s(t);
|
|
60
|
+
let r = Object.entries(e), i = r.every(([, e]) => typeof e == "string" && Object.hasOwn(n, e));
|
|
61
|
+
if (r.length > 100 || !i) throw new s(t);
|
|
62
|
+
return Object.fromEntries(r);
|
|
63
|
+
}
|
|
64
|
+
function f(e) {
|
|
65
|
+
if (!a(e)) throw new s("The rules must be an object.");
|
|
66
|
+
if (e.v !== 1) throw new s("The version must be 1.");
|
|
67
|
+
let { ttlMs: r, defaultRate: i, minLevel: o } = e;
|
|
68
|
+
if (typeof r != "number" || !(r > 0 && r <= 36e5)) throw new s(`ttlMs must be a number more than 0 and at most ${String(t)}.`);
|
|
69
|
+
if (i !== void 0 && !c(i)) throw new s("defaultRate must be a number from 0 to 1.");
|
|
70
|
+
if (o !== void 0 && !(typeof o == "string" && Object.hasOwn(n, o))) throw new s("minLevel must be a level name, for example DEBUG.");
|
|
71
|
+
let l = { rates: u(e.rates) };
|
|
72
|
+
return i !== void 0 && (l.defaultRate = i), o !== void 0 && (l.minLevel = o), e.minLevels !== void 0 && (l.minLevels = d(e.minLevels)), {
|
|
73
|
+
rules: l,
|
|
74
|
+
ttlMs: r
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function p(e, t) {
|
|
78
|
+
try {
|
|
79
|
+
return f(typeof e == "string" ? l(e) : e);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
let n = e instanceof s ? ` ${e.message}` : "";
|
|
82
|
+
return t.report("config.invalid", `The library ignores the sampling rules from the server.${n}`, void 0, e), null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function m(e, t, n) {
|
|
86
|
+
n && (e.sampling ??= new o(t)), e.sampling?.apply(n);
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { p as n, m as t };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=remote-rules-DIcC5vVC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote-rules-DIcC5vVC.js","names":["REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","levelFor","longestPrefix","isObject","RemoteSampling","config","update","now","local","namespace","rules","remote","RuleError","isRate","value","parseText","text","readRates","rule","entries","rate","readMinLevels","valid","level","readRules","ttlMs","defaultRate","minLevel","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { levelFor, longestPrefix } from \"./sampling\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n /** Lowest level for each namespace prefix. It can only lower the level of the config. */\n minLevels?: Record<string, LogLevel>;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends for a namespace. A remote prefix level wins\n * over the remote `minLevel`. A remote level applies only when it is lower than the config level.\n * @param namespace Target application namespace.\n * @returns The lower of the remote level and the config level of the namespace.\n */\n minLevelFor(namespace: string): LogLevel {\n const local = levelFor(namespace, this.config);\n const rules = this.current();\n const remote = longestPrefix(namespace, rules?.minLevels ?? {})?.value ?? rules?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[local] ? remote : local;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Reads the level for each namespace prefix.\n * @param value Value of `minLevels`.\n * @returns The levels.\n * @throws RuleError when a level is not valid.\n */\nfunction readMinLevels(value: unknown): Record<string, LogLevel> {\n const rule = `minLevels must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} level names.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n const valid = entries.every(\n ([, level]) => typeof level === \"string\" && Object.hasOwn(LEVEL_ORDER, level),\n );\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !valid) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, LogLevel>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n if (value.minLevels !== undefined) {\n rules.minLevels = readMinLevels(value.minLevels);\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":";;;AA8CA,IAAaM,IAAb,MAA4B;CAaG;CAX7B,QAAoC;CAGpC,aAAqB;CAGrB,QAAgB;CAKhB,YAAY,GAAyC;EAAxB,KAAA,SAAAC;CAAyB;CAMtD,MAAM,GAAmC;EACvC,IAAI,CAACC,GAAQ;GACX,KAAK,QAAQ;GACb;EACF;EAEA,IAAMC,IAAM,KAAK,IAAI;EAIrB,AAFA,KAAK,QAAQD,EAAO,OACpB,KAAK,aAAaC,GAClB,KAAK,QAAQA,IAAMD,EAAO;CAC5B;CAMA,UAA8B;EAC5B,IAAI,CAAC,KAAK,OACR,OAAO;EAGT,IAAMC,IAAM,KAAK,IAAI;EASrB,OALI,CAAC,KAAK,OAAO,SAAS,UAAUA,IAAM,KAAK,cAAcA,KAAO,KAAK,SACvE,KAAK,QAAQ,MACN,QAGF,KAAK;CACd;CAQA,YAAY,GAA6B;EACvC,IAAMC,IAAQP,EAASQ,GAAW,KAAK,MAAM,GACvCC,IAAQ,KAAK,QAAQ,GACrBC,IAAST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B,CAAM;AAC7B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-CW-MlHdY.cjs"),t=require("./sampling-BVjspJWu.cjs");var n=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevelFor(n){let r=t.n(n,this.config),i=this.current(),a=t.r(n,i?.minLevels??{})?.value??i?.minLevel;return a!==void 0&&e.mt[a]<e.mt[r]?a:r}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},r=class extends Error{};function i(e){return typeof e==`number`&&e>=0&&e<=1}function a(t){if(t.length>4096)throw new r(`The header is longer than ${String(e.It)} characters.`);try{return JSON.parse(t)}catch{throw new r(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let n=`rates must be an object with at most 100 rates from 0 to 1.`;if(!t.u(e))throw new r(n);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>i(e)))throw new r(n);return Object.fromEntries(a)}function s(n){let i=`minLevels must be an object with at most 100 level names.`;if(!t.u(n))throw new r(i);let a=Object.entries(n),o=a.every(([,t])=>typeof t==`string`&&Object.hasOwn(e.mt,t));if(a.length>100||!o)throw new r(i);return Object.fromEntries(a)}function c(n){if(!t.u(n))throw new r(`The rules must be an object.`);if(n.v!==1)throw new r(`The version must be 1.`);let{ttlMs:a,defaultRate:c,minLevel:l}=n;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new r(`ttlMs must be a number more than 0 and at most ${String(e.Lt)}.`);if(c!==void 0&&!i(c))throw new r(`defaultRate must be a number from 0 to 1.`);if(l!==void 0&&!(typeof l==`string`&&Object.hasOwn(e.mt,l)))throw new r(`minLevel must be a level name, for example DEBUG.`);let u={rates:o(n.rates)};return c!==void 0&&(u.defaultRate=c),l!==void 0&&(u.minLevel=l),n.minLevels!==void 0&&(u.minLevels=s(n.minLevels)),{rules:u,ttlMs:a}}function l(e,t){try{return c(typeof e==`string`?a(e):e)}catch(e){let n=e instanceof r?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${n}`,void 0,e),null}}function u(e,t,r){r&&(e.sampling??=new n(t)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
|
|
2
|
+
//# sourceMappingURL=remote-rules-DpFmOef2.cjs.map
|