@utk09/ui-observability 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +189 -25
  3. package/dist/bus/bus.d.ts +30 -0
  4. package/dist/bus-CUXRY0JR.cjs +2 -0
  5. package/dist/bus-CUXRY0JR.cjs.map +1 -0
  6. package/dist/{bus-BTMuVkDk.js → bus-DPDrlUBY.js} +96 -50
  7. package/dist/bus-DPDrlUBY.js.map +1 -0
  8. package/dist/capture/console.d.ts +37 -0
  9. package/dist/capture/errors.d.ts +2 -4
  10. package/dist/capture/long-frames.d.ts +31 -0
  11. package/dist/capture/storm.d.ts +17 -0
  12. package/dist/capture/types.d.ts +2 -0
  13. package/dist/console-CNljJict.js +81 -0
  14. package/dist/console-CNljJict.js.map +1 -0
  15. package/dist/console-PKzc-FmR.cjs +2 -0
  16. package/dist/console-PKzc-FmR.cjs.map +1 -0
  17. package/dist/constants-B28fDv2F.cjs +2 -0
  18. package/dist/constants-B28fDv2F.cjs.map +1 -0
  19. package/dist/constants-Bu49bm39.js +93 -0
  20. package/dist/constants-Bu49bm39.js.map +1 -0
  21. package/dist/constants.d.ts +35 -5
  22. package/dist/core/breadcrumbs.d.ts +1 -1
  23. package/dist/core/pipeline.d.ts +2 -2
  24. package/dist/core/record.d.ts +3 -0
  25. package/dist/core/remote-rules.d.ts +17 -0
  26. package/dist/core/remote-sampling.d.ts +65 -0
  27. package/dist/core/runtime.d.ts +10 -4
  28. package/dist/core/sampling.d.ts +5 -2
  29. package/dist/core/sender.d.ts +3 -0
  30. package/dist/errors-C78ZTjet.cjs +3 -0
  31. package/dist/errors-C78ZTjet.cjs.map +1 -0
  32. package/dist/{errors-Dwm2SzBa.js → errors-Dnc-X4Ec.js} +19 -20
  33. package/dist/errors-Dnc-X4Ec.js.map +1 -0
  34. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  35. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  36. package/dist/global-scope-dp2jADRl.js +19 -0
  37. package/dist/global-scope-dp2jADRl.js.map +1 -0
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +307 -241
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
  44. package/dist/{indexeddb-storage-B5dwq4hW.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
  45. package/dist/{indexeddb-storage-DjY4Ml6t.js → indexeddb-storage-uD4oaRMc.js} +10 -10
  46. package/dist/{indexeddb-storage-DjY4Ml6t.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
  47. package/dist/{interactions-DVom6eYn.cjs → interactions-CsE2y_fQ.cjs} +2 -2
  48. package/dist/{interactions-DVom6eYn.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
  49. package/dist/{interactions-DZmLu7l2.js → interactions-igKTAJvj.js} +2 -2
  50. package/dist/{interactions-DZmLu7l2.js.map → interactions-igKTAJvj.js.map} +1 -1
  51. package/dist/library-request-Br_T09Bn.cjs +2 -0
  52. package/dist/library-request-Br_T09Bn.cjs.map +1 -0
  53. package/dist/library-request-Dt0fXhcn.js +14 -0
  54. package/dist/library-request-Dt0fXhcn.js.map +1 -0
  55. package/dist/long-frames-6pnjWSSR.js +65 -0
  56. package/dist/long-frames-6pnjWSSR.js.map +1 -0
  57. package/dist/long-frames-DahhqM6u.cjs +2 -0
  58. package/dist/long-frames-DahhqM6u.cjs.map +1 -0
  59. package/dist/models/bus.d.ts +16 -0
  60. package/dist/models/config.d.ts +120 -6
  61. package/dist/network-CZ0aFUsy.cjs +2 -0
  62. package/dist/network-CZ0aFUsy.cjs.map +1 -0
  63. package/dist/{network-C4d2uw2Z.js → network-aSNbwpue.js} +16 -15
  64. package/dist/network-aSNbwpue.js.map +1 -0
  65. package/dist/{platform-CY8S3hUs.js → platform-BwbMRwHm.js} +7 -7
  66. package/dist/{platform-CY8S3hUs.js.map → platform-BwbMRwHm.js.map} +1 -1
  67. package/dist/{platform-CXio0W2n.cjs → platform-D_XkVIF6.cjs} +2 -2
  68. package/dist/{platform-CXio0W2n.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
  69. package/dist/remote-rules-5UA23alm.js +86 -0
  70. package/dist/remote-rules-5UA23alm.js.map +1 -0
  71. package/dist/remote-rules-rJJZKVG8.cjs +2 -0
  72. package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
  73. package/dist/sampling-E4x92Nn2.cjs +2 -0
  74. package/dist/sampling-E4x92Nn2.cjs.map +1 -0
  75. package/dist/sampling-J1eahbfT.js +160 -0
  76. package/dist/sampling-J1eahbfT.js.map +1 -0
  77. package/dist/sanitize-BMhh8ghJ.cjs +2 -0
  78. package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
  79. package/dist/sanitize-UJ-4Lb0n.js +114 -0
  80. package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
  81. package/dist/sender-B6ufz26f.cjs +3 -0
  82. package/dist/sender-B6ufz26f.cjs.map +1 -0
  83. package/dist/{sender-dpvR_bHM.js → sender-G6v4Uqi4.js} +304 -219
  84. package/dist/sender-G6v4Uqi4.js.map +1 -0
  85. package/dist/storm-BtzgLOCX.cjs +2 -0
  86. package/dist/storm-BtzgLOCX.cjs.map +1 -0
  87. package/dist/storm-DJkEZP_8.js +10 -0
  88. package/dist/storm-DJkEZP_8.js.map +1 -0
  89. package/dist/transport/custom-transport.d.ts +20 -0
  90. package/dist/transport/errors.d.ts +2 -1
  91. package/dist/transport/exit-flush.d.ts +15 -0
  92. package/dist/transport/http-transport.d.ts +2 -24
  93. package/dist/transport/memory-transport.d.ts +30 -0
  94. package/dist/transport/retry-engine.d.ts +2 -2
  95. package/dist/transport/serializers/select.d.ts +12 -1
  96. package/dist/transport/status-transport.d.ts +72 -0
  97. package/dist/utils/console.d.ts +7 -6
  98. package/dist/utils/deadline.d.ts +7 -0
  99. package/dist/utils/global-scope.d.ts +20 -0
  100. package/dist/utils/library-console.d.ts +11 -0
  101. package/dist/utils/library-request.d.ts +12 -0
  102. package/package.json +4 -2
  103. package/dist/bus-BTMuVkDk.js.map +0 -1
  104. package/dist/bus-ChIXDAWD.cjs +0 -2
  105. package/dist/bus-ChIXDAWD.cjs.map +0 -1
  106. package/dist/constants-0-YchbAL.js +0 -75
  107. package/dist/constants-0-YchbAL.js.map +0 -1
  108. package/dist/constants-TUFcy95w.cjs +0 -2
  109. package/dist/constants-TUFcy95w.cjs.map +0 -1
  110. package/dist/errors-DRXBRqvm.cjs +0 -3
  111. package/dist/errors-DRXBRqvm.cjs.map +0 -1
  112. package/dist/errors-Dwm2SzBa.js.map +0 -1
  113. package/dist/indexeddb-storage-B5dwq4hW.cjs +0 -2
  114. package/dist/network-C4d2uw2Z.js.map +0 -1
  115. package/dist/network-CuqWadNn.cjs +0 -2
  116. package/dist/network-CuqWadNn.cjs.map +0 -1
  117. package/dist/sampling-CEthcmEX.cjs +0 -2
  118. package/dist/sampling-CEthcmEX.cjs.map +0 -1
  119. package/dist/sampling-CJsI_24L.js +0 -251
  120. package/dist/sampling-CJsI_24L.js.map +0 -1
  121. package/dist/sender-ByFAkXVd.cjs +0 -3
  122. package/dist/sender-ByFAkXVd.cjs.map +0 -1
  123. package/dist/sender-dpvR_bHM.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-rules-rJJZKVG8.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`, or else `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests whether a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Tests whether a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD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AAgBG,EACd,EACA,EACA,EACM,CACFvB,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7CyB,EAAK,UAAU,MAAMxB,CAAM,CAC7B"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-B28fDv2F.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(){return`${String(Date.now())}000000`}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}var i={local:()=>localStorage,session:()=>sessionStorage};function a(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function o(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function s(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return o(16)}function c(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function l(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function u(t,n=i){let r=s(t),a=Date.now(),o=s(t),u=c(n,`local`,e.Yt,t);if(u)try{let e=JSON.parse(u);e.id&&a-(e.lastSeenAt??0)<18e5&&(o=e.id)}catch{t.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`)}let d=JSON.stringify({id:o,lastSeenAt:a});l(n,`local`,e.Yt,d,t);let f=c(n,`session`,`ui-observability.tab`,t)??``;return f||(f=s(t),l(n,`session`,e.sn,f,t)),{sessionId:o,tabId:f,contextId:r}}function d(t,n,r){l(r,`session`,e.sn,t,n)}var f=class{diagnostics;stores;lastTouchAt=0;constructor(e,t=i){this.diagnostics=e,this.stores=t}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});l(this.stores,`local`,e.Yt,r,this.diagnostics)}},p=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function m(e,n){let r,i=new Promise((e,i)=>{let a=setTimeout(()=>{i(new p(n))},n);r=a,t.t(a)});return Promise.race([e,i]).finally(()=>{clearTimeout(r)})}function h(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function g(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function _(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={rate:i,length:r.length});return n}function v(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,o=_(e,r),s=n?_(e,n.rates):void 0;return s&&s.length>=(o?.length??-1)?Math.min(s.rate,a):o?o.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function y(t,n,r){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=v(t.namespace,n,r);return r&&e.at[t.level]<e.at[n.minLevel]&&(i=Math.min(i,n.sampling.remoteMaxRate)),i>=1?!0:i<=0?!1:h(t.journeyId||t.traceId)/e.pn<i}function b(t,n,r=null){return y({level:t.severityText,type:g(t,e.l),namespace:g(t,e.n),journeyId:g(t,e.a),traceId:t.traceId},n,r)}var x=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return d}});
2
+ //# sourceMappingURL=sampling-E4x92Nn2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-E4x92Nn2.cjs","names":["SESSION_ID_KEY","TAB_ID_KEY","FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","require_unref","nowUnixNano","isLogRecord","value","record","BROWSER_STORES","memoryStores","wrap","map","key","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","DeadlineError","ms","withDeadline","expire","deadline","timer","reject","work","hash","h","readAttr","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies at once.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n if (remote && LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel]) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"8EAwDA,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gB,EAOhB,MAAM,EAA4B,CAChC,GAAIxD,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMqB,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
@@ -0,0 +1,160 @@
1
+ import { H as e, U as t, Yt as n, a as r, at as i, l as a, n as o, pn as s, sn as c } from "./constants-Bu49bm39.js";
2
+ import { t as l } from "./unref-16maCyKA.js";
3
+ //#region src/models/log-record.ts
4
+ function u() {
5
+ return `${String(Date.now())}000000`;
6
+ }
7
+ function d(e) {
8
+ if (typeof e != "object" || !e) return !1;
9
+ let t = e;
10
+ return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
11
+ }
12
+ //#endregion
13
+ //#region src/utils/identity.ts
14
+ var f = {
15
+ local: () => localStorage,
16
+ session: () => sessionStorage
17
+ };
18
+ function p() {
19
+ let e = (e) => ({
20
+ getItem: (t) => e.get(t) ?? null,
21
+ setItem: (t, n) => {
22
+ e.set(t, n);
23
+ },
24
+ removeItem: (t) => {
25
+ e.delete(t);
26
+ }
27
+ }), t = e(/* @__PURE__ */ new Map()), n = e(/* @__PURE__ */ new Map());
28
+ return {
29
+ local: () => t,
30
+ session: () => n
31
+ };
32
+ }
33
+ function m(e) {
34
+ let t = new Uint8Array(e);
35
+ if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
36
+ else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
37
+ return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
38
+ }
39
+ function h(e) {
40
+ try {
41
+ if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
42
+ } catch {
43
+ e.count("platform.api_blocked");
44
+ }
45
+ return m(16);
46
+ }
47
+ function g(e, t, n, r) {
48
+ return r.guard("storage.unavailable", `The library could not read ${t}Storage.`, () => e[t]().getItem(n)) ?? null;
49
+ }
50
+ function _(e, t, n, r, i) {
51
+ i.guard("storage.unavailable", `The library could not write to ${t}Storage.`, () => {
52
+ e[t]().setItem(n, r);
53
+ });
54
+ }
55
+ function v(e, t = f) {
56
+ let r = h(e), i = Date.now(), a = h(e), o = g(t, "local", n, e);
57
+ if (o) try {
58
+ let e = JSON.parse(o);
59
+ e.id && i - (e.lastSeenAt ?? 0) < 18e5 && (a = e.id);
60
+ } catch {
61
+ e.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
62
+ }
63
+ let s = JSON.stringify({
64
+ id: a,
65
+ lastSeenAt: i
66
+ });
67
+ _(t, "local", n, s, e);
68
+ let l = g(t, "session", "ui-observability.tab", e) ?? "";
69
+ return l || (l = h(e), _(t, "session", c, l, e)), {
70
+ sessionId: a,
71
+ tabId: l,
72
+ contextId: r
73
+ };
74
+ }
75
+ function y(e, t, n) {
76
+ _(n, "session", c, e, t);
77
+ }
78
+ var b = class {
79
+ diagnostics;
80
+ stores;
81
+ lastTouchAt = 0;
82
+ constructor(e, t = f) {
83
+ this.diagnostics = e, this.stores = t;
84
+ }
85
+ touch(e) {
86
+ let t = Date.now();
87
+ if (t - this.lastTouchAt < 6e4) return;
88
+ this.lastTouchAt = t;
89
+ let r = JSON.stringify({
90
+ id: e,
91
+ lastSeenAt: t
92
+ });
93
+ _(this.stores, "local", n, r, this.diagnostics);
94
+ }
95
+ }, x = class extends Error {
96
+ constructor(e) {
97
+ super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
98
+ }
99
+ };
100
+ function S(e, t) {
101
+ let n, r = new Promise((e, r) => {
102
+ let i = setTimeout(() => {
103
+ r(new x(t));
104
+ }, t);
105
+ n = i, l(i);
106
+ });
107
+ return Promise.race([e, r]).finally(() => {
108
+ clearTimeout(n);
109
+ });
110
+ }
111
+ //#endregion
112
+ //#region src/core/sampling.ts
113
+ function C(n) {
114
+ let r = e;
115
+ for (let e = 0; e < n.length; e++) r ^= n.charCodeAt(e), r = Math.imul(r, t);
116
+ return r >>> 0;
117
+ }
118
+ function w(e, t) {
119
+ let n = e.attributes[t];
120
+ return typeof n == "string" ? n : "";
121
+ }
122
+ function T(e, t) {
123
+ let n;
124
+ for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
125
+ rate: i,
126
+ length: r.length
127
+ });
128
+ return n;
129
+ }
130
+ function E(e, t, n) {
131
+ let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = T(e, r), s = n ? T(e, n.rates) : void 0;
132
+ return s && s.length >= (o?.length ?? -1) ? Math.min(s.rate, a) : o ? o.rate : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
133
+ }
134
+ function D(e, t, n) {
135
+ if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
136
+ let r = E(e.namespace, t, n);
137
+ return n && i[e.level] < i[t.minLevel] && (r = Math.min(r, t.sampling.remoteMaxRate)), r >= 1 ? !0 : r <= 0 ? !1 : C(e.journeyId || e.traceId) / s < r;
138
+ }
139
+ function O(e, t, n = null) {
140
+ return D({
141
+ level: e.severityText,
142
+ type: w(e, a),
143
+ namespace: w(e, o),
144
+ journeyId: w(e, r),
145
+ traceId: e.traceId
146
+ }, t, n);
147
+ }
148
+ var k = class {
149
+ windowStart = 0;
150
+ count = 0;
151
+ allow(e) {
152
+ if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
153
+ let t = Date.now();
154
+ return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
155
+ }
156
+ };
157
+ //#endregion
158
+ export { S as a, p as c, m as d, v as f, x as i, h as l, u as m, O as n, f as o, d as p, D as r, b as s, k as t, y as u };
159
+
160
+ //# sourceMappingURL=sampling-J1eahbfT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-J1eahbfT.js","names":["FNV_OFFSET_BASIS","FNV_PRIME","SESSION_ID_KEY","ATTR_JOURNEY_ID","LEVEL_ORDER","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","UINT32_MAX","TAB_ID_KEY","unrefTimer","nowUnixNano","isLogRecord","value","record","BROWSER_STORES","memoryStores","wrap","map","key","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","DeadlineError","ms","withDeadline","expire","deadline","timer","work","hash","h","readAttr","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/identity.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks whether a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns Whether `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. Otherwise it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. Otherwise each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record being evaluated.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies at once.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n if (remote && LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel]) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;;AAwDA,SAAgBU,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAMC,IAASD;CACf,OACE,OAAOC,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AC5BA,IAAaC,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKN,CAA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AAWA,EAAM,UAAU,WAI3CP,EAAO,SAAS,kBAAkB,SAASO,EAAM,IAAI,GACvD,OAAO;CAGT,IAAIX,IAAOG,EAAQQ,EAAM,WAAWP,GAAQG,CAAM;CAkBlD,OAfIA,KAAU1D,EAAY8D,EAAM,SAAqB9D,EAAYuD,EAAO,cACtE,IAAO,KAAK,IAAIJ,GAAMI,EAAO,SAAS,aAAa,IAGjDJ,KAAA,IACK,KAELA,KAAA,IACK,KAOFN,EAFKiB,EAAM,aAAaA,EAAM,OAEtB,IAAI3D,IAAagD;AAClC;AAUA,SAAgBY,EACd,GACA,GACA,IAA6B,MACpB;CACT,OAAOF,EACL;EACE,OAAOpD,EAAO;EACd,MAAMsC,EAAStC,GAAQR,CAAa;EACpC,WAAW8C,EAAStC,GAAQP,CAAkB;EAC9C,WAAW6C,EAAStC,GAAQV,CAAe;EAC3C,SAASU,EAAO;CAClB,GACA8C,GACAG,CACF;AACF;AAQA,IAAaM,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAIvD,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMqB,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-B28fDv2F.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.ot);function n(e){return t.run(e)}function r(){return t.open()}function i(e,t){if(e.length<=t)return e;let n=a(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function a(e){return e>=55296&&e<=56319}function o(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function s(e,t,n){return c(e,t,n).value}function c(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:u(e,t,new WeakSet,0,r),bytes:r.bytes}}function l(e,t){return t.bytes+=d(e)+2,e}function u(e,t,n,r,a){if(a.nodes++,a.nodes>t.maxNodes)return l(`[MaxNodes]`,a);if(e==null)return a.bytes+=4,e;if(typeof e==`string`)return l(i(e,t.maxAttributeChars),a);if(typeof e==`number`)return a.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return a.bytes+=5,e;if(typeof e==`bigint`)return l(`${e.toString()}n`,a);if(typeof e==`symbol`)return l(e.toString(),a);if(typeof e==`function`)return l(`[Function ${e.name===``?`anonymous`:e.name}]`,a);if(r>=t.maxDepth)return l(`[MaxDepth]`,a);if(n.has(e))return l(`[Circular]`,a);n.add(e),a.bytes+=2;try{if(e instanceof Error)return{name:l(e.name,a),message:l(i(e.message,t.maxAttributeChars),a),stack:e.stack?l(i(e.stack,t.maxStackChars),a):void 0,cause:e.cause?u(e.cause,t,n,r+1,a):void 0};if(e instanceof Date)return l(e.toISOString(),a);if(e instanceof RegExp)return l(e.toString(),a);if(e instanceof Map){let i=e,o={},s=0;for(let[e,c]of i){if(s>=t.maxArrayLength){o[`…`]=l(`[${String(i.size-t.maxArrayLength)} more entries]`,a);break}s++;let f=String(e);a.bytes+=d(f)+4,o[f]=u(c,t,n,r+1,a)}return o}if(e instanceof Set)return u([...e].slice(0,t.maxArrayLength),t,n,r,a);if(ArrayBuffer.isView(e)){let t=e.length??0;return l(`[${e.constructor.name}(${String(t)})]`,a)}if(e instanceof Promise)return l(`[Promise]`,a);if(typeof Node<`u`&&e instanceof Node)return l(o(e),a);if(Array.isArray(e)){let i=e,o=i.slice(0,t.maxArrayLength).map(e=>u(e,t,n,r+1,a));return i.length>t.maxArrayLength&&o.push(l(`[${String(i.length-t.maxArrayLength)} more items]`,a)),o}let s=e.toJSON;if(typeof s==`function`)return u(s.call(e),t,n,r+1,a);let c=e,f=Object.keys(c),p={},m=0;for(let e of f){if(m>=t.maxAttributeCount){p[`…`]=l(`[${String(f.length-m)} more keys]`,a);break}m++,a.bytes+=d(e)+4,p[e]=u(c[e],t,n,r+1,a)}return p}catch(e){return a.diagnostics.count(`record.sanitize_failed`),l(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,a)}finally{n.delete(e)}}function d(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return d}});
2
+ //# sourceMappingURL=sanitize-BMhh8ghJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize-BMhh8ghJ.cjs","names":["globalScope","LIBRARY_CONSOLE_KEY","set","toJson","require_constants","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","record","keys","count","error","bytes","i"],"sources":["../src/utils/library-console.ts","../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/library-console.ts\n//\n// Marks the console calls that the library makes itself. The console capture skips a call inside\n// this scope. Without the scope, the capture records each mirrored line again, and the loop does\n// not stop.\n\nimport { LIBRARY_CONSOLE_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library console calls. */\nconst scope = globalScope(LIBRARY_CONSOLE_KEY);\n\n/**\n * Runs a function inside the library console scope.\n * @param fn Function that writes to the console.\n * @returns The return value of the function.\n */\nexport function runAsLibraryConsole<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library console scope is open.\n * @returns True while the library writes to the console.\n */\nexport function isLibraryConsole(): boolean {\n return scope.open();\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. Otherwise a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":"4CAUA,IAAMK,uCAAQL,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAO7C,SAAgBK,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB,CCeA,SAAgBI,EAAS,EAAe,EAAqB,CAC3D,GAAIC,EAAM,QAAUC,EAClB,OAAOD,EAKT,IAAME,EAAMC,EAAgBH,EAAM,WAAWC,EAAM,CAAC,CAAC,EAAIA,EAAM,EAAIA,EACnE,MAAO,GAAGD,EAAM,MAAM,EAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,OAASE,CAAG,EAAE,QAC1E,CAOA,SAASC,EAAgB,EAAuB,CAC9C,OAAOC,GAAA,OAA8BA,GAAA,KACvC,CAcA,SAASC,EAAa,EAAwB,CAO5C,MAAO,aANMC,EAAK,UAAY,OAAA,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B,EAAM,YAAY,MAAM,wBAAwB,EAEzCE,EAAQ,oBADFkB,aAAiB,MAAQA,EAAM,KAAO,QACX,GAAIpB,CAAK,CACnD,QAAU,CAGRM,EAAK,OAAOjB,CAAK,CACnB,CACF,CAOA,SAAgBc,EAAc,EAAuB,CACnD,IAAIkB,EAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIjC,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWiC,CAAC,EAC3B7B,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO4B,CACT"}
@@ -0,0 +1,114 @@
1
+ import { ot as e } from "./constants-Bu49bm39.js";
2
+ import { t } from "./global-scope-dp2jADRl.js";
3
+ //#region src/utils/library-console.ts
4
+ var n = t(e);
5
+ function r(e) {
6
+ return n.run(e);
7
+ }
8
+ function i() {
9
+ return n.open();
10
+ }
11
+ //#endregion
12
+ //#region src/utils/sanitize.ts
13
+ function a(e, t) {
14
+ if (e.length <= t) return e;
15
+ let n = o(e.charCodeAt(t - 1)) ? t - 1 : t;
16
+ return `${e.slice(0, n)}… [truncated ${String(e.length - n)} chars]`;
17
+ }
18
+ function o(e) {
19
+ return e >= 55296 && e <= 56319;
20
+ }
21
+ function s(e) {
22
+ 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(".")}` : ""}]`;
23
+ }
24
+ function c(e, t, n) {
25
+ return l(e, t, n).value;
26
+ }
27
+ function l(e, t, n) {
28
+ let r = {
29
+ bytes: 0,
30
+ nodes: 0,
31
+ diagnostics: n
32
+ };
33
+ return {
34
+ value: d(e, t, /* @__PURE__ */ new WeakSet(), 0, r),
35
+ bytes: r.bytes
36
+ };
37
+ }
38
+ function u(e, t) {
39
+ return t.bytes += f(e) + 2, e;
40
+ }
41
+ function d(e, t, n, r, i) {
42
+ if (i.nodes++, i.nodes > t.maxNodes) return u("[MaxNodes]", i);
43
+ if (e == null) return i.bytes += 4, e;
44
+ if (typeof e == "string") return u(a(e, t.maxAttributeChars), i);
45
+ if (typeof e == "number") return i.bytes += 8, Number.isFinite(e) ? e : String(e);
46
+ if (typeof e == "boolean") return i.bytes += 5, e;
47
+ if (typeof e == "bigint") return u(`${e.toString()}n`, i);
48
+ if (typeof e == "symbol") return u(e.toString(), i);
49
+ if (typeof e == "function") return u(`[Function ${e.name === "" ? "anonymous" : e.name}]`, i);
50
+ if (r >= t.maxDepth) return u("[MaxDepth]", i);
51
+ if (n.has(e)) return u("[Circular]", i);
52
+ n.add(e), i.bytes += 2;
53
+ try {
54
+ if (e instanceof Error) return {
55
+ name: u(e.name, i),
56
+ message: u(a(e.message, t.maxAttributeChars), i),
57
+ stack: e.stack ? u(a(e.stack, t.maxStackChars), i) : void 0,
58
+ cause: e.cause ? d(e.cause, t, n, r + 1, i) : void 0
59
+ };
60
+ if (e instanceof Date) return u(e.toISOString(), i);
61
+ if (e instanceof RegExp) return u(e.toString(), i);
62
+ if (e instanceof Map) {
63
+ let a = e, o = {}, s = 0;
64
+ for (let [e, c] of a) {
65
+ if (s >= t.maxArrayLength) {
66
+ o["…"] = u(`[${String(a.size - t.maxArrayLength)} more entries]`, i);
67
+ break;
68
+ }
69
+ s++;
70
+ let l = String(e);
71
+ i.bytes += f(l) + 4, o[l] = d(c, t, n, r + 1, i);
72
+ }
73
+ return o;
74
+ }
75
+ if (e instanceof Set) return d([...e].slice(0, t.maxArrayLength), t, n, r, i);
76
+ if (ArrayBuffer.isView(e)) {
77
+ let t = e.length ?? 0;
78
+ return u(`[${e.constructor.name}(${String(t)})]`, i);
79
+ }
80
+ if (e instanceof Promise) return u("[Promise]", i);
81
+ if (typeof Node < "u" && e instanceof Node) return u(s(e), i);
82
+ if (Array.isArray(e)) {
83
+ let a = e, o = a.slice(0, t.maxArrayLength).map((e) => d(e, t, n, r + 1, i));
84
+ return a.length > t.maxArrayLength && o.push(u(`[${String(a.length - t.maxArrayLength)} more items]`, i)), o;
85
+ }
86
+ let o = e.toJSON;
87
+ if (typeof o == "function") return d(o.call(e), t, n, r + 1, i);
88
+ let c = e, l = Object.keys(c), p = {}, m = 0;
89
+ for (let e of l) {
90
+ if (m >= t.maxAttributeCount) {
91
+ p["…"] = u(`[${String(l.length - m)} more keys]`, i);
92
+ break;
93
+ }
94
+ m++, i.bytes += f(e) + 4, p[e] = d(c[e], t, n, r + 1, i);
95
+ }
96
+ return p;
97
+ } catch (e) {
98
+ return i.diagnostics.count("record.sanitize_failed"), u(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
99
+ } finally {
100
+ n.delete(e);
101
+ }
102
+ }
103
+ function f(e) {
104
+ let t = 0;
105
+ for (let n = 0; n < e.length; n++) {
106
+ let r = e.charCodeAt(n);
107
+ r < 128 ? t += 1 : r < 2048 ? t += 2 : r >= 55296 && r <= 56319 ? (t += 4, n++) : t += 3;
108
+ }
109
+ return t;
110
+ }
111
+ //#endregion
112
+ export { i as a, a as i, c as n, r as o, l as r, f as t };
113
+
114
+ //# sourceMappingURL=sanitize-UJ-4Lb0n.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize-UJ-4Lb0n.js","names":["set","toJson","LIBRARY_CONSOLE_KEY","scope","globalScope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","record","keys","count","error","bytes","i"],"sources":["../src/utils/library-console.ts","../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/library-console.ts\n//\n// Marks the console calls that the library makes itself. The console capture skips a call inside\n// this scope. Without the scope, the capture records each mirrored line again, and the loop does\n// not stop.\n\nimport { LIBRARY_CONSOLE_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library console calls. */\nconst scope = globalScope(LIBRARY_CONSOLE_KEY);\n\n/**\n * Runs a function inside the library console scope.\n * @param fn Function that writes to the console.\n * @returns The return value of the function.\n */\nexport function runAsLibraryConsole<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library console scope is open.\n * @returns True while the library writes to the console.\n */\nexport function isLibraryConsole(): boolean {\n return scope.open();\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. Otherwise a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":";;;AAUA,IAAMG,IAAQC,EAAYF,CAAmB;AAO7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB;;;ACeA,SAAgBK,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,EAA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FA,KACA,EAAM,SAASG,EAAcO,CAAG,IAAA,GAChC,EAAIA,KAAOT,EAAKgB,EAAOP,IAAMZ,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAC7D;EACA,OAAOQ;CACT,SAASY,GAAO;EAKd,OAFApB,EAAM,YAAY,MAAM,wBAAwB,GAEzCE,EAAQ,oBADFkB,aAAiB,QAAQA,EAAM,OAAO,QACX,IAAIpB,CAAK;CACnD,UAAU;EAGR,EAAK,OAAOX,CAAK;CACnB;AACF;AAOA,SAAgBc,EAAc,GAAuB;CACnD,IAAIkB,IAAQ;CACZ,KAAK,IAAIC,IAAI,GAAGA,IAAIjC,EAAM,QAAQ,KAAK;EACrC,IAAMI,IAAOJ,EAAM,WAAWiC,CAAC;EAC/B,AAAI7B,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAO4B;AACT"}
@@ -0,0 +1,3 @@
1
+ const e=require("./constants-B28fDv2F.cjs"),t=require("./sampling-E4x92Nn2.cjs"),n=require("./sanitize-BMhh8ghJ.cjs"),r=require("./unref-CU9Nyz_9.cjs"),i=require("./remote-rules-rJJZKVG8.cjs"),a=require("./library-request-Br_T09Bn.cjs");function o(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function s(e,n){if(e.records.length<2)return null;let r=Math.floor(e.records.length/2),i=r=>({id:t.l(n),records:r,createdAt:e.createdAt,attempts:e.attempts});return[i(e.records.slice(0,r)),i(e.records.slice(r))]}function c(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 l(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 u(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.R}${n}.${t.id}`}function d(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:o(n)?n:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function f(n,r){let i=0;for(let a of l(e.R,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=d(o,r);if(s!==null)try{await t.a(n.save(s),e.$t),i++}catch(e){r.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:a},e)}}return i}function p(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=l(e.R,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(u(t),JSON.stringify(t))})}async function m(e,t){return await c(`ui-observability.emergency`,t,()=>f(e,t),{skipIfBusy:!1})??0}function h(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}function g(t){let n=e.v.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var _=class{limits;diagnostics;onGap;name=e.rn;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){this.write(e,`localStorage refused a batch, evicting the oldest`)?await this.prune():(this.evictForQuota(),this.write(e,`localStorage refused a batch even after evicting`)||this.reportGap({batches:1,records:e.records.length,reason:`quota`}))}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=e=>{let n=this.read(e);this.removeKey(e),t.batches++,t.records+=n?.records.length??0},r=[];for(let t of this.keys()){let i=g(t);i===null||i<e?n(t):r.push(t)}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e)}return this.reportGap(t),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(h(e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`};for(let n of e.slice(0,Math.ceil(e.length/4))){let e=this.read(n);this.removeKey(n),t.batches++,t.records+=e?.records.length??0}this.reportGap(t)}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`The library dropped ${String(e.batches)} stored batches (${String(e.records)} records).`,{...e}),this.onGap?.(e))}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:o(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 l(e.v,this.diagnostics)}};function v(e){return e.reduce((e,t)=>e+t.records.length,0)}var y=class{limits;onGap;name=e.in;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),t.batches+=n.length,t.records+=v(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=v(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},b={name:e.an,save:()=>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 x(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function S(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e.on,`1`),localStorage.removeItem(e.on),!0))===!0}async function C(e,t,n,r,i){if(e===`none`)return b;if(e===`memory`)return new y(n,i);if(e===`indexeddb`||e===`auto`){if(x(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-D0p3iMD0.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 y(n,i)}return S(r)?new _(n,r,i):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new y(n,i))}var w=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 T(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.pt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function E(t){return e.ht.test(t)?Number(BigInt(t)/e.gt):Date.now()}function D(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function O(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function k(e,t,n,r){let i=D(n);if(i!==null)O(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)k(e,t,i,r);else for(let[i,a]of Object.entries(n))k(e,`${t}.${i}`,a,r);r.delete(n)}}function A(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))k(t,r,i,n);return t}var j={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=E(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:e.I[t.severityText]??t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Pt],version:t.resource[e.Ft],environment:t.resource[e.At]},user_agent:{original:t.resource[e.Ot]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...A(t.resource),...A(t.attributes)}})}).join(`
2
+ `)}\n`,contentType:e.k}}};function M(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(M).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:N(e)}}:null}function N(e){let t=[];for(let[n,r]of Object.entries(e)){let e=M(r);e&&t.push({key:n,value:e})}return t}var P=new WeakMap;function F(e){let t=P.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return P.set(e,n),n}var I={name:e.qt,serialize(t){let n=new Map;for(let e of t){let t=F(e.resource),r=n.get(t);r?r.records.push(e):n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:N(t.resource)},scopeLogs:[{scope:{name:e.ln,version:e.un},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:N(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.O}}};function L(e){return e===`otlp`?I:e===`ecs`?j:e}function R(e,t,n,r){try{return L(e).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var z=class{config;diagnostics;onSampling;throttledUntil=0;constructor(e,t,n=()=>void 0){this.config=e,this.diagnostics=t,this.onSampling=n}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}serialize(e){return R(this.config.serializer,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`)}accept(e){this.throttledUntil=0,this.config.sampling.remote&&e!=null&&this.onSampling(e)}reject(e,t,n){let r=String(e);if(e===401||e===403){let t=n.advice===void 0?``:` ${n.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${r}.${t}`,{status:e,endpoint:this.config.endpoint}),new w(`permanent`,`The server rejected the batch with ${r}.`,e)}if(e===413)return new w(`too_large`,`The payload is too large.`,e,void 0,n.maxBytes);if(e===429||e===503){let t=e===429;return this.throttledUntil=Date.now()+(n.retryAfterMs??2e3),t&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:n.retryAfterMs}),new w(`throttled`,t?`The server throttles the requests.`:`The service is not available.`,e,n.retryAfterMs)}return e===408||e>=500?new w(`transient`,`The server returned the error ${r}.`,e):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${r}. The library dropped it.`,{batchId:t,status:e}),new w(`permanent`,`The server rejected the batch with ${r}.`,e))}};function B(e,t){return{body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records}}function V(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 H(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var U=class extends z{async send(r){let{transport:i}=this.config;if(!i||r.records.length===0)return;let o=this.serialize(r);if(!o)return;let s=B(r,o),c;try{c=await t.a(a.n(()=>n.o(()=>i(s))),e.Dt)}catch(e){let n=e instanceof t.i?e:void 0;throw new w(n?`timeout`:`transient`,n?.message??`The custom transport failed.`,void 0,void 0,void 0,e)}if(!V(c))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:r.id}),new w(`transient`,`The custom transport returned no valid status.`);let{status:l}=c;if(l>=200&&l<300)this.accept(c.sampling);else throw this.reject(l,r.id,{retryAfterMs:H(c.retryAfterMs),maxBytes:H(c.maxBytes)})}},W=class{deps;installed=!1;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=globalThis.fin?.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=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(t){let{config:r,diagnostics:i}=this.deps;if(r.transport){this.flushCustom(t,r.transportOnExit);return}let a=this.endpointUrl();if(a===null)return;let o=this.drain(t);if(!o||o.records.length===0)return;let s=this.serialize(o,t);if(!s)return;if(n.t(s.body)>6e4){p(o,i);return}a.searchParams.set(e.bt,o.id),a.searchParams.set(e.xt,t);let c=a.toString(),l=this.beacon(c,s.body);l!==`sent`&&(l===`refused`?p(o,i):this.keepaliveFetch(c,s.body,t))}flushCustom(e,t){let{diagnostics:n}=this.deps;if(e===`hidden`&&!t)return;let r=this.drain(e);if(!r||r.records.length===0)return;let i=this.serialize(r,e);i&&(t===void 0||n.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>a.n(()=>t(B(r,i))))!==!0)&&p(r,n)}serialize(e,t){return R(this.deps.config.serializer,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`)}drain(e){return e===`hidden`?this.deps.drainPending():this.deps.drainForExit()}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(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`The keepalive fetch fallback failed.`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.J]:e.A},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`The exit flush failed.`,{reason:r},e)})})}};async function G(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.z)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var K=`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.`,q=class extends z{async send(e){let{endpoint:t}=this.config;t&&e.records.length!==0&&await this.post(e,t)}async post(t,n){let r=this.serialize(t);if(!r)return;let i=new Headers(await this.resolveHeaders());i.set(e.J,r.contentType),i.set(e.K,t.id),i.set(e.G,String(t.attempts));let a=await this.encodeBody(r.body);typeof a!=`string`&&i.set(e.q,e.z);let o=await this.dispatch(n,i,a);if(o.ok){this.accept(o.headers.get(e.X));return}let s=o.status,c=T(o.headers.get(e.Y)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,{retryAfterMs:c,maxBytes:l,advice:K})}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||n.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>G(e))??e}async dispatch(t,n,i){let{config:o}=this,s=new AbortController,c=setTimeout(()=>{s.abort()},e.Dt);r.t(c);try{return await a.n(()=>fetch(t,{method:`POST`,headers:n,body:i,credentials:o.credentials,signal:s.signal,cache:`no-store`}))}catch{if(s.signal.aborted)throw new w(`timeout`,`The request took longer than ${String(e.Dt)} ms.`);let t=globalThis.navigator?.onLine;throw new w(t===!1?`offline`:`transient`,`A network error occurred.`)}finally{clearTimeout(c)}}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;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()))??{}:e:{}}},J=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.Ht)}nudge(){this.draining||this.schedule(e.Vt)}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 t=setTimeout(()=>{this.drain()},e);this.timer=t,r.t(t)}bounded(n){return t.a(n,e.$t)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Vt*2**this.attempt,e.Ut);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await c(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.Ht)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(e.Ht),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.Ht),!0;for(let e of t)if(this.stopped||!await this.deliver(e))return!0;return this.schedule(t.length===this.batchesPerDrain?0:e.Ht),!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>=e.en.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}),await this.bounded(this.storage.remove(t.id)),!0;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,!0}catch(n){let r=n instanceof w?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),!0):r?.kind===`offline`?(this.schedule(e.Ht),!1):r?.kind===`throttled`?(this.attempt++,this.schedule(r.retryAfterMs??this.backoffMs()),!1):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,this.schedule(r?.retryAfterMs??this.backoffMs()),!1)}}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 w?t:void 0;if(n?.kind===`permanent`)return[];if(n?.kind!==`too_large`)return[e];let r=s(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)}),[])}};function Y(t){return t.attributes[e.l]===e.ut}var X={logs:{flushIntervalMs:e.lt,batchSize:100},metrics:{flushIntervalMs:e.ft,batchSize:500}},Z=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}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,r.t(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},Q=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i=X){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new Z(i.logs,a),metrics:new Z(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=t.m(),this.route(e))}drainPending(){return this.toBatch([...this.streams.metrics.take(),...this.streams.logs.take()])}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.toBatch([...e,...this.streams.metrics.take(),...this.streams.logs.take()])}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.stop(),this.queue.length=0}toBatch(e){return e.length===0?null:{id:t.l(this.diagnostics),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=Y(e)?this.streams.metrics:this.streams.logs;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){let n=e.take(),r={id:t.l(this.diagnostics),records:n,createdAt:Date.now(),attempts:0};this.unconfirmed.set(r.id,r),this.enqueue(r)}enqueue(e){this.queue.push(e),!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){try{await this.dispatch(e)}catch(t){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:e.id},t)}finally{this.inFlight--,this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs();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)}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.a(this.storage.save(n),e.$t),this.retry.nudge()})}},$=class t{storage;transport;retry;pipeline;exitFlush;diagnostics;constructor(e,t,n,r,i,a){this.storage=e,this.transport=t,this.retry=n,this.pipeline=r,this.exitFlush=i,this.diagnostics=a}static async create(n){let{config:r,diagnostics:a}=n,o=await C(r.storage,e.Qt,e.en,a,n.onGap),s=e=>{let t=i.n(e,a);t&&i.t(n.remote,r,t)},c=r.transport?new U(r,a,s):new q(r,a,s),l=new J(o,c,a,r),u=new Q(c,o,l,a),d=new W({config:r,diagnostics:a,drainForExit:()=>u.drainForExit(),drainPending:()=>u.drainPending()});await m(o,a);let f=!1;try{d.install(),l.start(),f=!0}finally{f||(d.uninstall(),l.stop())}return new t(o,c,l,u,d,a)}push(e){this.pipeline.push(e)}async flush(){let e=this.pipeline.drainPending();if(e)try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store the batch that flush() drained.`,async()=>{await this.retry.storeFailed({...e,attempts:e.attempts+1},t)}),this.diagnostics.report(`transport.http_error`,`The send from flush() failed. The library stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}async destroy(){this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}};exports.Sender=$;
3
+ //# sourceMappingURL=sender-B6ufz26f.cjs.map