@utk09/ui-observability 0.9.3 → 0.9.4
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 +45 -0
- package/README.md +108 -33
- package/dist/{batch-D5qvsMQ_.cjs → batch-C4oF6XZT.cjs} +2 -2
- package/dist/{batch-D5qvsMQ_.cjs.map → batch-C4oF6XZT.cjs.map} +1 -1
- package/dist/{batch-DDgxg16_.js → batch-D-4xl7op.js} +4 -4
- package/dist/{batch-DDgxg16_.js.map → batch-D-4xl7op.js.map} +1 -1
- package/dist/{bus-C6RwKzPW.js → bus-Cyvq-Ngx.js} +5 -5
- package/dist/{bus-C6RwKzPW.js.map → bus-Cyvq-Ngx.js.map} +1 -1
- package/dist/{bus-WPVDFw2y.cjs → bus-rOhVuRee.cjs} +2 -2
- package/dist/{bus-WPVDFw2y.cjs.map → bus-rOhVuRee.cjs.map} +1 -1
- package/dist/capture/network.d.ts +1 -0
- package/dist/capture/types.d.ts +3 -0
- package/dist/capture/web-socket.d.ts +40 -0
- package/dist/{console-Dv5GfaNn.js → console-BT7mcgU6.js} +3 -3
- package/dist/{console-Dv5GfaNn.js.map → console-BT7mcgU6.js.map} +1 -1
- package/dist/{console-BSusX_M-.cjs → console-Boqa7new.cjs} +2 -2
- package/dist/{console-BSusX_M-.cjs.map → console-Boqa7new.cjs.map} +1 -1
- package/dist/constants-BgRS6MB0.cjs +2 -0
- package/dist/constants-BgRS6MB0.cjs.map +1 -0
- package/dist/constants-L_d5YvvQ.js +160 -0
- package/dist/constants-L_d5YvvQ.js.map +1 -0
- package/dist/constants.d.ts +34 -2
- package/dist/core/breadcrumbs.d.ts +3 -1
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/journey.d.ts +7 -0
- package/dist/core/meter.d.ts +19 -1
- package/dist/core/pipeline.d.ts +12 -4
- package/dist/core/record.d.ts +40 -8
- package/dist/core/remote-sampling.d.ts +7 -3
- package/dist/core/runtime.d.ts +62 -3
- package/dist/core/sampling.d.ts +32 -1
- package/dist/core/sender.d.ts +8 -0
- package/dist/core/spans.d.ts +34 -0
- package/dist/{errors-DCZWcHkd.js → errors-BDI96zKc.js} +6 -6
- package/dist/errors-BDI96zKc.js.map +1 -0
- package/dist/errors-_xEsCVXn.cjs +3 -0
- package/dist/errors-_xEsCVXn.cjs.map +1 -0
- package/dist/identity-Bwku7zzN.cjs +2 -0
- package/dist/identity-Bwku7zzN.cjs.map +1 -0
- package/dist/{identity-Di-QXGCC.js → identity-Dtv917nz.js} +33 -23
- package/dist/identity-Dtv917nz.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +23 -1
- package/dist/index.js +803 -524
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-DX18p39D.cjs → indexeddb-storage-Cvavrf-y.cjs} +2 -2
- package/dist/{indexeddb-storage-DX18p39D.cjs.map → indexeddb-storage-Cvavrf-y.cjs.map} +1 -1
- package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-HgkQUTyS.js} +26 -26
- package/dist/{indexeddb-storage-T9YIYVYC.js.map → indexeddb-storage-HgkQUTyS.js.map} +1 -1
- package/dist/{interactions-_hfOerfC.cjs → interactions-Bhe1ft8P.cjs} +2 -2
- package/dist/interactions-Bhe1ft8P.cjs.map +1 -0
- package/dist/{interactions-BLH_tX87.js → interactions-Ck01cEij.js} +3 -3
- package/dist/interactions-Ck01cEij.js.map +1 -0
- package/dist/journey-Co9OlzrW.cjs +2 -0
- package/dist/journey-Co9OlzrW.cjs.map +1 -0
- package/dist/{journey-yALMEWF7.js → journey-DRK0A8u_.js} +37 -34
- package/dist/journey-DRK0A8u_.js.map +1 -0
- package/dist/{library-request-CQD4HUiP.js → library-request-ChCar5F8.js} +3 -3
- package/dist/{library-request-CQD4HUiP.js.map → library-request-ChCar5F8.js.map} +1 -1
- package/dist/{library-request-BcAxuwsf.cjs → library-request-gMFOCNcn.cjs} +2 -2
- package/dist/{library-request-BcAxuwsf.cjs.map → library-request-gMFOCNcn.cjs.map} +1 -1
- package/dist/log-record-cwFiLyPY.js +17 -0
- package/dist/log-record-cwFiLyPY.js.map +1 -0
- package/dist/log-record-jX9eWUP8.cjs +2 -0
- package/dist/log-record-jX9eWUP8.cjs.map +1 -0
- package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-Bky6nZDF.cjs} +2 -2
- package/dist/long-frames-Bky6nZDF.cjs.map +1 -0
- package/dist/{long-frames-DD_Um9_4.js → long-frames-DDumopji.js} +4 -4
- package/dist/long-frames-DDumopji.js.map +1 -0
- package/dist/models/config.d.ts +56 -5
- package/dist/models/log-record.d.ts +1 -1
- package/dist/models/plugin.d.ts +47 -0
- package/dist/models/stats.d.ts +11 -0
- package/dist/{network--GoE7_Or.js → network-BsBZ6_-Q.js} +43 -29
- package/dist/network-BsBZ6_-Q.js.map +1 -0
- package/dist/network-_4csBGBM.cjs +2 -0
- package/dist/network-_4csBGBM.cjs.map +1 -0
- package/dist/{platform-GaM6h7XM.js → platform-4yYjMD-B.js} +11 -6
- package/dist/platform-4yYjMD-B.js.map +1 -0
- package/dist/{platform-kIL5AZB7.cjs → platform-o7r1ocOu.cjs} +2 -2
- package/dist/platform-o7r1ocOu.cjs.map +1 -0
- package/dist/remote-rules-1KqfVBIu.js +91 -0
- package/dist/remote-rules-1KqfVBIu.js.map +1 -0
- package/dist/remote-rules-BHgEGlYi.cjs +2 -0
- package/dist/remote-rules-BHgEGlYi.cjs.map +1 -0
- package/dist/sampling-C4my-ma0.cjs +2 -0
- package/dist/sampling-C4my-ma0.cjs.map +1 -0
- package/dist/sampling-nYIWP_vP.js +86 -0
- package/dist/sampling-nYIWP_vP.js.map +1 -0
- package/dist/{sanitize-DP0xDPrt.js → sanitize-BiUKCUG6.js} +2 -2
- package/dist/{sanitize-DP0xDPrt.js.map → sanitize-BiUKCUG6.js.map} +1 -1
- package/dist/{sanitize--_e4oOPX.cjs → sanitize-BxuPSXOk.cjs} +2 -2
- package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-BxuPSXOk.cjs.map} +1 -1
- package/dist/sender-6vrT9fFL.cjs +3 -0
- package/dist/sender-6vrT9fFL.cjs.map +1 -0
- package/dist/{sender-BUBWLn5i.js → sender-DFQMF39P.js} +382 -275
- package/dist/sender-DFQMF39P.js.map +1 -0
- package/dist/{storm-DhHGHhOc.cjs → storm-6YYbXzT_.cjs} +2 -2
- package/dist/{storm-DhHGHhOc.cjs.map → storm-6YYbXzT_.cjs.map} +1 -1
- package/dist/{storm-OD5J6Ylm.js → storm-CfO0Sam2.js} +2 -2
- package/dist/{storm-OD5J6Ylm.js.map → storm-CfO0Sam2.js.map} +1 -1
- package/dist/transport/exit-flush.d.ts +6 -0
- package/dist/transport/http-transport.d.ts +2 -1
- package/dist/transport/serializers/otlp-traces.d.ts +3 -0
- package/dist/transport/serializers/select.d.ts +8 -5
- package/dist/transport/status-transport.d.ts +7 -0
- package/dist/types-BR9t_w28.js +8 -0
- package/dist/types-BR9t_w28.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs +2 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -0
- package/dist/utils/identity.d.ts +11 -0
- package/dist/utils/platform.d.ts +8 -0
- package/dist/utils/tracing.d.ts +82 -4
- package/dist/web-socket-Ar4cZxmd.js +102 -0
- package/dist/web-socket-Ar4cZxmd.js.map +1 -0
- package/dist/web-socket-BwJdwSHl.cjs +2 -0
- package/dist/web-socket-BwJdwSHl.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/constants-Cb92egPS.cjs +0 -2
- package/dist/constants-Cb92egPS.cjs.map +0 -1
- package/dist/constants-DhH6VI5a.js +0 -144
- package/dist/constants-DhH6VI5a.js.map +0 -1
- package/dist/deadline-CUrH0Hd8.cjs +0 -2
- package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
- package/dist/deadline-DeqXEliN.js +0 -31
- package/dist/deadline-DeqXEliN.js.map +0 -1
- package/dist/errors-DCZWcHkd.js.map +0 -1
- package/dist/errors-ERu-su8m.cjs +0 -3
- package/dist/errors-ERu-su8m.cjs.map +0 -1
- package/dist/identity-C1WLItSl.cjs +0 -2
- package/dist/identity-C1WLItSl.cjs.map +0 -1
- package/dist/identity-Di-QXGCC.js.map +0 -1
- package/dist/interactions-BLH_tX87.js.map +0 -1
- package/dist/interactions-_hfOerfC.cjs.map +0 -1
- package/dist/journey-BRUj0hqD.cjs +0 -2
- package/dist/journey-BRUj0hqD.cjs.map +0 -1
- package/dist/journey-yALMEWF7.js.map +0 -1
- package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
- package/dist/long-frames-DD_Um9_4.js.map +0 -1
- package/dist/network--GoE7_Or.js.map +0 -1
- package/dist/network-DcuS2H1P.cjs +0 -2
- package/dist/network-DcuS2H1P.cjs.map +0 -1
- package/dist/platform-GaM6h7XM.js.map +0 -1
- package/dist/platform-kIL5AZB7.cjs.map +0 -1
- package/dist/remote-rules-6ePq8CrI.js +0 -84
- package/dist/remote-rules-6ePq8CrI.js.map +0 -1
- package/dist/remote-rules-CI3gbRCL.cjs +0 -2
- package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
- package/dist/sampling-C-M8p3FK.cjs +0 -2
- package/dist/sampling-C-M8p3FK.cjs.map +0 -1
- package/dist/sampling-Ud_WiuU9.js +0 -65
- package/dist/sampling-Ud_WiuU9.js.map +0 -1
- package/dist/sender-BESHz6my.cjs +0 -3
- package/dist/sender-BESHz6my.cjs.map +0 -1
- package/dist/sender-BUBWLn5i.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling-C4my-ma0.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LEVEL_ORDER","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","countInWindow","ERROR_STORM_WINDOW_MS","require_constants","require_fixed_window","isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work","hash","h","i","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// 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_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\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 to test.\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/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\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\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\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 /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\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, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\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 level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, 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 aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\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 /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, 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 // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW, ERROR_STORM_WINDOW_MS);\n }\n}\n"],"mappings":"qFAUA,SAAgBa,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CCAA,SAAgBC,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAAkB,EAAwB,CACxE,IAAIC,EAEEC,EAAW,IAA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OAAA,IAAsCC,EAAAA,CAAqB,CACvF,CACF"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { En as e, J as t, K as n, St as r, d as i, ft as a, n as o, pt as s, q as c, s as l } from "./constants-L_d5YvvQ.js";
|
|
2
|
+
import { t as u } from "./fixed-window-Re7jIRJH.js";
|
|
3
|
+
//#region src/utils/guards.ts
|
|
4
|
+
function d(e) {
|
|
5
|
+
return typeof e == "object" && !!e && !Array.isArray(e);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/utils/unref.ts
|
|
9
|
+
function f(e) {
|
|
10
|
+
typeof e != "number" && e.unref?.();
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/utils/deadline.ts
|
|
14
|
+
var p = class extends Error {
|
|
15
|
+
constructor(e) {
|
|
16
|
+
super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function m(e, t) {
|
|
20
|
+
let n, r = new Promise((e, r) => {
|
|
21
|
+
let i = setTimeout(() => {
|
|
22
|
+
r(new p(t));
|
|
23
|
+
}, t);
|
|
24
|
+
n = i, f(i);
|
|
25
|
+
});
|
|
26
|
+
return Promise.race([e, r]).finally(() => {
|
|
27
|
+
clearTimeout(n);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/core/sampling.ts
|
|
32
|
+
function h(e) {
|
|
33
|
+
let n = c;
|
|
34
|
+
for (let r = 0; r < e.length; r++) n ^= e.charCodeAt(r), n = Math.imul(n, t);
|
|
35
|
+
return n >>> 0;
|
|
36
|
+
}
|
|
37
|
+
function g(e, t) {
|
|
38
|
+
let n = e.attributes[t];
|
|
39
|
+
return typeof n == "string" ? n : "";
|
|
40
|
+
}
|
|
41
|
+
function _(e, t) {
|
|
42
|
+
let n;
|
|
43
|
+
for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
|
|
44
|
+
value: i,
|
|
45
|
+
length: r.length
|
|
46
|
+
});
|
|
47
|
+
return n;
|
|
48
|
+
}
|
|
49
|
+
function v(e, t) {
|
|
50
|
+
return _(e, t.minLevels)?.value ?? t.minLevel;
|
|
51
|
+
}
|
|
52
|
+
function y(e, t, n) {
|
|
53
|
+
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = _(e, r), s = n ? _(e, n.rates) : void 0;
|
|
54
|
+
return s && s.length >= (o?.length ?? -1) ? Math.min(s.value, a) : o ? o.value : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
|
|
55
|
+
}
|
|
56
|
+
function b(t, n) {
|
|
57
|
+
return n >= 1 ? !0 : n <= 0 ? !1 : h(t) / e < n;
|
|
58
|
+
}
|
|
59
|
+
function x(e, t, n) {
|
|
60
|
+
if (e.aggregated === !0 || e.type === "span" || e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
61
|
+
let r = y(e.namespace, t, n), i = v(e.namespace, t), o = s[e.level] < s[i];
|
|
62
|
+
return n && o && !a.includes(e.type) && (r = Math.min(r, t.sampling.remoteMaxRate)), b(e.journeyId || e.traceId, r);
|
|
63
|
+
}
|
|
64
|
+
function S(e, t, n = null) {
|
|
65
|
+
return x({
|
|
66
|
+
level: e.severityText,
|
|
67
|
+
type: g(e, i),
|
|
68
|
+
namespace: g(e, o),
|
|
69
|
+
journeyId: g(e, l),
|
|
70
|
+
traceId: e.traceId,
|
|
71
|
+
aggregated: g(e, "log.type") === "metric" && g(e, r.start) !== ""
|
|
72
|
+
}, t, n);
|
|
73
|
+
}
|
|
74
|
+
var C = class {
|
|
75
|
+
window = {
|
|
76
|
+
start: 0,
|
|
77
|
+
count: 0
|
|
78
|
+
};
|
|
79
|
+
allow(e) {
|
|
80
|
+
return e.severityText !== "ERROR" && e.severityText !== "FATAL" || u(this.window, 500, n);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
//#endregion
|
|
84
|
+
export { S as a, m as c, b as i, f as l, v as n, x as o, _ as r, p as s, C as t, d as u };
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=sampling-nYIWP_vP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling-nYIWP_vP.js","names":["UINT32_MAX","FNV_PRIME","ERROR_STORM_WINDOW_MS","METRIC_KEYS","ATTR_LOG_TYPE","LEVEL_BYPASS_TYPES","ATTR_APP_NAMESPACE","LEVEL_ORDER","FNV_OFFSET_BASIS","ATTR_JOURNEY_ID","countInWindow","isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work","hash","h","i","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// 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_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\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 to test.\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/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\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\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\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 /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\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, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\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 level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, 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 aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\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 /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, 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 // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW,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Aa;EACpC,WAAWoB,EAASC,GAAQnB,CAAkB;EAC9C,WAAWkB,EAASC,GAAQhB,CAAe;EAC3C,SAASgB,EAAO;EAChB,YACED,EAASC,GAAA,UAAqB,MAAM,YAAYD,EAASC,GAAQtB,EAAY,KAAK,MAAM;CAC5F,GACA8B,GACAK,CACF;AACF;AAQA,IAAaU,IAAb,MAA0B;CAExB,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAO5D,MAAM,GAA4B;EAMhC,OALIvB,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,WAKxDf,EAAc,KAAK,QAAA,KAAsCR,CAAqB;CACvF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mt as e } from "./constants-L_d5YvvQ.js";
|
|
2
2
|
import { n as t, t as n } from "./error-like-Ywo5uRHo.js";
|
|
3
3
|
import { t as r } from "./global-scope-dp2jADRl.js";
|
|
4
4
|
//#region src/utils/library-console.ts
|
|
@@ -120,4 +120,4 @@ function m(e) {
|
|
|
120
120
|
//#endregion
|
|
121
121
|
export { o as a, s as i, u as n, a as o, d as r, m as t };
|
|
122
122
|
|
|
123
|
-
//# sourceMappingURL=sanitize-
|
|
123
|
+
//# sourceMappingURL=sanitize-BiUKCUG6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-DP0xDPrt.js","names":["set","toJson","LIBRARY_CONSOLE_KEY","isDataField","ERROR_OWN_KEYS","globalScope","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","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 if 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\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\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 * Tests if 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 // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, 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. If not, 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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I,IAAOJ,EAAM,WAAWoC,CAAC;EAC/B,AAAIhC,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAO+B;AACT"}
|
|
1
|
+
{"version":3,"file":"sanitize-BiUKCUG6.js","names":["set","toJson","LIBRARY_CONSOLE_KEY","isDataField","ERROR_OWN_KEYS","globalScope","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","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 if 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\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\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 * Tests if 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 // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, 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. If not, 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":";;;;AAUA,IAAMM,IAAQD,EAAYH,CAAmB;AAO7C,SAAgBK,EAAuB,GAAgB;CACrD,OAAOD,EAAM,IAAIE,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOH,EAAM,KAAK;AACpB;;;ACgBA,SAAgBI,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT,IAAME,IAAMC,EAAgBH,EAAM,WAAWC,IAAM,CAAC,CAAC,IAAIA,IAAM,IAAIA;CACnE,OAAO,GAAGD,EAAM,MAAM,GAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,SAASE,CAAG,EAAE;AAC1E;AAOA,SAASC,EAAgB,GAAuB;CAC9C,OAAOC,KAAA,SAA8BA,KAAA;AACvC;AAcA,SAASC,EAAa,GAAwB;CAO5C,OAAO,aANMC,EAAK,YAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,KAAK,IAAIA,EAAK,OAAO,KAEnC,OAAOA,EAAK,aAAc,YAAYA,EAAK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AAMb,KAAOY,GAAM;GACtB,IAAIC,KAASzB,EAAO,mBAAmB;IACrC,EAAI,OAAOI,EAAQ,IAAI,OAAOoB,EAAK,SAASC,CAAK,EAAE,cAAcvB,CAAK;IACtE;GACF;GAGA,AAFA,KACA,EAAM,SAASG,EAAcO,CAAG,IAAA,GAChC,EAAIA,KAAOT,EAAKoB,EAAOX,IAAMZ,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAC7D;EACA,OAAOa;CACT,SAASN,GAAO;EAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,GAEzCE,EAAQ,oBADFK,aAAiB,QAAQA,EAAM,OAAO,QACX,IAAIP,CAAK;CACnD,UAAU;EAGR,EAAK,OAAOX,CAAK;CACnB;AACF;AAOA,SAAgBc,EAAc,GAAuB;CACnD,IAAIqB,IAAQ;CACZ,KAAK,IAAIC,IAAI,GAAGA,IAAIpC,EAAM,QAAQ,KAAK;EACrC,IAAMI,IAAOJ,EAAM,WAAWoC,CAAC;EAC/B,AAAIhC,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAO+B;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=sanitize
|
|
1
|
+
const e=require("./constants-BgRS6MB0.cjs"),t=require("./error-like-gGRx2s36.cjs");var n=require("./global-scope-BN-Io_yv.cjs").t(e.mt);function r(e){return n.run(e)}function i(){return n.open()}function a(e,t){if(e.length<=t)return e;let n=o(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function o(e){return e>=55296&&e<=56319}function s(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 c(e,t,n){return l(e,t,n).value}function l(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:d(e,t,new WeakSet,0,r),bytes:r.bytes}}function u(e,t){return t.bytes+=f(e)+2,e}function d(e,n,r,i,o){if(o.nodes++,o.nodes>n.maxNodes)return u(`[MaxNodes]`,o);if(e==null)return o.bytes+=4,e;if(typeof e==`string`)return u(a(e,n.maxAttributeChars),o);if(typeof e==`number`)return o.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return o.bytes+=5,e;if(typeof e==`bigint`)return u(`${e.toString()}n`,o);if(typeof e==`symbol`)return u(e.toString(),o);if(typeof e==`function`)return u(`[Function ${e.name===``?`anonymous`:e.name}]`,o);if(i>=n.maxDepth)return u(`[MaxDepth]`,o);if(r.has(e))return u(`[Circular]`,o);r.add(e),o.bytes+=2;try{if(e instanceof Error||Object.prototype.toString.call(e)===`[object Error]`){let s=e,c={},l=0;for(let e of Object.keys(s)){let n=s[e];!t.t.has(e)&&t.n(n)&&(c[e]=n,l++)}return{name:u(s.name,o),message:u(a(s.message,n.maxAttributeChars),o),stack:s.stack?u(a(s.stack,n.maxStackChars),o):void 0,cause:s.cause?d(s.cause,n,r,i+1,o):void 0,data:l>0?d(c,n,r,i+1,o):void 0}}if(e instanceof Date)return u(e.toISOString(),o);if(e instanceof RegExp)return u(e.toString(),o);if(e instanceof Map){let t=e,a={},s=0;for(let[e,c]of t){if(s>=n.maxArrayLength){a[`…`]=u(`[${String(t.size-n.maxArrayLength)} more entries]`,o);break}s++;let l=String(e);o.bytes+=f(l)+4,a[l]=d(c,n,r,i+1,o)}return a}if(e instanceof Set)return d([...e].slice(0,n.maxArrayLength),n,r,i,o);if(ArrayBuffer.isView(e)){let t=e.length??0;return u(`[${e.constructor.name}(${String(t)})]`,o)}if(e instanceof Promise)return u(`[Promise]`,o);if(typeof Node<`u`&&e instanceof Node)return u(s(e),o);if(Array.isArray(e)){let t=e,a=t.slice(0,n.maxArrayLength).map(e=>d(e,n,r,i+1,o));return t.length>n.maxArrayLength&&a.push(u(`[${String(t.length-n.maxArrayLength)} more items]`,o)),a}let c=e.toJSON;if(typeof c==`function`)return d(c.call(e),n,r,i+1,o);let l=e,p=Object.keys(l),m={},h=0;for(let e of p){if(h>=n.maxAttributeCount){m[`…`]=u(`[${String(p.length-h)} more keys]`,o);break}h++,o.bytes+=f(e)+4,m[e]=d(l[e],n,r,i+1,o)}return m}catch(e){return o.diagnostics.count(`record.sanitize_failed`),u(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,o)}finally{r.delete(e)}}function f(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 i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return f}});
|
|
2
|
+
//# sourceMappingURL=sanitize-BxuPSXOk.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize--_e4oOPX.cjs","names":["globalScope","LIBRARY_CONSOLE_KEY","ERROR_OWN_KEYS","isDataField","set","toJson","require_constants","require_error_like","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","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 if 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\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\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 * Tests if 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 // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, 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. If not, 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":"mFAUA,IAAMQ,uCAAQR,CAAAA,CAA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,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT"}
|
|
1
|
+
{"version":3,"file":"sanitize-BxuPSXOk.cjs","names":["globalScope","LIBRARY_CONSOLE_KEY","ERROR_OWN_KEYS","isDataField","set","toJson","require_constants","require_error_like","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","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 if 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\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\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 * Tests if 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 // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, 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. If not, 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":"mFAUA,IAAMQ,uCAAQR,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAO7C,SAAgBQ,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB,CCgBA,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,KAAO,KAEnC,OAAOA,EAAK,WAAc,UAAYA,EAAK,UACvC,IAAIA,E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IC,GAASzB,EAAO,kBAAmB,CACrC,EAAI,KAAOI,EAAQ,IAAI,OAAOoB,EAAK,OAASC,CAAK,EAAE,aAAcvB,CAAK,EACtE,KACF,CACA,IACA,EAAM,OAASG,EAAcO,CAAG,EAAA,EAChC,EAAIA,GAAOT,EAAKoB,EAAOX,GAAMZ,EAAQQ,EAAMD,EAAQ,EAAGL,CAAK,CAC7D,CACA,OAAOa,CACT,OAASN,EAAO,CAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,EAEzCE,EAAQ,oBADFK,aAAiB,MAAQA,EAAM,KAAO,QACX,GAAIP,CAAK,CACnD,QAAU,CAGRM,EAAK,OAAOjB,CAAK,CACnB,CACF,CAOA,SAAgBc,EAAc,EAAuB,CACnD,IAAIqB,EAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIpC,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWoC,CAAC,EAC3BhC,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./constants-BgRS6MB0.cjs"),t=require("./sampling-C4my-ma0.cjs"),n=require("./log-record-jX9eWUP8.cjs"),r=require("./sanitize-BxuPSXOk.cjs"),i=require("./identity-Bwku7zzN.cjs"),a=require("./library-request-gMFOCNcn.cjs"),o=require("./openfin-DtH2f7zX.cjs"),s=require("./platform-o7r1ocOu.cjs"),c=require("./batch-C4oF6XZT.cjs"),l=require("./remote-rules-BHgEGlYi.cjs");function u(e){let{maxBatches:t}=e;return e.mode===`until-delivered`?{maxBatches:t,maxAgeMs:1/0,maxAttempts:1/0}:{maxBatches:t,maxAgeMs:e.maxAgeMs,maxAttempts:e.maxAttempts}}function d(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function f(e,t){return`${e}${String(t.createdAt).padStart(14,`0`)}.${t.id}`}function p(e,t){let n=[];return t.guard(`storage.unavailable`,`The library could not list the localStorage keys.`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function m(e,t){let n=t.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return n===void 0?null:c.i(n)?n:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function h(n,r){let i=0;for(let a of p(e.U,r)){let o=r.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(a);return localStorage.removeItem(a),e});if(!o)continue;let s=m(o,r);if(s!==null)try{await t.c(n.save(s),e.dn),i++}catch(e){r.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:a},e)}}return i}function g(t,n,r){let i=`writing the emergency queue, ${String(t.records.length)} records`,a=[],o=n.guard(`storage.quota_exceeded`,i,()=>{let r=p(e.U,n);for(let e of r.slice(0,Math.max(0,r.length-20+1))){let t=m(String(localStorage.getItem(e)),n);t!==null&&a.push(t),localStorage.removeItem(e)}return localStorage.setItem(f(e.U,t),JSON.stringify(t)),!0});n.guard(`pipeline.crashed`,`The loss report of the emergency queue failed.`,()=>{if(a.length>0){let e=a.flatMap(e=>e.records);r?.(`exit_queue_full`,e,a.map(e=>e.id))}o!==!0&&r?.(`quota`,t.records,[t.id])})}async function _(e,t){return await d(`ui-observability.emergency`,t,()=>h(e,t),{skipIfBusy:!1})??0}function v(e){return Array.isArray(e.records)&&e.records.some(c.r)}var y=class{howMany;isAudit;plain=[];audit=[];constructor(e,t){this.howMany=e,this.isAudit=t}add(e){return this.isAudit(e)?this.audit.length<this.howMany&&this.audit.push(e):this.plain.push(e),this.plain.length<this.howMany}picked(){return[...this.plain,...this.audit].slice(0,this.howMany)}};function b(e,t,n){let r=new y(t,n);for(let t of e)if(!r.add(t))break;return r.picked()}function x(e,t,n,r){return e.batches+=n,e.records+=r,e.reason=t,{batches:n,records:r,reason:t}}function S(e,t,n,r){n.batches!==0&&(e.report(`storage.evicted`,`The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`,{...n}),t?.(n,r))}function C(t){let n=e.x.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var ee=class{limits;diagnostics;onGap;name=e.mn;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`))await this.prune();else if(this.evictForQuota(),!this.write(e,`localStorage refused a batch even after evicting`)){let t={batches:1,records:e.records.length,reason:`quota`};S(this.diagnostics,this.onGap,t,[e])}}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=[],r=[];for(let t of this.keys()){let i=C(t);i===null||i<e?n.push(t):r.push(t)}this.drop(t,`expired`,[...this.entries(n)]);let i=r.length-this.limits.maxBatches;return i>0&&this.drop(t,`over_capacity`,this.evictable(r,i)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(t,n){return this.diagnostics.guard(`storage.quota_exceeded`,n,()=>(localStorage.setItem(f(e.x,t),JSON.stringify(t)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`},n=Math.ceil(e.length/4);this.drop(t,`quota`,this.evictable(e,n))}evictable(e,t){return b(this.entries(e),t,e=>e.batch!==null&&v(e.batch))}*entries(e){for(let t of e)yield{key:t,batch:this.read(t)}}drop(e,t,n){if(n.length===0)return;let r=[];for(let{key:e,batch:t}of n)this.removeKey(e),t&&r.push(t);let i=x(e,t,n.length,c.n(r));S(this.diagnostics,this.onGap,i,r)}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(t));return n===void 0?null:c.i(n)?n:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return p(e.x,this.diagnostics)}},w=class{limits;onGap;name=e.hn;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),this.report(t,`expired`,n);let r=this.batches.length-this.limits.maxBatches;if(r>0){let e=b(this.batches,r,v);this.batches=this.batches.filter(t=>!e.includes(t)),this.report(t,`over_capacity`,e)}return Promise.resolve(t)}report(e,t,n){if(n.length===0)return;let r=x(e,t,n.length,c.n(n));this.onGap?.(r,n)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},te=t=>({name:e.gn,save:e=>(t?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),Promise.resolve()),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()});function ne(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function re(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e._n,`1`),localStorage.removeItem(e._n),!0))===!0}async function ie(e,t,n,r,i){if(e===`none`)return te(i);if(e===`memory`)return new w(n,i);if(e===`indexeddb`||e===`auto`){if(ne(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-Cvavrf-y.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new w(n,i)}return re(r)?new ee(n,r,i):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new w(n,i))}var T=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i,a){super(t,a===void 0?void 0:{cause:a}),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function ae(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.wt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var E={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},D=new Set([e.n,...Object.keys(E)]);function oe(t){return e.Et.test(t)?Number(BigInt(t)/e.Dt):Date.now()}function se(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function ce(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function O(e,t,n,r){let i=se(n);if(i!==null)ce(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)O(e,t,i,r);else for(let[i,a]of Object.entries(n))O(e,`${t}.${i}`,a,r);r.delete(n)}}function k(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))O(t,r,i,n);return t}function le(e){let t=[];for(let[n,r]of Object.entries(E)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function ue(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(D.has(e)&&typeof t==`string`)))}var de={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=oe(t.timeUnixNano),{attributes:r}=t,i=r[e.n];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.V},log:{level:e.B[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:le(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Gt],version:t.resource[e.Kt],environment:t.resource[e.Vt]},user_agent:{original:t.resource[e.zt]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...k(t.resource),...k(ue(r))}})}).join(`
|
|
2
|
+
`)}\n`,contentType:e.N}}};function A(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isSafeInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(A).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:j(e)}}:null}function j(e){let t=[];for(let[n,r]of Object.entries(e)){let e=A(r);e&&t.push({key:n,value:e})}return t}var M=new WeakMap;function fe(e){let t=M.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return M.set(e,n),n}function N(e){let t=new Map;for(let n of e){let e=fe(n.resource),r=t.get(e);r?r.records.push(n):t.set(e,{resource:n.resource,records:[n]})}return[...t.values()]}var P={name:e.in,serialize(t){let n=N(t).map(t=>({resource:{attributes:j(t.resource)},scopeLogs:[{scope:{name:e.bn,version:e.xn},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:j(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:n}),contentType:e.M}}},F=1;function I(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function L(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function R(t){let n=t.attributes[e.St.attributeKeys],r={};if(!Array.isArray(n))return r;for(let e of n){let n=typeof e==`string`&&!e.startsWith(`metric.`)?t.attributes[e]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[e]=n)}return r}function z(t){let n=I(t,e.St.count);if(n===void 0){let e=I(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.St.bounds],i=t.attributes[e.St.buckets];if(!L(r)||!L(i)||i.length!==r.length+1)return null;let a=I(t,e.St.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:I(t,e.St.sum),min:a,max:I(t,e.St.max),bucketCounts:i.map(String),explicitBounds:r}}function B(e){let t=I(e,`metric.value`);return t===void 0?null:{asDouble:t}}function V(t,n){let r=t.attributes[e.St.start],i=n===`histogram`?z(t):B(t);return i===null?null:{attributes:j(R(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function pe({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:F,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var me={name:e.in,serialize(t){let n=N(t).map(t=>{let n=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],r=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=V(e,r);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:r,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=n.get(c)??s;l.points.push(i),n.set(c,l)}return{resource:{attributes:j(t.resource)},scopeMetrics:[{scope:{name:e.bn,version:e.xn},metrics:[...n.values()].map(pe)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.M}}},H={internal:1,client:3},he=2,ge=0,_e=new Set([e.d,...Object.values(e.ln)]);function U(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function ve(t){let n=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!_e.has(e))),r=U(t,e.ln.parentId);return{traceId:t.traceId,spanId:t.spanId,...r?{parentSpanId:r}:{},name:t.body,kind:U(t,e.ln.kind)===`client`?H.client:H.internal,startTimeUnixNano:U(t,e.ln.start)??t.timeUnixNano,endTimeUnixNano:U(t,e.ln.end)??t.timeUnixNano,attributes:j(n),status:{code:U(t,e.ln.status)===`error`?he:ge}}}var ye={name:e.in,serialize(t){let n=N(t).map(t=>({resource:{attributes:j(t.resource)},scopeSpans:[{scope:{name:e.bn,version:e.xn},spans:t.records.map(ve)}]}));return{body:JSON.stringify({resourceSpans:n}),contentType:e.M}}};function be(e){return e===`otlp`?P:e===`ecs`?de:e}function W(e,t){let n=t=>e.records.length>0&&e.records.every(e=>c.t(e,`log.type`)===t);return t.metricsEndpoint!==``&&n(`metric`)?`metrics`:n(`span`)?`traces`:`logs`}function G(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var xe={metrics:me,traces:ye};function K(e,t,n,r){try{return(xe[W(t,e)]??be(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var q=class{config;diagnostics;onSampling;onLoss;throttledUntil={logs:0,metrics:0,traces:0};acceptedAt=null;constructor(e,t,n=()=>void 0,r=()=>void 0){this.config=e,this.diagnostics=t,this.onSampling=n,this.onLoss=r}throttledForMs(e){return Math.max(0,this.throttledUntil[W(e,this.config)]-Date.now())}lastSendAt(){return this.acceptedAt}serialize(e){let t=K(this.config,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`);return t||this.onLoss(`unserializable`,e.records,[e.id]),t}accept(e,t){this.throttledUntil[e]=0,this.acceptedAt=Date.now(),this.config.sampling.remote&&t!=null&&this.onSampling(t)}reject(t,n,r,i){let a=String(t);if(t===401||t===403){let e=i.advice===void 0?``:` ${i.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${a}.${e}`,{status:t,endpoint:G(r,this.config)}),new T(`permanent`,`The server rejected the batch with ${a}.`,t)}if(t===413)return new T(`too_large`,`The payload is too large.`,t,void 0,i.maxBytes);if(t===429||t===503){let n=t===429,a=i.retryAfterMs===void 0?void 0:Math.min(i.retryAfterMs,e.en);return this.throttledUntil[r]=Date.now()+(a??2e3),n&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:a}),new T(`throttled`,n?`The server throttles the requests.`:`The service is not available.`,t,a)}return t===408||t>=500?new T(`transient`,`The server returned the error ${a}.`,t):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${a}. The library dropped it.`,{batchId:n,status:t}),new T(`permanent`,`The server rejected the batch with ${a}.`,t))}};function J(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records}}function Se(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isInteger(t)&&t>=100&&t<=599}function Y(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var Ce=class extends q{async send(n){let{transport:i}=this.config;if(!i||n.records.length===0)return;let o=this.serialize(n);if(!o)return;let s=W(n,this.config),c=J(n,o,s),l;try{l=await t.c(a.i(()=>a.r(()=>r.o(()=>i(c)))),e.Rt)}catch(e){let n=e instanceof t.s?e:void 0;throw new T(n?`timeout`:`transient`,n?.message??`The custom transport failed.`,void 0,void 0,void 0,e)}if(!Se(l))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:n.id}),new T(`transient`,`The custom transport returned no valid status.`);let{status:u}=l;if(u>=200&&u<300)this.accept(s,l.sampling);else throw this.reject(u,n.id,s,{retryAfterMs:Y(l.retryAfterMs),maxBytes:Y(l.maxBytes)})}},we=class{deps;installed=!1;keepaliveBytes=0;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(e){let{config:t,diagnostics:n}=this.deps;if(n.guard(`pipeline.crashed`,`The metric points before the exit flush failed.`,()=>{this.deps.beforeExit?.()}),e===`hidden`){this.flushAlive();return}if(t.transport){this.flushCustom(e,t.transportOnExit);return}let r=this.endpointUrl();if(r!==null){this.keepaliveBytes=0;for(let i of this.deps.drainForExit()){let a=W(i,t),o=a===`logs`?r.href:G(a,t);o?this.flushBatch(i,e,new URL(o)):n.count(`record.dropped_no_destination`)}}}flushBatch(t,n,i){let{config:a}=this.deps;if(t.records.length===0)return;let o=this.serialize(t,n);if(!o)return;if(r.t(o.body)>6e4){this.park(t);return}i.searchParams.set(e.jt,t.id),i.searchParams.set(e.Mt,n);let s=i.toString(),c=this.deps.exitHeaders();if(c){this.keepaliveFetch(s,t,o.body,n,()=>{let n=new Headers(c);return n.set(e.$,o.contentType),n.set(e.Z,t.id),n});return}if(a.headers){this.park(t);return}let l=this.beacon(s,o.body);l!==`sent`&&(l===`refused`?this.park(t):this.keepaliveFetch(s,t,o.body,n,()=>new Headers({[e.$]:e.P})))}flushAlive(){let{diagnostics:e}=this.deps,t=`The flush of the hidden document failed.`;e.guard(`pipeline.crashed`,t,()=>{Promise.resolve(this.deps.flushAlive()).catch(n=>{e.report(`pipeline.crashed`,t,void 0,n)})})}flushCustom(e,t){let{config:n,diagnostics:r}=this.deps;for(let i of this.deps.drainForExit()){let o=this.serialize(i,e);if(!o)continue;let s=J(i,o,W(i,n));(t===void 0||r.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>a.r(()=>t(s)))!==!0)&&this.park(i)}}park(e){let{config:t,diagnostics:n,onLoss:r}=this.deps;t.storage===`memory`||t.storage===`none`?r?.(`not_stored`,e.records,[e.id]):g(e,n,r)}serialize(e,t){let n=K(this.deps.config,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`);return n||this.deps.onLoss?.(`unserializable`,e.records,[e.id]),n}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`The sendBeacon call failed.`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(e,t,n,i,a){let{config:o,diagnostics:s}=this.deps,c=()=>{this.park(t)},l=r.t(n);this.keepaliveBytes+l>6e4?c():(this.keepaliveBytes+=l,s.guard(`transport.http_error`,`The keepalive fetch failed.`,()=>(fetch(e,{method:`POST`,body:n,headers:a(),credentials:o.credentials,keepalive:!0}).catch(e=>{s.report(`transport.http_error`,`The exit flush failed.`,{reason:i},e),c()}),!0))!==!0&&c())}};async function Te(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.W)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var Ee=`In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,X=class extends q{cachedHeaders;async send(e,t){let{config:n}=this,r=W(e,n),i=G(r,n);i?e.records.length!==0&&await this.post(e,r,i,t):this.diagnostics.count(`record.dropped_no_destination`)}lastHeaders(){let{headers:e}=this.config;if(!e)return;if(typeof e!=`function`)return e;let t=this.cachedHeaders;return t?.source===e&&t.endpoint===this.config.endpoint&&t.metricsEndpoint===this.config.metricsEndpoint&&t.tracesEndpoint===this.config.tracesEndpoint?t.headers:void 0}async post(t,n,r,i){let a=this.serialize(t);if(!a)return;let o=await this.attempt(t,r,a,i);if(this.rejectsCredentials(o.status)&&typeof this.config.headers==`function`&&(this.cachedHeaders=void 0,o=await this.attempt(t,r,a,i)),o.ok){this.accept(n,o.headers.get(e.tt));return}let s=o.status,c=ae(o.headers.get(e.et)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,n,{retryAfterMs:c,maxBytes:l,advice:Ee})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i){let a=Date.now()+e.Rt,o=new Headers(await this.before(this.resolveHeaders(),a,n));o.set(e.$,r.contentType),o.set(e.Z,t.id),o.set(e.X,String(t.attempts));let s=await this.before(this.encodeBody(r.body),a,n);typeof s!=`string`&&o.set(e.Q,e.W);let c=this.keepalive(s);return c&&i?.(),this.dispatch(n,o,s,a,c)}async before(e,n,r){try{return await t.c(e,Math.max(0,n-Date.now()))}catch{throw this.timeout(r)}}timeout(t){let n=`The request took longer than ${String(e.Rt)} ms.`;return this.diagnostics.report(`transport.timeout`,n,{endpoint:t}),new T(`timeout`,n)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||r.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>Te(e))??e}async dispatch(e,n,r,i,o){let{config:c}=this,l=new AbortController,u=setTimeout(()=>{l.abort()},Math.max(0,i-Date.now()));t.l(u);try{return await a.r(()=>fetch(e,{method:`POST`,headers:n,body:r,credentials:c.credentials,signal:l.signal,cache:`no-store`,keepalive:o}))}catch{throw l.signal.aborted?this.timeout(e):new T(s.r()?`transient`:`offline`,`A network error occurred.`)}finally{clearTimeout(u)}}keepalive(e){let t=globalThis.document?.visibilityState===`hidden`,n=typeof e==`string`?r.t(e):e.byteLength;return t&&n<=6e4}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`The library could not read the body of the 413 response.`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;if(!e)return{};if(typeof e!=`function`)return e;let{endpoint:t,metricsEndpoint:n,tracesEndpoint:r}=this.config,i=await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()));return i&&(this.cachedHeaders={source:e,endpoint:t,metricsEndpoint:n,tracesEndpoint:r,headers:i}),i??{}}},De=class{storage;transport;diagnostics;config;batchesPerDrain;onLoss;timer=null;attempt=0;draining=!1;stopped=!1;maxAttempts;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20,a=()=>void 0){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i,this.onLoss=a,this.maxAttempts=u(r.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.$t)}nudge(){this.draining||this.schedule(e.Qt)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let n=setTimeout(()=>{this.drain()},e);this.timer=n,t.l(n)}bounded(n){return t.c(n,e.dn)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Qt*2**this.attempt,e.en);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await d(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.$t)}finally{this.draining=!1}}}async drainLocked(){try{if(!s.r())return this.schedule(e.$t),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.$t),!0;let n=new Set,r=0;for(let e of t){if(this.stopped)return!0;let t=W(e,this.config);if(n.has(t))continue;let i=await this.deliver(e);if(i===`stop`)return!0;i!==`next`&&(n.add(t),r=Math.max(r,i))}return n.size>0?this.schedule(r):this.schedule(t.length===this.batchesPerDrain?0:e.$t),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${t.attempts.toString()} attempts.`,{batchId:t.id,records:t.records.length}),this.onLoss(`max_attempts`,t.records,[t.id]),await this.bounded(this.storage.remove(t.id)),`next`;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,`next`}catch(n){let r=n instanceof T?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),`next`):r?.kind===`offline`?(this.schedule(e.$t),`stop`):r?.kind===`throttled`?(this.attempt++,r.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,r?.retryAfterMs??this.backoffMs())}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof T?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=c.a(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),this.onLoss(`rejected`,e.records,[e.id]),[])}},Z=[`metrics`,`logs`,`traces`];function Q(t){let n=t.attributes[e.d];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}var $=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}get size(){return this.pending.length}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,t.l(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},Oe=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new $(i.logs,a),metrics:new $(i.metrics,a),traces:new $(i.traces,a)}}push(e){this.stopped||(e.observedTimeUnixNano=n.r(),this.route(e))}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),Z.map(t=>this.toBatch([...e.filter(e=>Q(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(){if(!this.stopped)for(let e of Z)this.claim(this.streams[e]);await Promise.all([...this.open].map(e=>e.done))}counts(){let e=e=>{let t=0;for(let n of e)t+=n.batch.records.length;return t},t=e(this.queue);return{pending:Z.reduce((e,t)=>e+this.streams[t].size,0)+t,inFlight:e(this.open)-t}}destroy(){this.stopped=!0;for(let e of Z)this.streams[e].stop();this.queue.length=0;for(let e of this.open)e.resolve();this.open.clear()}toBatch(e){return e.length===0?null:{id:i.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=this.streams[Q(e)];if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){this.enqueue(this.toBatch(e.take()))}enqueue(e){if(!e)return;let t,n={batch:e,done:new Promise(e=>{t=e}),resolve:t};this.unconfirmed.set(e.id,e),this.open.add(n),this.queue.push(n),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){let{batch:t}=e;try{await this.dispatch(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:t.id},e)}finally{this.inFlight--,this.open.delete(e),e.resolve(),this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs(e);if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`The server throttles requests. The pipeline stored the batch and did not send it.`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e,()=>{this.unconfirmed.delete(e.id)})}catch(t){await this.storeFailed({...e,attempts:e.attempts+1},t),this.diagnostics.report(`transport.http_error`,`The send failed. The pipeline stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await this.retry.storeFailed(e,t)})}async store(n){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await t.c(this.storage.save(n),e.dn),this.retry.nudge()})}},ke=class t{storage;retry;pipeline;exitFlush;diagnostics;transport;constructor(e,t,n,r,i,a){this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i,this.transport=a}static async create(n){let{config:r,diagnostics:i}=n,a=await ie(r.storage,e.un,u(r.retention),i,n.onGap),o=e=>{let t=l.n(e,i);t&&l.t(n.remote,r,t)},{onLoss:s}=n,c=r.transport?void 0:new X(r,i,o,s),d=c??new Ce(r,i,o,s),f=new De(a,d,i,r,20,s),{batching:p}=r,m=new Oe(d,a,f,i,{logs:{flushIntervalMs:p.logFlushIntervalMs,batchSize:p.logBatchSize},metrics:{flushIntervalMs:p.metricFlushIntervalMs,batchSize:p.metricBatchSize},traces:{flushIntervalMs:p.logFlushIntervalMs,batchSize:p.logBatchSize}}),h=new we({config:r,diagnostics:i,drainForExit:()=>m.drainForExit(),flushAlive:()=>m.flushPending(),exitHeaders:()=>c?.lastHeaders(),onLoss:s,beforeExit:n.beforeExit}),g=!1;try{h.install(),f.start(),g=!0}finally{g||(h.uninstall(),f.stop())}let _=new t(a,f,m,h,i,d);return _.importEmergency(),_}push(e){this.pipeline.push(e)}async flush(){await this.pipeline.flushPending()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}stats(){return{...this.pipeline.counts(),lastSendAt:this.transport.lastSendAt()}}async destroy(){await this.diagnostics.guardAsync(`pipeline.crashed`,`The flush before shutdown failed.`,()=>this.flush()),this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}async importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>_(this.storage,this.diagnostics));e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=ke,exports.i=v,exports.n=S,exports.r=y,exports.t=x;
|
|
3
|
+
//# sourceMappingURL=sender-6vrT9fFL.cjs.map
|