@utk09/ui-observability 0.8.0 → 0.9.1
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 +95 -0
- package/README.md +75 -48
- package/dist/batch-DEK4bv9N.js +31 -0
- package/dist/batch-DEK4bv9N.js.map +1 -0
- package/dist/batch-DEVFs28i.cjs +2 -0
- package/dist/batch-DEVFs28i.cjs.map +1 -0
- package/dist/bus/bus.d.ts +46 -12
- package/dist/bus/links.d.ts +6 -3
- package/dist/bus-DNFvTkif.cjs +2 -0
- package/dist/bus-DNFvTkif.cjs.map +1 -0
- package/dist/{bus-DPDrlUBY.js → bus-HVQ8E72V.js} +128 -71
- package/dist/bus-HVQ8E72V.js.map +1 -0
- package/dist/capture/interactions.d.ts +7 -6
- package/dist/capture/network.d.ts +23 -9
- package/dist/capture/types.d.ts +3 -3
- package/dist/console-C9Y639mn.js +82 -0
- package/dist/console-C9Y639mn.js.map +1 -0
- package/dist/console-DssDxq1B.cjs +2 -0
- package/dist/console-DssDxq1B.cjs.map +1 -0
- package/dist/constants-N99w84xy.js +117 -0
- package/dist/constants-N99w84xy.js.map +1 -0
- package/dist/constants-X86IDwkC.cjs +2 -0
- package/dist/constants-X86IDwkC.cjs.map +1 -0
- package/dist/constants.d.ts +36 -18
- package/dist/core/diagnostics.d.ts +2 -2
- package/dist/core/drops.d.ts +29 -0
- package/dist/core/hold-buffer.d.ts +27 -0
- package/dist/core/journey.d.ts +16 -4
- package/dist/core/logger.d.ts +6 -2
- package/dist/core/pipeline.d.ts +20 -16
- package/dist/core/record.d.ts +11 -6
- package/dist/core/remote-sampling.d.ts +1 -1
- package/dist/core/runtime.d.ts +87 -23
- package/dist/core/sender.d.ts +19 -11
- 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/error-like-Ywo5uRHo.js +19 -0
- package/dist/error-like-Ywo5uRHo.js.map +1 -0
- package/dist/error-like-gGRx2s36.cjs +2 -0
- package/dist/error-like-gGRx2s36.cjs.map +1 -0
- package/dist/errors-BTWuVnHZ.cjs +3 -0
- package/dist/errors-BTWuVnHZ.cjs.map +1 -0
- package/dist/{errors-Dnc-X4Ec.js → errors-CQusIGWJ.js} +39 -20
- package/dist/errors-CQusIGWJ.js.map +1 -0
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/global-scope-dp2jADRl.js.map +1 -1
- package/dist/identity-B1GDS1Tb.cjs +2 -0
- package/dist/identity-B1GDS1Tb.cjs.map +1 -0
- package/dist/identity-D4DPjTM9.js +88 -0
- package/dist/identity-D4DPjTM9.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +12 -4
- package/dist/index.js +720 -446
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-uD4oaRMc.js → indexeddb-storage-B8SGUzSV.js} +88 -59
- package/dist/indexeddb-storage-B8SGUzSV.js.map +1 -0
- package/dist/indexeddb-storage-ukzC82dm.cjs +2 -0
- package/dist/indexeddb-storage-ukzC82dm.cjs.map +1 -0
- package/dist/interactions-CcxrVzpg.cjs +2 -0
- package/dist/interactions-CcxrVzpg.cjs.map +1 -0
- package/dist/{interactions-igKTAJvj.js → interactions-CnjfQgw3.js} +22 -19
- package/dist/interactions-CnjfQgw3.js.map +1 -0
- package/dist/journey-DjvDzHyp.js +163 -0
- package/dist/journey-DjvDzHyp.js.map +1 -0
- package/dist/journey-DxlfdFJV.cjs +2 -0
- package/dist/journey-DxlfdFJV.cjs.map +1 -0
- package/dist/{library-request-Br_T09Bn.cjs → library-request-BZ1ekVtl.cjs} +2 -2
- package/dist/{library-request-Br_T09Bn.cjs.map → library-request-BZ1ekVtl.cjs.map} +1 -1
- package/dist/{library-request-Dt0fXhcn.js → library-request-C8kc5YWv.js} +2 -2
- package/dist/{library-request-Dt0fXhcn.js.map → library-request-C8kc5YWv.js.map} +1 -1
- package/dist/{long-frames-DahhqM6u.cjs → long-frames-BGik_Yhy.cjs} +2 -2
- package/dist/{long-frames-DahhqM6u.cjs.map → long-frames-BGik_Yhy.cjs.map} +1 -1
- package/dist/{long-frames-6pnjWSSR.js → long-frames-CZk3XOkH.js} +3 -3
- package/dist/{long-frames-6pnjWSSR.js.map → long-frames-CZk3XOkH.js.map} +1 -1
- package/dist/models/batch.d.ts +15 -1
- package/dist/models/bus.d.ts +7 -4
- package/dist/models/config.d.ts +189 -12
- package/dist/models/drop.d.ts +39 -0
- package/dist/models/log-record.d.ts +12 -6
- package/dist/models/storage.d.ts +15 -3
- package/dist/network-51iicpLl.js +174 -0
- package/dist/network-51iicpLl.js.map +1 -0
- package/dist/network-jBbjyAJP.cjs +2 -0
- package/dist/network-jBbjyAJP.cjs.map +1 -0
- package/dist/patch-BX8KrPCT.cjs +2 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -0
- package/dist/patch-CCWfuEY7.js +9 -0
- package/dist/patch-CCWfuEY7.js.map +1 -0
- package/dist/platform-Cjts-8k8.js +48 -0
- package/dist/platform-Cjts-8k8.js.map +1 -0
- package/dist/{platform-D_XkVIF6.cjs → platform-DW3GFIUE.cjs} +2 -2
- package/dist/platform-DW3GFIUE.cjs.map +1 -0
- package/dist/{remote-rules-rJJZKVG8.cjs → remote-rules-ByS34k4e.cjs} +2 -2
- package/dist/remote-rules-ByS34k4e.cjs.map +1 -0
- package/dist/{remote-rules-5UA23alm.js → remote-rules-M-XZ1xbe.js} +14 -14
- package/dist/remote-rules-M-XZ1xbe.js.map +1 -0
- package/dist/sampling-BN3Oi6SV.js +63 -0
- package/dist/sampling-BN3Oi6SV.js.map +1 -0
- package/dist/sampling-b2ck5X98.cjs +2 -0
- package/dist/sampling-b2ck5X98.cjs.map +1 -0
- package/dist/sanitize-DKp5MRsa.cjs +2 -0
- package/dist/sanitize-DKp5MRsa.cjs.map +1 -0
- package/dist/sanitize-Dwj9JCkI.js +123 -0
- package/dist/sanitize-Dwj9JCkI.js.map +1 -0
- package/dist/{sender-G6v4Uqi4.js → sender-BBY0IcUo.js} +439 -322
- package/dist/sender-BBY0IcUo.js.map +1 -0
- package/dist/sender-BXoAZKum.cjs +3 -0
- package/dist/sender-BXoAZKum.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +5 -2
- package/dist/storage/eviction.d.ts +40 -0
- package/dist/storage/factory.d.ts +1 -1
- package/dist/storage/idb-driver.d.ts +7 -1
- package/dist/storage/indexeddb-storage.d.ts +13 -5
- package/dist/storage/local-storage.d.ts +27 -4
- package/dist/storage/memory-storage.d.ts +10 -3
- package/dist/{storm-BtzgLOCX.cjs → storm-CKuaBp7i.cjs} +2 -2
- package/dist/{storm-BtzgLOCX.cjs.map → storm-CKuaBp7i.cjs.map} +1 -1
- package/dist/{storm-DJkEZP_8.js → storm-DhtL2eVr.js} +2 -2
- package/dist/{storm-DJkEZP_8.js.map → storm-DhtL2eVr.js.map} +1 -1
- package/dist/transport/compression.d.ts +1 -1
- package/dist/transport/exit-flush.d.ts +27 -17
- package/dist/transport/http-transport.d.ts +61 -7
- package/dist/transport/retry-engine.d.ts +12 -8
- package/dist/transport/status-transport.d.ts +8 -3
- package/dist/utils/console.d.ts +5 -2
- package/dist/utils/error-like.d.ts +25 -0
- package/dist/utils/global-scope.d.ts +1 -1
- package/dist/utils/identity.d.ts +1 -1
- package/dist/utils/library-console.d.ts +1 -1
- package/dist/utils/library-request.d.ts +1 -1
- package/dist/utils/patch.d.ts +9 -0
- package/dist/utils/platform.d.ts +3 -3
- package/dist/utils/sequence.d.ts +0 -5
- package/dist/utils/timer.d.ts +1 -1
- package/dist/utils/tracing.d.ts +3 -3
- package/dist/utils/unref.d.ts +2 -2
- package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
- package/dist/web-vitals-Bflr5jSA.js.map +1 -0
- package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
- package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
- package/package.json +2 -2
- package/dist/bus-CUXRY0JR.cjs +0 -2
- package/dist/bus-CUXRY0JR.cjs.map +0 -1
- package/dist/bus-DPDrlUBY.js.map +0 -1
- package/dist/console-CNljJict.js +0 -81
- package/dist/console-CNljJict.js.map +0 -1
- package/dist/console-PKzc-FmR.cjs +0 -2
- package/dist/console-PKzc-FmR.cjs.map +0 -1
- package/dist/constants-B28fDv2F.cjs +0 -2
- package/dist/constants-B28fDv2F.cjs.map +0 -1
- package/dist/constants-Bu49bm39.js +0 -93
- package/dist/constants-Bu49bm39.js.map +0 -1
- package/dist/errors-C78ZTjet.cjs +0 -3
- package/dist/errors-C78ZTjet.cjs.map +0 -1
- package/dist/errors-Dnc-X4Ec.js.map +0 -1
- package/dist/indexeddb-storage-D0p3iMD0.cjs +0 -2
- package/dist/indexeddb-storage-D0p3iMD0.cjs.map +0 -1
- package/dist/indexeddb-storage-uD4oaRMc.js.map +0 -1
- package/dist/interactions-CsE2y_fQ.cjs +0 -2
- package/dist/interactions-CsE2y_fQ.cjs.map +0 -1
- package/dist/interactions-igKTAJvj.js.map +0 -1
- package/dist/network-CZ0aFUsy.cjs +0 -2
- package/dist/network-CZ0aFUsy.cjs.map +0 -1
- package/dist/network-aSNbwpue.js +0 -112
- package/dist/network-aSNbwpue.js.map +0 -1
- package/dist/platform-BwbMRwHm.js +0 -48
- package/dist/platform-BwbMRwHm.js.map +0 -1
- package/dist/platform-D_XkVIF6.cjs.map +0 -1
- package/dist/remote-rules-5UA23alm.js.map +0 -1
- package/dist/remote-rules-rJJZKVG8.cjs.map +0 -1
- package/dist/sampling-E4x92Nn2.cjs +0 -2
- package/dist/sampling-E4x92Nn2.cjs.map +0 -1
- package/dist/sampling-J1eahbfT.js +0 -160
- package/dist/sampling-J1eahbfT.js.map +0 -1
- package/dist/sanitize-BMhh8ghJ.cjs +0 -2
- package/dist/sanitize-BMhh8ghJ.cjs.map +0 -1
- package/dist/sanitize-UJ-4Lb0n.js +0 -114
- package/dist/sanitize-UJ-4Lb0n.js.map +0 -1
- package/dist/sender-B6ufz26f.cjs +0 -3
- package/dist/sender-B6ufz26f.cjs.map +0 -1
- package/dist/sender-G6v4Uqi4.js.map +0 -1
- package/dist/unref-16maCyKA.js +0 -8
- package/dist/unref-16maCyKA.js.map +0 -1
- package/dist/unref-CU9Nyz_9.cjs +0 -2
- package/dist/unref-CU9Nyz_9.cjs.map +0 -1
- package/dist/web-vitals-B2FYsEAU.cjs +0 -2
- package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
- package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-aSNbwpue.js","names":["stripUrlQuery","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","isLibraryRequest","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // 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 /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":";;;AAgHA,SAAgBC,EAAW,GAAa,GAAwC;CAC9E,OAAOC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWC,EAAI,SAASD,CAAO,IAAIA,EAAQ,KAAKC,CAAG,CACxE;AACF;;;AC7FA,SAASC,IAAyB;CAChC,OAAO,eAAe;AACxB;AAGA,IAAaC,IAAb,MAA+C;CAgBhB;CAd7B,OAAgB;CAGhB,gBAAwC;CAGxC,eAAkD;CAGlD,eAAkD;CAKlD,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EAId,AAHI,KAAK,IAAI,OAAO,QAAQ,SAC1B,KAAK,aAAa,GAEhB,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,WAAW;CAEpB;CAGA,YAAkB;EAShB,AARA,AAEE,KAAK,mBADL,WAAW,QAAQ,KAAK,eACH,OAEvB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL,OAEtB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL;CAExB;CAOA,QAAgB,GAAsB;EAIpC,OAAOC,EAAiB,KAAKP,EAAWG,GAAK,KA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cgC,CAAM;EAI5E,KAAK,IAAI,YAAY,MACnB,yBACA,gCAAgCpB,EAAO,GAAGR,EAAI,UACxC;GACJ,IAAM6B,IAAU,KAAK,MAAMnB,CAAU;GAErC,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,GAAGF,EAAO,GAAGR,EAAI,GAAGS,MAAW,IAAI,WAAW,OAAOA,CAAM;IACpE,MAAM,EAAE,YAAYoB,EAAQ;GAC9B,CAAC;GAED,IAAMC,IAAa;IACjB,uBAAuBtB;IACvB,YAAYR;IACZ,6BAA6BS;IAC7B,oBAAoBoB;GACtB;GAEA,AAAIpB,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGR,EAAI,UAAUW,GAAOmB,CAAU,IAGhErB,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGR,EAAI,YAAY,OAAOS,CAAM,KAAKqB,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGR,KAAO8B,CAAU;EACtD,CACF;CACF;AACF"}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { dt as e, mt as t, t as n, tt as r, yt as i } from "./constants-Bu49bm39.js";
|
|
2
|
-
//#region src/utils/platform.ts
|
|
3
|
-
var a = null;
|
|
4
|
-
function o(e, t) {
|
|
5
|
-
let n = e[t];
|
|
6
|
-
return n !== void 0 && e instanceof n;
|
|
7
|
-
}
|
|
8
|
-
function s(e) {
|
|
9
|
-
if (a) return a;
|
|
10
|
-
let t = globalThis, n = t.navigator?.userAgent ?? "", r = "browser", s, u, d = !1, f = t.fin?.me;
|
|
11
|
-
return o(t, "ServiceWorkerGlobalScope") ? (r = "service_worker", d = !0) : o(t, "SharedWorkerGlobalScope") ? (r = "shared_worker", d = !0) : o(t, "WorkerGlobalScope") ? (r = "web_worker", d = !0) : f === void 0 ? t.Capacitor !== void 0 || t.Ionic !== void 0 ? r = "ionic" : t.cordova !== void 0 || c(n) ? r = "mobile_webview" : typeof document > "u" && typeof process < "u" && (r = "node") : (r = i.test(n) ? "openfin" : "openfin_web", e.guard("openfin.unavailable", "The library could not read fin.me.identity.", () => {
|
|
12
|
-
let e = f.identity;
|
|
13
|
-
s = e?.uuid, u = e?.name;
|
|
14
|
-
})), a = {
|
|
15
|
-
platform: r,
|
|
16
|
-
openfinUuid: s,
|
|
17
|
-
openfinName: u,
|
|
18
|
-
userAgent: n,
|
|
19
|
-
isWorker: d,
|
|
20
|
-
isTopLevelDocument: l(e)
|
|
21
|
-
}, a;
|
|
22
|
-
}
|
|
23
|
-
function c(i) {
|
|
24
|
-
return n.test(i) ? !0 : (r.test(i) || e.test(i) && t.test(i)) && i.includes("AppleWebKit") && !i.includes("Safari/");
|
|
25
|
-
}
|
|
26
|
-
function l(e) {
|
|
27
|
-
if (typeof window > "u") return !1;
|
|
28
|
-
try {
|
|
29
|
-
return window.self === window.top;
|
|
30
|
-
} catch {
|
|
31
|
-
return e.count("platform.api_blocked"), !1;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
function u(e) {
|
|
35
|
-
try {
|
|
36
|
-
return typeof location < "u" ? location.href : "";
|
|
37
|
-
} catch {
|
|
38
|
-
return e.count("platform.api_blocked"), "";
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
function d(e) {
|
|
42
|
-
let t = e.search(/[?#]/);
|
|
43
|
-
return t === -1 ? e : e.slice(0, t);
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
export { s as n, d as r, u as t };
|
|
47
|
-
|
|
48
|
-
//# sourceMappingURL=platform-BwbMRwHm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"platform-BwbMRwHm.js","names":["MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","OPENFIN_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"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\";\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 /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether 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 * Evaluates whether 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/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\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 = (g.fin as FinLike | undefined)?.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 * Evaluates whether 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 * Determines whether 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/**\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/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,I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D,MAAQ,KAAKC,IAAMA,EAAI,MAAM,GAAGD,CAAG;AAC5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"platform-D_XkVIF6.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"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\";\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 /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether 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 * Evaluates whether 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/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\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 = (g.fin as FinLike | undefined)?.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 * Evaluates whether 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 * Determines whether 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/**\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/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,E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O,OAAS,OAAO,GAChC,MAAQ,CAGN,OADAF,EAAY,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,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-5UA23alm.js","names":["REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","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\";\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}\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.\n * @returns The remote level if it is lower than `minLevel`, or else `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\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 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 whether 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 * Tests whether a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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 * 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 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":";;AA2CA,IAAaG,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;CAMA,WAAqB;EACnB,IAAM,EAAE,gBAAa,KAAK,QACpBC,IAAS,KAAK,QAAQ,CAAC,EAAE;EAE/B,OAAOA,MAAW,KAAA,KAAaN,EAAYM,KAAUN,EAAYO,KAAYD,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OV,CAA0B,EAAE,EACvF;CAGF,IAAIsB,MAAgB,KAAA,KAAa,CAACX,EAAOW,CAAW,GAClD,MAAM,IAAIZ,EAAU,2CAA2C;CAGjE,IACEF,MAAa,KAAA,KACb,EAAE,OAAOA,KAAa,YAAY,OAAO,OAAOP,GAAaO,CAAQ,IAErE,MAAM,IAAIE,EAAU,mDAAmD;CAGzE,IAAMD,IAAqB,EAAE,OAAOO,EAAUJ,EAAM,KAAK,EAAE;CAU3D,OARIU,MAAgB,KAAA,MAClB,EAAM,cAAcA,IAGlBd,MAAa,KAAA,MACf,EAAM,WAAWA,IAGZ;EAAE;EAAO;CAAM;AACxB;AAQA,SAAgBe,EAAiB,GAAc,GAA+C;CAC5F,IAAI;EACF,OAAOH,EAAU,OAAOI,KAAQ,WAAWV,EAAUU,CAAG,IAAIA,CAAG;CACjE,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiBf,IAAY,IAAIe,EAAM,YAAY;EAQlE,OANAE,EAAY,OACV,kBACA,0DAA0DD,KAC1D,KAAA,GACAD,CACF,GACO;CACT;AACF;AAQA,SAAgBG,EACd,GACA,GACA,GACM;CAKN,AAJIvB,MACF,EAAK,aAAa,IAAIF,EAAeC,CAAM,IAG7CyB,EAAK,UAAU,MAAMxB,CAAM;AAC7B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-rJJZKVG8.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","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\";\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}\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.\n * @returns The remote level if it is lower than `minLevel`, or else `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\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 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 whether 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 * Tests whether a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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 * 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 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":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF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AAM,GAG7CyB,EAAK,UAAU,MAAMxB,CAAM,CAC7B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-B28fDv2F.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(){return`${String(Date.now())}000000`}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}var i={local:()=>localStorage,session:()=>sessionStorage};function a(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function o(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function s(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return o(16)}function c(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function l(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function u(t,n=i){let r=s(t),a=Date.now(),o=s(t),u=c(n,`local`,e.Yt,t);if(u)try{let e=JSON.parse(u);e.id&&a-(e.lastSeenAt??0)<18e5&&(o=e.id)}catch{t.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`)}let d=JSON.stringify({id:o,lastSeenAt:a});l(n,`local`,e.Yt,d,t);let f=c(n,`session`,`ui-observability.tab`,t)??``;return f||(f=s(t),l(n,`session`,e.sn,f,t)),{sessionId:o,tabId:f,contextId:r}}function d(t,n,r){l(r,`session`,e.sn,t,n)}var f=class{diagnostics;stores;lastTouchAt=0;constructor(e,t=i){this.diagnostics=e,this.stores=t}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});l(this.stores,`local`,e.Yt,r,this.diagnostics)}},p=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function m(e,n){let r,i=new Promise((e,i)=>{let a=setTimeout(()=>{i(new p(n))},n);r=a,t.t(a)});return Promise.race([e,i]).finally(()=>{clearTimeout(r)})}function h(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function g(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function _(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={rate:i,length:r.length});return n}function v(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,o=_(e,r),s=n?_(e,n.rates):void 0;return s&&s.length>=(o?.length??-1)?Math.min(s.rate,a):o?o.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function y(t,n,r){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=v(t.namespace,n,r);return r&&e.at[t.level]<e.at[n.minLevel]&&(i=Math.min(i,n.sampling.remoteMaxRate)),i>=1?!0:i<=0?!1:h(t.journeyId||t.traceId)/e.pn<i}function b(t,n,r=null){return y({level:t.severityText,type:g(t,e.l),namespace:g(t,e.n),journeyId:g(t,e.a),traceId:t.traceId},n,r)}var x=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return d}});
|
|
2
|
-
//# sourceMappingURL=sampling-E4x92Nn2.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-E4x92Nn2.cjs","names":["SESSION_ID_KEY","TAB_ID_KEY","FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","require_unref","nowUnixNano","isLogRecord","value","record","BROWSER_STORES","memoryStores","wrap","map","key","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","DeadlineError","ms","withDeadline","expire","deadline","timer","reject","work","hash","h","readAttr","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies at once.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n if (remote && LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel]) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"8EAwDA,SAAgBW,GAAsB,CACpC,MAAO,GA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GAAIxD,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMqB,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
|
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
import { H as e, U as t, Yt as n, a as r, at as i, l as a, n as o, pn as s, sn as c } from "./constants-Bu49bm39.js";
|
|
2
|
-
import { t as l } from "./unref-16maCyKA.js";
|
|
3
|
-
//#region src/models/log-record.ts
|
|
4
|
-
function u() {
|
|
5
|
-
return `${String(Date.now())}000000`;
|
|
6
|
-
}
|
|
7
|
-
function d(e) {
|
|
8
|
-
if (typeof e != "object" || !e) return !1;
|
|
9
|
-
let t = e;
|
|
10
|
-
return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
|
|
11
|
-
}
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/utils/identity.ts
|
|
14
|
-
var f = {
|
|
15
|
-
local: () => localStorage,
|
|
16
|
-
session: () => sessionStorage
|
|
17
|
-
};
|
|
18
|
-
function p() {
|
|
19
|
-
let e = (e) => ({
|
|
20
|
-
getItem: (t) => e.get(t) ?? null,
|
|
21
|
-
setItem: (t, n) => {
|
|
22
|
-
e.set(t, n);
|
|
23
|
-
},
|
|
24
|
-
removeItem: (t) => {
|
|
25
|
-
e.delete(t);
|
|
26
|
-
}
|
|
27
|
-
}), t = e(/* @__PURE__ */ new Map()), n = e(/* @__PURE__ */ new Map());
|
|
28
|
-
return {
|
|
29
|
-
local: () => t,
|
|
30
|
-
session: () => n
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
function m(e) {
|
|
34
|
-
let t = new Uint8Array(e);
|
|
35
|
-
if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
|
|
36
|
-
else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
|
|
37
|
-
return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
|
|
38
|
-
}
|
|
39
|
-
function h(e) {
|
|
40
|
-
try {
|
|
41
|
-
if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
|
|
42
|
-
} catch {
|
|
43
|
-
e.count("platform.api_blocked");
|
|
44
|
-
}
|
|
45
|
-
return m(16);
|
|
46
|
-
}
|
|
47
|
-
function g(e, t, n, r) {
|
|
48
|
-
return r.guard("storage.unavailable", `The library could not read ${t}Storage.`, () => e[t]().getItem(n)) ?? null;
|
|
49
|
-
}
|
|
50
|
-
function _(e, t, n, r, i) {
|
|
51
|
-
i.guard("storage.unavailable", `The library could not write to ${t}Storage.`, () => {
|
|
52
|
-
e[t]().setItem(n, r);
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
function v(e, t = f) {
|
|
56
|
-
let r = h(e), i = Date.now(), a = h(e), o = g(t, "local", n, e);
|
|
57
|
-
if (o) try {
|
|
58
|
-
let e = JSON.parse(o);
|
|
59
|
-
e.id && i - (e.lastSeenAt ?? 0) < 18e5 && (a = e.id);
|
|
60
|
-
} catch {
|
|
61
|
-
e.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
|
|
62
|
-
}
|
|
63
|
-
let s = JSON.stringify({
|
|
64
|
-
id: a,
|
|
65
|
-
lastSeenAt: i
|
|
66
|
-
});
|
|
67
|
-
_(t, "local", n, s, e);
|
|
68
|
-
let l = g(t, "session", "ui-observability.tab", e) ?? "";
|
|
69
|
-
return l || (l = h(e), _(t, "session", c, l, e)), {
|
|
70
|
-
sessionId: a,
|
|
71
|
-
tabId: l,
|
|
72
|
-
contextId: r
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
function y(e, t, n) {
|
|
76
|
-
_(n, "session", c, e, t);
|
|
77
|
-
}
|
|
78
|
-
var b = class {
|
|
79
|
-
diagnostics;
|
|
80
|
-
stores;
|
|
81
|
-
lastTouchAt = 0;
|
|
82
|
-
constructor(e, t = f) {
|
|
83
|
-
this.diagnostics = e, this.stores = t;
|
|
84
|
-
}
|
|
85
|
-
touch(e) {
|
|
86
|
-
let t = Date.now();
|
|
87
|
-
if (t - this.lastTouchAt < 6e4) return;
|
|
88
|
-
this.lastTouchAt = t;
|
|
89
|
-
let r = JSON.stringify({
|
|
90
|
-
id: e,
|
|
91
|
-
lastSeenAt: t
|
|
92
|
-
});
|
|
93
|
-
_(this.stores, "local", n, r, this.diagnostics);
|
|
94
|
-
}
|
|
95
|
-
}, x = class extends Error {
|
|
96
|
-
constructor(e) {
|
|
97
|
-
super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
function S(e, t) {
|
|
101
|
-
let n, r = new Promise((e, r) => {
|
|
102
|
-
let i = setTimeout(() => {
|
|
103
|
-
r(new x(t));
|
|
104
|
-
}, t);
|
|
105
|
-
n = i, l(i);
|
|
106
|
-
});
|
|
107
|
-
return Promise.race([e, r]).finally(() => {
|
|
108
|
-
clearTimeout(n);
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
//#endregion
|
|
112
|
-
//#region src/core/sampling.ts
|
|
113
|
-
function C(n) {
|
|
114
|
-
let r = e;
|
|
115
|
-
for (let e = 0; e < n.length; e++) r ^= n.charCodeAt(e), r = Math.imul(r, t);
|
|
116
|
-
return r >>> 0;
|
|
117
|
-
}
|
|
118
|
-
function w(e, t) {
|
|
119
|
-
let n = e.attributes[t];
|
|
120
|
-
return typeof n == "string" ? n : "";
|
|
121
|
-
}
|
|
122
|
-
function T(e, t) {
|
|
123
|
-
let n;
|
|
124
|
-
for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
|
|
125
|
-
rate: i,
|
|
126
|
-
length: r.length
|
|
127
|
-
});
|
|
128
|
-
return n;
|
|
129
|
-
}
|
|
130
|
-
function E(e, t, n) {
|
|
131
|
-
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = T(e, r), s = n ? T(e, n.rates) : void 0;
|
|
132
|
-
return s && s.length >= (o?.length ?? -1) ? Math.min(s.rate, a) : o ? o.rate : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
|
|
133
|
-
}
|
|
134
|
-
function D(e, t, n) {
|
|
135
|
-
if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
136
|
-
let r = E(e.namespace, t, n);
|
|
137
|
-
return n && i[e.level] < i[t.minLevel] && (r = Math.min(r, t.sampling.remoteMaxRate)), r >= 1 ? !0 : r <= 0 ? !1 : C(e.journeyId || e.traceId) / s < r;
|
|
138
|
-
}
|
|
139
|
-
function O(e, t, n = null) {
|
|
140
|
-
return D({
|
|
141
|
-
level: e.severityText,
|
|
142
|
-
type: w(e, a),
|
|
143
|
-
namespace: w(e, o),
|
|
144
|
-
journeyId: w(e, r),
|
|
145
|
-
traceId: e.traceId
|
|
146
|
-
}, t, n);
|
|
147
|
-
}
|
|
148
|
-
var k = class {
|
|
149
|
-
windowStart = 0;
|
|
150
|
-
count = 0;
|
|
151
|
-
allow(e) {
|
|
152
|
-
if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
|
|
153
|
-
let t = Date.now();
|
|
154
|
-
return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
|
|
155
|
-
}
|
|
156
|
-
};
|
|
157
|
-
//#endregion
|
|
158
|
-
export { S as a, p as c, m as d, v as f, x as i, h as l, u as m, O as n, f as o, d as p, D as r, b as s, k as t, y as u };
|
|
159
|
-
|
|
160
|
-
//# sourceMappingURL=sampling-J1eahbfT.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-J1eahbfT.js","names":["FNV_OFFSET_BASIS","FNV_PRIME","SESSION_ID_KEY","ATTR_JOURNEY_ID","LEVEL_ORDER","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","UINT32_MAX","TAB_ID_KEY","unrefTimer","nowUnixNano","isLogRecord","value","record","BROWSER_STORES","memoryStores","wrap","map","key","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","DeadlineError","ms","withDeadline","expire","deadline","timer","work","hash","h","readAttr","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies at once.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n if (remote && LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel]) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;;AAwDA,SAAgBU,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAMC,IAASD;CACf,OACE,OAAOC,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AC5BA,IAAaC,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKN,CAAK;EACpB;EACA,aAAa,MAAQ;GACnB,EAAI,OAAOM,CAAG;EAChB;CACF,IAEMC,IAAaH,kBAAK,I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AIX,IAAOG,EAAQQ,EAAM,WAAWP,GAAQG,CAAM;CAkBlD,OAfIA,KAAU1D,EAAY8D,EAAM,SAAqB9D,EAAYuD,EAAO,cACtE,IAAO,KAAK,IAAIJ,GAAMI,EAAO,SAAS,aAAa,IAGjDJ,KAAA,IACK,KAELA,KAAA,IACK,KAOFN,EAFKiB,EAAM,aAAaA,EAAM,OAEtB,IAAI3D,IAAagD;AAClC;AAUA,SAAgBY,EACd,GACA,GACA,IAA6B,MACpB;CACT,OAAOF,EACL;EACE,OAAOpD,EAAO;EACd,MAAMsC,EAAStC,GAAQR,CAAa;EACpC,WAAW8C,EAAStC,GAAQP,CAAkB;EAC9C,WAAW6C,EAAStC,GAAQV,CAAe;EAC3C,SAASU,EAAO;CAClB,GACA8C,GACAG,CACF;AACF;AAQA,IAAaM,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAIvD,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMqB,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-B28fDv2F.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.ot);function n(e){return t.run(e)}function r(){return t.open()}function i(e,t){if(e.length<=t)return e;let n=a(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function a(e){return e>=55296&&e<=56319}function o(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function s(e,t,n){return c(e,t,n).value}function c(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:u(e,t,new WeakSet,0,r),bytes:r.bytes}}function l(e,t){return t.bytes+=d(e)+2,e}function u(e,t,n,r,a){if(a.nodes++,a.nodes>t.maxNodes)return l(`[MaxNodes]`,a);if(e==null)return a.bytes+=4,e;if(typeof e==`string`)return l(i(e,t.maxAttributeChars),a);if(typeof e==`number`)return a.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return a.bytes+=5,e;if(typeof e==`bigint`)return l(`${e.toString()}n`,a);if(typeof e==`symbol`)return l(e.toString(),a);if(typeof e==`function`)return l(`[Function ${e.name===``?`anonymous`:e.name}]`,a);if(r>=t.maxDepth)return l(`[MaxDepth]`,a);if(n.has(e))return l(`[Circular]`,a);n.add(e),a.bytes+=2;try{if(e instanceof Error)return{name:l(e.name,a),message:l(i(e.message,t.maxAttributeChars),a),stack:e.stack?l(i(e.stack,t.maxStackChars),a):void 0,cause:e.cause?u(e.cause,t,n,r+1,a):void 0};if(e instanceof Date)return l(e.toISOString(),a);if(e instanceof RegExp)return l(e.toString(),a);if(e instanceof Map){let i=e,o={},s=0;for(let[e,c]of i){if(s>=t.maxArrayLength){o[`…`]=l(`[${String(i.size-t.maxArrayLength)} more entries]`,a);break}s++;let f=String(e);a.bytes+=d(f)+4,o[f]=u(c,t,n,r+1,a)}return o}if(e instanceof Set)return u([...e].slice(0,t.maxArrayLength),t,n,r,a);if(ArrayBuffer.isView(e)){let t=e.length??0;return l(`[${e.constructor.name}(${String(t)})]`,a)}if(e instanceof Promise)return l(`[Promise]`,a);if(typeof Node<`u`&&e instanceof Node)return l(o(e),a);if(Array.isArray(e)){let i=e,o=i.slice(0,t.maxArrayLength).map(e=>u(e,t,n,r+1,a));return i.length>t.maxArrayLength&&o.push(l(`[${String(i.length-t.maxArrayLength)} more items]`,a)),o}let s=e.toJSON;if(typeof s==`function`)return u(s.call(e),t,n,r+1,a);let c=e,f=Object.keys(c),p={},m=0;for(let e of f){if(m>=t.maxAttributeCount){p[`…`]=l(`[${String(f.length-m)} more keys]`,a);break}m++,a.bytes+=d(e)+4,p[e]=u(c[e],t,n,r+1,a)}return p}catch(e){return a.diagnostics.count(`record.sanitize_failed`),l(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,a)}finally{n.delete(e)}}function d(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return d}});
|
|
2
|
-
//# sourceMappingURL=sanitize-BMhh8ghJ.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-BMhh8ghJ.cjs","names":["globalScope","LIBRARY_CONSOLE_KEY","set","toJson","require_constants","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","record","keys","count","error","bytes","i"],"sources":["../src/utils/library-console.ts","../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/library-console.ts\n//\n// Marks the console calls that the library makes itself. The console capture skips a call inside\n// this scope. Without the scope, the capture records each mirrored line again, and the loop does\n// not stop.\n\nimport { LIBRARY_CONSOLE_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library console calls. */\nconst scope = globalScope(LIBRARY_CONSOLE_KEY);\n\n/**\n * Runs a function inside the library console scope.\n * @param fn Function that writes to the console.\n * @returns The return value of the function.\n */\nexport function runAsLibraryConsole<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library console scope is open.\n * @returns True while the library writes to the console.\n */\nexport function isLibraryConsole(): boolean {\n return scope.open();\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. Otherwise a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":"4CAUA,IAAMK,uCAAQL,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAO7C,SAAgBK,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB,CCeA,SAAgBI,EAAS,EAAe,EAAqB,CAC3D,GAAIC,EAAM,QAAUC,EAClB,OAAOD,EAKT,IAAME,EAAMC,EAAgBH,EAAM,WAAWC,EAAM,CAAC,CAAC,EAAIA,EAAM,EAAIA,EACnE,MAAO,GAAGD,EAAM,MAAM,EAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,OAASE,CAAG,EAAE,QAC1E,CAOA,SAASC,EAAgB,EAAuB,CAC9C,OAAOC,GAAA,OAA8BA,GAAA,KACvC,CAcA,SAASC,EAAa,EAAwB,CAO5C,MAAO,aANMC,EAAK,UAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,GAAK,IAAIA,EAAK,KAA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