@utk09/ui-observability 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -219
- package/README.md +24 -26
- package/dist/{batch-CXmPmTse.js → batch-D3NHhF9L.js} +3 -3
- package/dist/{batch-CXmPmTse.js.map → batch-D3NHhF9L.js.map} +1 -1
- package/dist/{batch-mmPigCpi.cjs → batch-DnYRJqhU.cjs} +2 -2
- package/dist/{batch-mmPigCpi.cjs.map → batch-DnYRJqhU.cjs.map} +1 -1
- package/dist/bus/bus.d.cts +26 -2
- package/dist/bus/bus.d.ts +26 -2
- package/dist/bus-B__467mL.cjs +2 -0
- package/dist/bus-B__467mL.cjs.map +1 -0
- package/dist/{bus-C39wspFV.js → bus-dw7T92sO.js} +37 -24
- package/dist/bus-dw7T92sO.js.map +1 -0
- package/dist/capture/interactions.d.cts +35 -3
- package/dist/capture/interactions.d.ts +35 -3
- package/dist/capture/observed-windows.d.cts +51 -0
- package/dist/capture/observed-windows.d.ts +51 -0
- package/dist/{compression-CvED_Jel.cjs → compression-C0hUHKR-.cjs} +2 -2
- package/dist/{compression-CvED_Jel.cjs.map → compression-C0hUHKR-.cjs.map} +1 -1
- package/dist/{compression-tVtXwVjX.js → compression-SHPAvS4U.js} +2 -2
- package/dist/{compression-tVtXwVjX.js.map → compression-SHPAvS4U.js.map} +1 -1
- package/dist/{config-SgQcCP1_.js → config-CSNcS7OZ.js} +194 -196
- package/dist/config-CSNcS7OZ.js.map +1 -0
- package/dist/config-CybPP5VM.cjs +2 -0
- package/dist/config-CybPP5VM.cjs.map +1 -0
- package/dist/{console-BGgGnjSi.js → console-BsM-fSCQ.js} +4 -4
- package/dist/{console-BGgGnjSi.js.map → console-BsM-fSCQ.js.map} +1 -1
- package/dist/{console-CSZ5_Vx5.cjs → console-Dkxs6IVQ.cjs} +2 -2
- package/dist/{console-CSZ5_Vx5.cjs.map → console-Dkxs6IVQ.cjs.map} +1 -1
- package/dist/{constants-CUyd9cTZ.js → constants-BwJDXzj6.js} +23 -23
- package/dist/constants-BwJDXzj6.js.map +1 -0
- package/dist/constants-CtF52hIV.cjs +2 -0
- package/dist/constants-CtF52hIV.cjs.map +1 -0
- package/dist/constants.d.cts +12 -0
- package/dist/constants.d.ts +12 -0
- package/dist/core/diagnostics.d.cts +1 -1
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/rotation.d.cts +26 -2
- package/dist/core/rotation.d.ts +26 -2
- package/dist/core/runtime.d.cts +9 -0
- package/dist/core/runtime.d.ts +9 -0
- package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-B2v6Cym-.cjs} +2 -2
- package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-B2v6Cym-.cjs.map} +1 -1
- package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-Cs_YWzTa.js} +4 -4
- package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-Cs_YWzTa.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.js +31 -31
- package/dist/doctor.js.map +1 -1
- package/dist/{errors-CNPbesMs.cjs → errors-DP2RUm4V.cjs} +2 -2
- package/dist/{errors-CNPbesMs.cjs.map → errors-DP2RUm4V.cjs.map} +1 -1
- package/dist/{errors-BE_EZV7Q.js → errors-Q3Ng1ciC.js} +3 -3
- package/dist/{errors-BE_EZV7Q.js.map → errors-Q3Ng1ciC.js.map} +1 -1
- package/dist/{factory-CTi0Is3F.js → factory-DV17sm2p.js} +22 -22
- package/dist/{factory-CTi0Is3F.js.map → factory-DV17sm2p.js.map} +1 -1
- package/dist/{factory-hRrH32v5.cjs → factory-K8O6gpux.cjs} +2 -2
- package/dist/{factory-hRrH32v5.cjs.map → factory-K8O6gpux.cjs.map} +1 -1
- package/dist/{identity-DdhKgrpk.js → identity-BgtHyY4u.js} +38 -27
- package/dist/identity-BgtHyY4u.js.map +1 -0
- package/dist/identity-CvuyqZk7.cjs +2 -0
- package/dist/identity-CvuyqZk7.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +600 -569
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-D4KVcqdD.cjs} +2 -2
- package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-D4KVcqdD.cjs.map} +1 -1
- package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-e-13ZLWm.js} +17 -17
- package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-e-13ZLWm.js.map} +1 -1
- package/dist/interactions-Byxf1C82.js +207 -0
- package/dist/interactions-Byxf1C82.js.map +1 -0
- package/dist/interactions-OK85T-Dk.cjs +2 -0
- package/dist/interactions-OK85T-Dk.cjs.map +1 -0
- package/dist/{journey-D2_sia57.js → journey-C93FTYcs.js} +14 -14
- package/dist/{journey-D2_sia57.js.map → journey-C93FTYcs.js.map} +1 -1
- package/dist/{journey-B4Adltjm.cjs → journey-nMbob3OB.cjs} +2 -2
- package/dist/{journey-B4Adltjm.cjs.map → journey-nMbob3OB.cjs.map} +1 -1
- package/dist/{library-console-CPW6bvZH.cjs → library-console-DJUQzcgM.cjs} +2 -2
- package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DJUQzcgM.cjs.map} +1 -1
- package/dist/{library-console-Btrzt814.js → library-console-DklSmucS.js} +2 -2
- package/dist/{library-console-Btrzt814.js.map → library-console-DklSmucS.js.map} +1 -1
- package/dist/{library-request-BJ9PLRaD.js → library-request-UGEwOHpf.js} +2 -2
- package/dist/{library-request-BJ9PLRaD.js.map → library-request-UGEwOHpf.js.map} +1 -1
- package/dist/{library-request-D7OvTxZV.cjs → library-request-kY9iTpIF.cjs} +2 -2
- package/dist/{library-request-D7OvTxZV.cjs.map → library-request-kY9iTpIF.cjs.map} +1 -1
- package/dist/{lifecycle-22CUCrc9.js → lifecycle-B2PlIuQu.js} +2 -2
- package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-B2PlIuQu.js.map} +1 -1
- package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-DaMdH_X7.cjs} +2 -2
- package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-DaMdH_X7.cjs.map} +1 -1
- package/dist/{log-record-CkivuiEl.cjs → log-record-Bmx6etMh.cjs} +2 -2
- package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bmx6etMh.cjs.map} +1 -1
- package/dist/{log-record-BNiLfqtL.js → log-record-DSt2P-Sr.js} +2 -2
- package/dist/{log-record-BNiLfqtL.js.map → log-record-DSt2P-Sr.js.map} +1 -1
- package/dist/{long-frames-DNFaRnC3.js → long-frames-Bamjs1WV.js} +3 -3
- package/dist/{long-frames-DNFaRnC3.js.map → long-frames-Bamjs1WV.js.map} +1 -1
- package/dist/{long-frames-BUUbXd-B.cjs → long-frames-lhtONgGt.cjs} +2 -2
- package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-lhtONgGt.cjs.map} +1 -1
- package/dist/models/bus.d.cts +6 -1
- package/dist/models/bus.d.ts +6 -1
- package/dist/models/config.d.cts +23 -8
- package/dist/models/config.d.ts +23 -8
- package/dist/models/serializer.d.cts +3 -1
- package/dist/models/serializer.d.ts +3 -1
- package/dist/{network-CGMLQ-mA.cjs → network-BCn8Gn47.cjs} +2 -2
- package/dist/{network-CGMLQ-mA.cjs.map → network-BCn8Gn47.cjs.map} +1 -1
- package/dist/{network-on2zZT6H.js → network-Cg1L2w2r.js} +12 -12
- package/dist/{network-on2zZT6H.js.map → network-Cg1L2w2r.js.map} +1 -1
- package/dist/observed-windows-B3gJkdql.cjs +2 -0
- package/dist/observed-windows-B3gJkdql.cjs.map +1 -0
- package/dist/observed-windows-BrwaJNlj.js +64 -0
- package/dist/observed-windows-BrwaJNlj.js.map +1 -0
- package/dist/{otlp-BENHf3g9.cjs → otlp-CrAWkQdO.cjs} +2 -2
- package/dist/{otlp-BENHf3g9.cjs.map → otlp-CrAWkQdO.cjs.map} +1 -1
- package/dist/{otlp-DimfrRor.js → otlp-D6dRZyB8.js} +6 -6
- package/dist/{otlp-DimfrRor.js.map → otlp-D6dRZyB8.js.map} +1 -1
- package/dist/{platform-BaaFIPCU.js → platform-8DLhjddo.js} +7 -7
- package/dist/{platform-BaaFIPCU.js.map → platform-8DLhjddo.js.map} +1 -1
- package/dist/{platform-CfA3-7sJ.cjs → platform-BqRc-7RO.cjs} +2 -2
- package/dist/{platform-CfA3-7sJ.cjs.map → platform-BqRc-7RO.cjs.map} +1 -1
- package/dist/{profiler-BAZoh7A4.js → profiler-BaXSqCfz.js} +59 -59
- package/dist/{profiler-BAZoh7A4.js.map → profiler-BaXSqCfz.js.map} +1 -1
- package/dist/{profiler-D4tJpDRc.cjs → profiler-BvWW2kNM.cjs} +2 -2
- package/dist/{profiler-D4tJpDRc.cjs.map → profiler-BvWW2kNM.cjs.map} +1 -1
- package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-C4ySHN0X.js} +16 -16
- package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-C4ySHN0X.js.map} +1 -1
- package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-DeaBiB-5.cjs} +2 -2
- package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-DeaBiB-5.cjs.map} +1 -1
- package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-D7L6D_D2.cjs} +2 -2
- package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-D7L6D_D2.cjs.map} +1 -1
- package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-Dq9xe7Qn.js} +22 -22
- package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-Dq9xe7Qn.js.map} +1 -1
- package/dist/{replay-Ds-ANH34.js → replay-B0M8kWz_.js} +24 -24
- package/dist/{replay-Ds-ANH34.js.map → replay-B0M8kWz_.js.map} +1 -1
- package/dist/{replay-B3gFXIZd.cjs → replay-QOFBpAXh.cjs} +2 -2
- package/dist/{replay-B3gFXIZd.cjs.map → replay-QOFBpAXh.cjs.map} +1 -1
- package/dist/{reports-C-thq-bk.js → reports--8APRLa-.js} +3 -3
- package/dist/{reports-C-thq-bk.js.map → reports--8APRLa-.js.map} +1 -1
- package/dist/{reports-BDSe4dFH.cjs → reports-ojuMKGO7.cjs} +2 -2
- package/dist/{reports-BDSe4dFH.cjs.map → reports-ojuMKGO7.cjs.map} +1 -1
- package/dist/{resource-timing-eUl2dNgC.js → resource-timing-BzR05rE-.js} +4 -4
- package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-BzR05rE-.js.map} +1 -1
- package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-pAG3ZhB5.cjs} +2 -2
- package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-pAG3ZhB5.cjs.map} +1 -1
- package/dist/{response-body-eoSQpLiH.js → response-body-BWvwKQ2p.js} +106 -106
- package/dist/{response-body-eoSQpLiH.js.map → response-body-BWvwKQ2p.js.map} +1 -1
- package/dist/{response-body-YdNl-HkR.cjs → response-body-CKEJ5itk.cjs} +3 -3
- package/dist/{response-body-YdNl-HkR.cjs.map → response-body-CKEJ5itk.cjs.map} +1 -1
- package/dist/{rotation-Cwct4ckk.js → rotation-BylN1B9e.js} +10 -11
- package/dist/rotation-BylN1B9e.js.map +1 -0
- package/dist/rotation-E2eKClIs.cjs +2 -0
- package/dist/rotation-E2eKClIs.cjs.map +1 -0
- package/dist/{sampling-mXt4dstx.cjs → sampling-B46LW0cy.cjs} +2 -2
- package/dist/{sampling-mXt4dstx.cjs.map → sampling-B46LW0cy.cjs.map} +1 -1
- package/dist/{sampling-BlrI8jor.js → sampling-zXA6r-Nw.js} +16 -16
- package/dist/{sampling-BlrI8jor.js.map → sampling-zXA6r-Nw.js.map} +1 -1
- package/dist/{sanitize-Ba0KqU06.js → sanitize-DjnR6RXR.js} +2 -2
- package/dist/{sanitize-Ba0KqU06.js.map → sanitize-DjnR6RXR.js.map} +1 -1
- package/dist/{sanitize-DQyiI_KY.cjs → sanitize-Qj6LuZqp.cjs} +2 -2
- package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-Qj6LuZqp.cjs.map} +1 -1
- package/dist/{sender-Dv8rAmpV.js → sender-Bdp-TAS4.js} +71 -71
- package/dist/{sender-Dv8rAmpV.js.map → sender-Bdp-TAS4.js.map} +1 -1
- package/dist/{sender-BdRuNVhF.cjs → sender-DR7ZycZY.cjs} +2 -2
- package/dist/{sender-BdRuNVhF.cjs.map → sender-DR7ZycZY.cjs.map} +1 -1
- package/dist/{stored-context-CXt7eHZL.cjs → stored-context-BOu54M8Y.cjs} +2 -2
- package/dist/{stored-context-CXt7eHZL.cjs.map → stored-context-BOu54M8Y.cjs.map} +1 -1
- package/dist/{stored-context-B2EzVuYm.js → stored-context-CSttrAsw.js} +6 -6
- package/dist/{stored-context-B2EzVuYm.js.map → stored-context-CSttrAsw.js.map} +1 -1
- package/dist/{storm-C-zYSdDX.cjs → storm-BHgI12iS.cjs} +2 -2
- package/dist/{storm-C-zYSdDX.cjs.map → storm-BHgI12iS.cjs.map} +1 -1
- package/dist/{storm-DjKetLKZ.js → storm-DKlpv0FL.js} +2 -2
- package/dist/{storm-DjKetLKZ.js.map → storm-DKlpv0FL.js.map} +1 -1
- package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-BYPYYkQ5.cjs} +2 -2
- package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-BYPYYkQ5.cjs.map} +1 -1
- package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-BcOB8A2e.js} +2 -2
- package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-BcOB8A2e.js.map} +1 -1
- package/dist/{user-timing-BePqb1uN.js → user-timing-4KIJ74Vi.js} +2 -2
- package/dist/{user-timing-BePqb1uN.js.map → user-timing-4KIJ74Vi.js.map} +1 -1
- package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BsU2wQKE.cjs} +2 -2
- package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BsU2wQKE.cjs.map} +1 -1
- package/dist/utils/identity.d.cts +5 -0
- package/dist/utils/identity.d.ts +5 -0
- package/dist/{web-socket-CoIUBM3C.cjs → web-socket-Cs1ZbmmN.cjs} +2 -2
- package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-Cs1ZbmmN.cjs.map} +1 -1
- package/dist/{web-socket-DSHgDiZ6.js → web-socket-Zg0hj1LB.js} +4 -4
- package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-Zg0hj1LB.js.map} +1 -1
- package/dist/{worker-protocol-x074Rpet.js → worker-protocol-CYpAbrVl.js} +4 -4
- package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-CYpAbrVl.js.map} +1 -1
- package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-DFYXIFus.cjs} +2 -2
- package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-DFYXIFus.cjs.map} +1 -1
- package/dist/{worker-server-CFe4nvos.cjs → worker-server--yGTadTA.cjs} +2 -2
- package/dist/{worker-server-CFe4nvos.cjs.map → worker-server--yGTadTA.cjs.map} +1 -1
- package/dist/{worker-server-iUVSjH8L.js → worker-server-BokySIII.js} +25 -25
- package/dist/{worker-server-iUVSjH8L.js.map → worker-server-BokySIII.js.map} +1 -1
- package/dist/worker-transport-BdEvh_-a.cjs +2 -0
- package/dist/worker-transport-BdEvh_-a.cjs.map +1 -0
- package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-JK-Fby9J.js} +23 -19
- package/dist/worker-transport-JK-Fby9J.js.map +1 -0
- package/llms.txt +13 -10
- package/package.json +13 -5
- package/dist/bus-C39wspFV.js.map +0 -1
- package/dist/bus-_EaOVPGq.cjs +0 -2
- package/dist/bus-_EaOVPGq.cjs.map +0 -1
- package/dist/config-DUs7uHHt.cjs +0 -2
- package/dist/config-DUs7uHHt.cjs.map +0 -1
- package/dist/config-SgQcCP1_.js.map +0 -1
- package/dist/constants-CUyd9cTZ.js.map +0 -1
- package/dist/constants-CqdJhTxH.cjs +0 -2
- package/dist/constants-CqdJhTxH.cjs.map +0 -1
- package/dist/identity-DdhKgrpk.js.map +0 -1
- package/dist/identity-DlWRIuwy.cjs +0 -2
- package/dist/identity-DlWRIuwy.cjs.map +0 -1
- package/dist/interactions-CUkzK8sR.cjs +0 -2
- package/dist/interactions-CUkzK8sR.cjs.map +0 -1
- package/dist/interactions-DiFvCosX.js +0 -111
- package/dist/interactions-DiFvCosX.js.map +0 -1
- package/dist/rotation-Cwct4ckk.js.map +0 -1
- package/dist/rotation-D4qUAHAu.cjs +0 -2
- package/dist/rotation-D4qUAHAu.cjs.map +0 -1
- package/dist/worker-transport-CRAX-09c.cjs +0 -2
- package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
- package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rotation-BylN1B9e.js","names":["ROUTING_KEYS","ROUTING_RESET","newId","resolveEndpoint","resolveDestination","applyResolvedConfig","resolveConfig","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","validOptions","isObject","update","pending","timeoutMs","planRotation","host","options","previous","runtime","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","clearStored","keepStored","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Runs the plan and holds the diagnostic records it raises until endRotation(), because the\n * logger drops every call during a rotation and these records belong to the next context.\n * @param plan Checks the next context's settings. It's synchronous, so nothing else is held.\n * @returns The plan's result.\n */\n holdRecords(plan: () => RotationPlan): RotationPlan;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again and writes the held diagnostic records. If a later rotation\n * waits, records stay blocked and the held ones are dropped, because they describe this context.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * It stays synchronous, because holdRecords() holds only what runs before the plan returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It throws for a setting it can't apply.\n */\nfunction planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): RotationPlan {\n const { runtime } = host;\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n plan = host.holdRecords(() => planRotation(host, update, options));\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n\n // shutdown() ran during the new sender's load, and that load stopped itself. Carry's live\n // records aren't routed yet, so they're lost. The other rules reported or stored theirs above.\n if (runtime.isDestroyed()) {\n if (rule === \"carry\") {\n host.drop(live);\n // The id is already the new one, so only these ids let a clearStorage find the old batches.\n await host.adopt(stored);\n }\n throw new Error(\"The runtime has stopped.\");\n }\n\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":";;;;;;AA2BA,IAAMO,IAAmC;CAAC;CAAW;CAAS;CAAU;AAAO,GAGzEC,IAAU,OAAO,SAAS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,QAAQ,MAAM,GAElBuB,KACFvB,EAAQ,QAAQ,MAAMuB,CAAO,GAG/BvB,EAAQ,YAAY,MAAM,GAC1BA,EAAQ,WAAW,GACnBA,EAAQ,QAAQ,mBAAmB,GACnC,MAAMH,EAAK,aAAa,GAIpBG,EAAQ,YAAY,GAMtB,MALIG,MAAS,YACXN,EAAK,KAAKQ,CAAI,GAEd,MAAMR,EAAK,MAAMS,CAAM,IAEf,MAAM,0BAA0B;CAO5C,IAFAT,EAAK,YAAY2B,CAAG,GAEhB9B,MAAY,SAAS;EACvB,KAAK,IAAM+B,KAAUpB,GACnB,EAAK,MAAMoB,CAAM;EAInB,MAAM5B,EAAK,MAAMS,CAAM;CACzB;CAEA,EAAQ,YAAY,OAAO,oBAAoB,6CAA6C,EAC1F,WACF,CAAC;AACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-CtF52hIV.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./identity-CvuyqZk7.cjs"),r=require("./config-CybPP5VM.cjs"),i=require("./stored-context-BOu54M8Y.cjs");var a=[`discard`,`flush`,`retain`,`carry`],o=Symbol(`refused`);function s(t,n,i){return e.Nn.filter(e=>{let a=t[e],s=n[e];return a===void 0?!1:e===`endpoint`?r.a(a,o,i)!==s:e===`metricsEndpoint`||e===`tracesEndpoint`?r.i(e,a,o,i)!==s:a===null?s!==void 0:s!==a})}function c(t,n){let r={...e.Pn};for(let i of Object.keys(t))if(e.Nn.includes(i)){let e=Reflect.get(t,i);Object.assign(r,{[i]:e})}else n.diagnostics.report(`config.invalid`,`rotateSecurityContext() ignores routing.${i}. A rotation changes only the routing settings.`);return r}function l(e,n,r){return t.n(e)&&t.n(e.routing)&&t.n(e.context??{})&&a.includes(n)&&Number.isFinite(r)&&r>=0&&r<=6e5&&(e.id===void 0||typeof e.id==`string`&&e.id.length>0)}function u(t,i,a){let{runtime:o}=t,u=a.pending??`discard`,d=a.timeoutMs??5e3;if(!l(i,u,d))throw Error(`Invalid security-context rotation options.`);let f=o.config.securityContext.id,p=i.id??n.i(o.diagnostics);if(p===f)throw Error(`A rotation requires a different security-context id.`);let m=t.allowed({...c(i.routing,o),securityContext:{id:p}}),h=r.r(m,o.diagnostics,{...o.config,...e.Pn});if(s(m,h,t.quiet).length>0)throw Error(`Invalid routing settings for the next security context.`);return{next:h,context:i.context?Object.fromEntries(Object.entries(i.context)):void 0,pending:u,timeoutMs:d,previous:f}}function d(e,t,n,r){return e===`retain`?t:e===`carry`?n:[...n,...r.flatMap(e=>e.records)]}async function f(e,t,n,a){let{runtime:o}=e,{config:s}=o,c;try{await e.senderLoaded(),c=e.holdRecords(()=>u(e,t,n))}catch(t){throw await e.closeDelivery(),t}if(o.isDestroyed())throw Error(`The runtime has stopped.`);let{next:l,context:f,pending:p,timeoutMs:m,previous:h}=c,g=new Set([s.endpoint,s.metricsEndpoint,s.tracesEndpoint]),_=new Set([l.endpoint,l.metricsEndpoint,l.tracesEndpoint]);l.capture.ignoreUrls=l.capture.ignoreUrls.filter(e=>!g.has(e)||_.has(e)),e.closeContext();let{held:v,sender:y,closed:b,carried:x}=e.takeOld(),S=b&&p===`flush`?`discard`:p,C=await y?.retire(S,m,h)??{buffered:[],stored:[]},w=[...v,...C.buffered],T=[...x,...C.stored];if(o.isDestroyed())throw e.drop(d(S,v,w,C.stored)),await e.adopt(x),Error(`The runtime has stopped.`);S!==`retain`&&S!==`carry`&&e.drop([...w,...T.flatMap(e=>e.records)]);let{diagnostics:E}=o;if(!y&&(S===`discard`||S===`flush`)){let t=x.map(e=>e.id);await E.guardAsync(`storage.degraded`,`The library could not remove the stored batches of the old context.`,()=>i.clearStored(e.storeAccess(),`context`,t))}if(S===`retain`&&(v.length>0||x.length>0)&&await E.guardAsync(`storage.degraded`,`The library could not store the records of the old context.`,()=>i.keepStored(e.storeAccess(),v,x)),o.isDestroyed())throw Error(`The runtime has stopped.`);if(l.lockConfiguration=s.lockConfiguration,r.n(s,l),e.advanceIdentity(),o.context.clear(),f&&o.context.merge(f),o.breadcrumbs.clear(),o.newSession(),o.builder.invalidateResource(),await e.openDelivery(),o.isDestroyed())throw S===`carry`&&(e.drop(w),await e.adopt(T)),Error(`The runtime has stopped.`);if(e.endRotation(a),p===`carry`){for(let t of w)e.route(t);await e.adopt(T)}o.diagnostics.report(`security.rotated`,`The runtime rotated its security context.`,{pending:p})}exports.rotateContext=f;
|
|
2
|
+
//# sourceMappingURL=rotation-E2eKClIs.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rotation-E2eKClIs.cjs","names":["ROUTING_KEYS","resolveEndpoint","resolveDestination","ROUTING_RESET","isObject","newId","resolveConfig","clearStored","keepStored","require_constants","require_guards","require_identity","require_config","require_stored_context","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","runtime","validOptions","update","pending","timeoutMs","planRotation","host","options","previous","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Runs the plan and holds the diagnostic records it raises until endRotation(), because the\n * logger drops every call during a rotation and these records belong to the next context.\n * @param plan Checks the next context's settings. It's synchronous, so nothing else is held.\n * @returns The plan's result.\n */\n holdRecords(plan: () => RotationPlan): RotationPlan;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again and writes the held diagnostic records. If a later rotation\n * waits, records stay blocked and the held ones are dropped, because they describe this context.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * It stays synchronous, because holdRecords() holds only what runs before the plan returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It throws for a setting it can't apply.\n */\nfunction planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): RotationPlan {\n const { runtime } = host;\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n plan = host.holdRecords(() => planRotation(host, update, options));\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n\n // shutdown() ran during the new sender's load, and that load stopped itself. Carry's live\n // records aren't routed yet, so they're lost. The other rules reported or stored theirs above.\n if (runtime.isDestroyed()) {\n if (rule === \"carry\") {\n host.drop(live);\n // The id is already the new one, so only these ids let a clearStorage find the old batches.\n await host.adopt(stored);\n }\n throw new Error(\"The runtime has stopped.\");\n }\n\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":"A,kMA2BA,IAAMc,EAAmC,CAAC,UAAW,QAAS,SAAU,OAAO,EAGzEC,EAAU,OAAO,SAAS,EA4FhC,SAASC,EACP,EACA,EACA,EACU,CACV,OAAOhB,EAAAA,GAAa,OAAQ,GAAQ,CAClC,IAAMiB,EAAiBC,EAAMC,GACvBC,EAAmBC,EAAKF,GAiB9B,OAdIF,IAAU,IAAA,GACL,GAILE,IAAQ,WACHlB,EAAAA,EAAgBgB,EAAOF,EAASO,CAAK,IAAMF,EAGhDD,IAAQ,mBAAqBA,IAAQ,iB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,aAAa,EAIpBN,EAAQ,YAAY,EAMtB,MALIW,IAAS,UACXL,EAAK,KAAKO,CAAI,EAEd,MAAMP,EAAK,MAAMQ,CAAM,GAEf,MAAM,0BAA0B,EAO5C,GAFAR,EAAK,YAAYwB,CAAG,EAEhB3B,IAAY,QAAS,CACvB,IAAK,IAAM4B,KAAUlB,EACnBP,EAAK,MAAMyB,CAAM,EAInB,MAAMzB,EAAK,MAAMQ,CAAM,CACzB,CAEAd,EAAQ,YAAY,OAAO,mBAAoB,4CAA6C,CAC1F,SACF,CAAC,CACH,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=sampling-
|
|
1
|
+
const e=require("./constants-CtF52hIV.cjs"),t=require("./fixed-window-CvESpFYV.cjs"),n=require("./defineProperty-X1c4tIPD.cjs");function r(t){let n=e.st;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.ct);return n>>>0}function i(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function a(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={value:i,length:r.length});return n}function o(e,t){return a(e,t.minLevels)?.value??t.minLevel}function s(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:o}=t.sampling,s=a(e,r),c=n?a(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.value,o):s?s.value:n?.defaultRate===void 0?i:Math.min(n.defaultRate,o)}function c(t,n){return e.At[t]>=e.At[n]}function l(t,n){return n>=1?!0:n<=0?!1:r(t)/e.dr<n}function u(t,n,r){if(t.aggregated===!0||t.type===`span`||c(t.level,n.sampling.alwaysSampleFrom)||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=s(t.namespace,n,r),a=o(t.namespace,n),u=e.At[t.level]<e.At[a];return r&&u&&!e.kt.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),l(t.journeyId||t.traceId,i)}function d(t,n,r=null){return u({level:t.severityText,type:i(t,e.g),namespace:i(t,e.a),journeyId:i(t,e.f),traceId:t.traceId,aggregated:i(t,`log.type`)===`metric`&&i(t,e.Bt.start)!==``},n,r)}var f=class{constructor(){n.t(this,`window`,{start:0,count:0})}allow(n,r=500,i=e.rt,a=`ERROR`){return!c(n.severityText,a)||r===null||t.t(this.window,r,i)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return f}});
|
|
2
|
+
//# sourceMappingURL=sampling-B46LW0cy.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-mXt4dstx.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","require_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, 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 at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * 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 Current remote rules, 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 // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether 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 Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":"A,gIAgCA,SAASc,EAAK,EAAuB,CACnC,IAAIC,EAAIf,EAAAA,GAER,IAAK,IAAIgB,EAAI,EAAGA,EAAIC,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWD,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGd,EAAAA,EAAS,EAG5B,OAAOc,IAAM,CACf,CASA,SAASG,EAAS,EAAmB,EAAqB,CACxD,IAAMD,EAAiBE,EAAO,WAAWC,GACzC,OAAO,OAAOH,GAAU,SAAWA,EAAQ,EAC7C,CAiBA,SAAgBI,EACd,EACA,EAC4B,CAC5B,IAAIC,EAEJ,IAAK,GAAM,CAACC,EAAQN,KAAU,OAAO,QAAQO,CAA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A,GAAmB,SAASqC,EAAM,IAAe,IAC/E,EAAO,KAAK,IAAIF,EAAMZ,EAAO,SAAS,aAAa,GAI9CW,EAAUG,EAAM,WAAaA,EAAM,QAASF,CAAI,CACzD,CAUA,SAAgBK,EACd,EACA,EACA,EAA6B,KACpB,CACT,OAAOJ,EACL,CACE,MAAOrB,EAAO,aACd,KAAMD,EAASC,EAAQd,EAAAA,CAAa,EACpC,UAAWa,EAASC,EAAQb,EAAAA,CAAkB,EAC9C,UAAWY,EAASC,EAAQZ,EAAAA,CAAe,EAC3C,QAASY,EAAO,QAChB,WACED,EAASC,EAAA,UAAqB,IAAM,UAAYD,EAASC,EAAQX,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAmB,EACAK,CACF,CACF,CAQA,IAAaa,EAAb,KAA0B,C,cAExBhC,EAAA,EAAA,KAAA,SAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,CAAA,C,CAU5D,MACE,EACA,EAAA,IACA,EAAWJ,EAAAA,GACX,EAAiB,QACR,CAMT,MALA,CAAK0B,EAAUhB,EAAO,aAAckB,CAAI,GAKjCS,IAAU,MAAQpC,EAAAA,EAAc,KAAK,OAAQoC,EAAOC,CAAQ,CACrE,CACF,E"}
|
|
1
|
+
{"version":3,"file":"sampling-B46LW0cy.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","require_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, 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 at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * 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 Current remote rules, 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 // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether 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 Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":"A,gIAgCA,SAASc,EAAK,EAAuB,CACnC,IAAIC,EAAIf,EAAAA,GAER,IAAK,IAAIgB,EAAI,EAAGA,EAAIC,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWD,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGd,EAAAA,EAAS,EAG5B,OAAOc,IAAM,CACf,CASA,SAASG,EAAS,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GT,IAAIF,EAAOX,EAAQa,EAAM,UAAWd,EAAQK,CAAM,EAK5CU,EAAchB,EAASe,EAAM,UAAWd,CAAM,EAC9CgB,EAAgBzC,EAAAA,GAAYuC,EAAM,OAAqBvC,EAAAA,GAAYwC,GAMzE,OALIV,GAAUW,GAAiB,CAACvC,EAAAA,GAAmB,SAASqC,EAAM,IAAe,IAC/E,EAAO,KAAK,IAAIF,EAAMZ,EAAO,SAAS,aAAa,GAI9CW,EAAUG,EAAM,WAAaA,EAAM,QAASF,CAAI,CACzD,CAUA,SAAgBK,EACd,EACA,EACA,EAA6B,KACpB,CACT,OAAOJ,EACL,CACE,MAAOrB,EAAO,aACd,KAAMD,EAASC,EAAQd,EAAAA,CAAa,EACpC,UAAWa,EAASC,EAAQb,EAAAA,CAAkB,EAC9C,UAAWY,EAASC,EAAQZ,EAAAA,CAAe,EAC3C,QAASY,EAAO,QAChB,WACED,EAASC,EAAA,UAAqB,IAAM,UAAYD,EAASC,EAAQX,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAmB,EACAK,CACF,CACF,CAQA,IAAaa,EAAb,KAA0B,C,cAExBhC,EAAA,EAAA,KAAA,SAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,CAAA,C,CAU5D,MACE,EACA,EAAA,IACA,EAAWJ,EAAAA,GACX,EAAiB,QACR,CAMT,MALA,CAAK0B,EAAUhB,EAAO,aAAckB,CAAI,GAKjCS,IAAU,MAAQpC,EAAAA,EAAc,KAAK,OAAQoC,EAAOC,CAAQ,CACrE,CACF,E"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { At as e, Bt as t, a as n, ct as r, dr as i, f as a, g as o, kt as s, rt as c, st as l } from "./constants-BwJDXzj6.js";
|
|
2
2
|
import { t as u } from "./fixed-window-Dq3MLUUv.js";
|
|
3
3
|
import { t as d } from "./defineProperty-s2S8BXUc.js";
|
|
4
4
|
// src/core/sampling.ts
|
|
5
5
|
function f(e) {
|
|
6
|
-
let t =
|
|
7
|
-
for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t,
|
|
6
|
+
let t = l;
|
|
7
|
+
for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, r);
|
|
8
8
|
return t >>> 0;
|
|
9
9
|
}
|
|
10
10
|
function p(e, t) {
|
|
@@ -26,26 +26,26 @@ function g(e, t, n) {
|
|
|
26
26
|
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = m(e, r), s = n ? m(e, n.rates) : void 0;
|
|
27
27
|
return s && s.length >= (o?.length ?? -1) ? Math.min(s.value, a) : o ? o.value : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
|
|
28
28
|
}
|
|
29
|
-
function _(
|
|
30
|
-
return
|
|
29
|
+
function _(t, n) {
|
|
30
|
+
return e[t] >= e[n];
|
|
31
31
|
}
|
|
32
32
|
function v(e, t) {
|
|
33
|
-
return t >= 1 ? !0 : t <= 0 ? !1 : f(e) /
|
|
33
|
+
return t >= 1 ? !0 : t <= 0 ? !1 : f(e) / i < t;
|
|
34
34
|
}
|
|
35
35
|
function y(t, n, r) {
|
|
36
36
|
if (t.aggregated === !0 || t.type === "span" || _(t.level, n.sampling.alwaysSampleFrom) || n.sampling.alwaysSampleTypes.includes(t.type)) return !0;
|
|
37
|
-
let i = g(t.namespace, n, r),
|
|
38
|
-
return r &&
|
|
37
|
+
let i = g(t.namespace, n, r), a = h(t.namespace, n), o = e[t.level] < e[a];
|
|
38
|
+
return r && o && !s.includes(t.type) && (i = Math.min(i, n.sampling.remoteMaxRate)), v(t.journeyId || t.traceId, i);
|
|
39
39
|
}
|
|
40
|
-
function b(e,
|
|
40
|
+
function b(e, r, i = null) {
|
|
41
41
|
return y({
|
|
42
42
|
level: e.severityText,
|
|
43
|
-
type: p(e,
|
|
44
|
-
namespace: p(e,
|
|
45
|
-
journeyId: p(e,
|
|
43
|
+
type: p(e, o),
|
|
44
|
+
namespace: p(e, n),
|
|
45
|
+
journeyId: p(e, a),
|
|
46
46
|
traceId: e.traceId,
|
|
47
|
-
aggregated: p(e, "log.type") === "metric" && p(e,
|
|
48
|
-
},
|
|
47
|
+
aggregated: p(e, "log.type") === "metric" && p(e, t.start) !== ""
|
|
48
|
+
}, r, i);
|
|
49
49
|
}
|
|
50
50
|
var x = class {
|
|
51
51
|
constructor() {
|
|
@@ -54,10 +54,10 @@ var x = class {
|
|
|
54
54
|
count: 0
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
|
-
allow(e, t = 500, n =
|
|
57
|
+
allow(e, t = 500, n = c, r = "ERROR") {
|
|
58
58
|
return !_(e.severityText, r) || t === null || u(this.window, t, n);
|
|
59
59
|
}
|
|
60
60
|
};
|
|
61
61
|
export { b as a, v as i, h as n, y as o, m as r, x as t };
|
|
62
62
|
|
|
63
|
-
//# sourceMappingURL=sampling-
|
|
63
|
+
//# sourceMappingURL=sampling-zXA6r-Nw.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-BlrI8jor.js","names":["LEVEL_BYPASS_TYPES","ATTR_APP_NAMESPACE","UINT32_MAX","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","LEVEL_ORDER","ERROR_STORM_WINDOW_MS","FNV_OFFSET_BASIS","FNV_PRIME","METRIC_KEYS","countInWindow","_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, 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 at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * 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 Current remote rules, 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 // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether 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 Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":";;;;AAgCA,SAASY,EAAK,GAAuB;CACnC,IAAIC,IAAIN;CAER,KAAK,IAAIO,IAAI,GAAGA,IAAIC,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWD,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGL,CAAS;CAG5B,OAAOK,MAAM;AACf;AASA,SAASG,EAAS,GAAmB,GAAqB;CACxD,IAAMD,IAAiBE,EAAO,WAAWC;CACzC,OAAO,OAAOH,KAAU,WAAWA,IAAQ;AAC7C;AAiBA,SAAgBI,EACd,GACA,GAC4B;CAC5B,IAAIC;CAEJ,KAAK,IAAM,CAACC,G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AmB,SAASuC,EAAM,IAAe,MAC/E,IAAO,KAAK,IAAIF,GAAMZ,EAAO,SAAS,aAAa,IAI9CW,EAAUG,EAAM,aAAaA,EAAM,SAASF,CAAI;AACzD;AAUA,SAAgBK,EACd,GACA,GACA,IAA6B,MACpB;CACT,OAAOJ,EACL;EACE,OAAOrB,EAAO;EACd,MAAMD,EAASC,GAAQb,CAAa;EACpC,WAAWY,EAASC,GAAQhB,CAAkB;EAC9C,WAAWe,EAASC,GAAQd,CAAe;EAC3C,SAASc,EAAO;EAChB,YACED,EAASC,GAAA,UAAqB,MAAM,YAAYD,EAASC,GAAQR,EAAY,KAAK,MAAM;CAC5F,GACAgB,GACAK,CACF;AACF;AAQA,IAAaa,IAAb,MAA0B;;EAExB,EAAA,MAAA,UAAuC;GAAE,OAAO;GAAG,OAAO;EAAE,CAAA;;CAU5D,MACE,GACA,IAAA,KACA,IAAWrC,GACX,IAAiB,SACR;EAMT,OALA,CAAK2B,EAAUhB,EAAO,cAAckB,CAAI,KAKjCS,MAAU,QAAQlC,EAAc,KAAK,QAAQkC,GAAOC,CAAQ;CACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"sampling-zXA6r-Nw.js","names":["LEVEL_ORDER","METRIC_KEYS","ATTR_APP_NAMESPACE","FNV_PRIME","UINT32_MAX","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","LEVEL_BYPASS_TYPES","ERROR_STORM_WINDOW_MS","FNV_OFFSET_BASIS","countInWindow","_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, 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 at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * 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 Current remote rules, 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 // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether 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 Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":";;;;AAgCA,SAASY,EAAK,GAAuB;CACnC,IAAIC,IAAIJ;CAER,KAAK,IAAIK,IAAI,GAAGA,IAAIC,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWD,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGV,CAAS;CAG5B,OAAOU,MAAM;AACf;AASA,SAASG,EAAS,GAAmB,GAAqB;CACxD,IAAMD,IAAiBE,EAAO,WAAWC;CACzC,OAAO,OAAOH,KAAU,WAAWA,IAAQ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B,IAAgBzC,EAAYuC,EAAM,SAAqBvC,EAAYwC;CAMzE,OALIV,KAAUW,KAAiB,CAAClC,EAAmB,SAASgC,EAAM,IAAe,MAC/E,IAAO,KAAK,IAAIF,GAAMZ,EAAO,SAAS,aAAa,IAI9CW,EAAUG,EAAM,aAAaA,EAAM,SAASF,CAAI;AACzD;AAUA,SAAgBK,EACd,GACA,GACA,IAA6B,MACpB;CACT,OAAOJ,EACL;EACE,OAAOrB,EAAO;EACd,MAAMD,EAASC,GAAQX,CAAa;EACpC,WAAWU,EAASC,GAAQf,CAAkB;EAC9C,WAAWc,EAASC,GAAQZ,CAAe;EAC3C,SAASY,EAAO;EAChB,YACED,EAASC,GAAA,UAAqB,MAAM,YAAYD,EAASC,GAAQhB,EAAY,KAAK,MAAM;CAC5F,GACAwB,GACAK,CACF;AACF;AAQA,IAAaa,IAAb,MAA0B;;EAExB,EAAA,MAAA,UAAuC;GAAE,OAAO;GAAG,OAAO;EAAE,CAAA;;CAU5D,MACE,GACA,IAAA,KACA,IAAWnC,GACX,IAAiB,SACR;EAMT,OALA,CAAKyB,EAAUhB,EAAO,cAAckB,CAAI,KAKjCS,MAAU,QAAQlC,EAAc,KAAK,QAAQkC,GAAOC,CAAQ;CACrE;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./constants-
|
|
1
|
+
import "./constants-BwJDXzj6.js";
|
|
2
2
|
import { n as e, t } from "./error-like-B11pB4aL.js";
|
|
3
3
|
// src/utils/sanitize.ts
|
|
4
4
|
function n(e, t) {
|
|
@@ -109,4 +109,4 @@ function l(e) {
|
|
|
109
109
|
}
|
|
110
110
|
export { n as i, a as n, o as r, l as t };
|
|
111
111
|
|
|
112
|
-
//# sourceMappingURL=sanitize-
|
|
112
|
+
//# sourceMappingURL=sanitize-DjnR6RXR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-Ba0KqU06.js","names":["set","toJson","isDataField","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","ERROR_OWN_KEYS","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // 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 * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the 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. 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. 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. 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 a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The 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, replacing 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 don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be 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, or a repeated sibling would show\n // up 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":";;;AA2CA,SAAgBG,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT,IAAME,IAAM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EAAM,SAASrB,EAAO,kBACxBgB,EAAI,KAAKZ,EAAQ,IAAI,OAAOiB,EAAM,SAASrB,EAAO,cAAc,EAAE,eAAeE,CAAK,CAAC,GAElFc;EACT;EAEA,IAAMO,IAAwBhC,EAA+B;EAC7D,IAAI,OAAOgC,KAAgB,YAEzB,OAAOpB,EAAKf,EAAO,KAAKG,CAAK,GAAGS,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAGhE,IAAMsB,IAASjC,GACTkC,IAAO,OAAO,KAAKD,CAAM,GACzBR,IAA+B,CAAC,GAClCU,IAAQ;EACZ,KAAK,IAAMd,KAAOa,GAAM;GACtB,IAAIC,KAAS1B,EAAO,mBAAmB;IACrC,EAAI,OAAOI,EAAQ,IAAI,OAAOqB,EAAK,SAASC,CAAK,EAAE,cAAcxB,CAAK;IACtE;GACF;GAGA,AAFA,KACA,EAAM,SAASG,EAAcO,CAAG,IAAA,GAChC,EAAIA,KAAOT,EAAKqB,EAAOZ,IAAMZ,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAC7D;EACA,OAAOc;CACT,SAASP,GAAO;EAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,GAEzCE,EAAQ,oBADFK,aAAiB,QAAQA,EAAM,OAAO,QACX,IAAIP,CAAK;CACnD,UAAU;EAGR,EAAK,OAAOX,CAAK;CACnB;AACF;AAOA,SAAgBc,EAAc,GAAuB;CACnD,IAAIsB,IAAQ;CACZ,KAAK,IAAIC,IAAI,GAAGA,IAAIrC,EAAM,QAAQ,KAAK;EACrC,IAAMI,IAAOJ,EAAM,WAAWqC,CAAC;EAC/B,AAAIjC,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAOgC;AACT"}
|
|
1
|
+
{"version":3,"file":"sanitize-DjnR6RXR.js","names":["set","toJson","isDataField","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","ERROR_OWN_KEYS","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // 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 * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the 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. 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. 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. 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 a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The 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, replacing 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 don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be 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, or a repeated sibling would show\n // up 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":";;;AA2CA,SAAgBG,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT,IAAME,IAAMC,EAAgBH,EAAM,WA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error-like-gGRx2s36.cjs");function t(e,t){if(e.length<=t)return e;let r=n(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,r)}… [truncated ${String(e.length-r)} chars]`}function n(e){return e>=55296&&e<=56319}function r(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 i(e,t,n){return a(e,t,n).value}function a(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:s(e,t,new WeakSet,0,r),bytes:r.bytes}}function o(e,t){return t.bytes+=c(e)+2,e}function s(n,i,a,l,u){if(u.nodes++,u.nodes>i.maxNodes)return o(`[MaxNodes]`,u);if(n==null)return u.bytes+=4,n;if(typeof n==`string`)return o(t(n,i.maxAttributeChars),u);if(typeof n==`number`)return u.bytes+=8,Number.isFinite(n)?n:String(n);if(typeof n==`boolean`)return u.bytes+=5,n;if(typeof n==`bigint`)return o(`${n.toString()}n`,u);if(typeof n==`symbol`)return o(n.toString(),u);if(typeof n==`function`)return o(`[Function ${n.name===``?`anonymous`:n.name}]`,u);if(l>=i.maxDepth)return o(`[MaxDepth]`,u);if(a.has(n))return o(`[Circular]`,u);a.add(n),u.bytes+=2;try{if(n instanceof Error||Object.prototype.toString.call(n)===`[object Error]`){let r=n,c={},d=0;for(let t of Object.keys(r)){let n=r[t];!e.t.has(t)&&e.n(n)&&(c[t]=n,d++)}return{name:o(r.name,u),message:o(t(r.message,i.maxAttributeChars),u),stack:r.stack?o(t(r.stack,i.maxStackChars),u):void 0,cause:r.cause?s(r.cause,i,a,l+1,u):void 0,data:d>0?s(c,i,a,l+1,u):void 0}}if(n instanceof Date)return o(n.toISOString(),u);if(n instanceof RegExp)return o(n.toString(),u);if(n instanceof Map){let e=n,t={},r=0;for(let[n,d]of e){if(r>=i.maxArrayLength){t[`…`]=o(`[${String(e.size-i.maxArrayLength)} more entries]`,u);break}r++;let f=String(n);u.bytes+=c(f)+4,t[f]=s(d,i,a,l+1,u)}return t}if(n instanceof Set)return s([...n].slice(0,i.maxArrayLength),i,a,l,u);if(ArrayBuffer.isView(n)){let e=n.length??0;return o(`[${n.constructor.name}(${String(e)})]`,u)}if(n instanceof Promise)return o(`[Promise]`,u);if(typeof Node<`u`&&n instanceof Node)return o(r(n),u);if(Array.isArray(n)){let e=n,t=e.slice(0,i.maxArrayLength).map(e=>s(e,i,a,l+1,u));return e.length>i.maxArrayLength&&t.push(o(`[${String(e.length-i.maxArrayLength)} more items]`,u)),t}let d=n.toJSON;if(typeof d==`function`)return s(d.call(n),i,a,l+1,u);let f=n,p=Object.keys(f),m={},h=0;for(let e of p){if(h>=i.maxAttributeCount){m[`…`]=o(`[${String(p.length-h)} more keys]`,u);break}h++,u.bytes+=c(e)+4,m[e]=s(f[e],i,a,l+1,u)}return m}catch(e){return u.diagnostics.count(`record.sanitize_failed`),o(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,u)}finally{a.delete(n)}}function c(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,"i",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}});
|
|
2
|
+
//# sourceMappingURL=sanitize-Qj6LuZqp.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-DQyiI_KY.cjs","names":["ERROR_OWN_KEYS","isDataField","set","toJson","require_error_like","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // 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 * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the 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. 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. 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. 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 a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The 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, replacing 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 don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be 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, or a repeated sibling would show\n // up 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":"A,iFA2CA,SAAgBK,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,EAA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OAAOnB,EAAKf,EAAO,KAAKG,CAAK,EAAGS,EAAQQ,EAAMD,EAAQ,EAAGL,CAAK,EAGhE,IAAMqB,EAAShC,EACTiC,EAAO,OAAO,KAAKD,CAAM,EACzBR,EAA+B,CAAC,EAClCU,EAAQ,EACZ,IAAK,IAAMb,KAAOY,EAAM,CACtB,GAAIC,GAASzB,EAAO,kBAAmB,CACrC,EAAI,KAAOI,EAAQ,IAAI,OAAOoB,EAAK,OAASC,CAAK,EAAE,aAAcvB,CAAK,EACtE,KACF,CACA,IACA,EAAM,OAASG,EAAcO,CAAG,EAAA,EAChC,EAAIA,GAAOT,EAAKoB,EAAOX,GAAMZ,EAAQQ,EAAMD,EAAQ,EAAGL,CAAK,CAC7D,CACA,OAAOa,CACT,OAASN,EAAO,CAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,EAEzCE,EAAQ,oBADFK,aAAiB,MAAQA,EAAM,KAAO,QACX,GAAIP,CAAK,CACnD,QAAU,CAGRM,EAAK,OAAOjB,CAAK,CACnB,CACF,CAOA,SAAgBc,EAAc,EAAuB,CACnD,IAAIqB,EAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIpC,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWoC,CAAC,EAC3BhC,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT,C"}
|
|
1
|
+
{"version":3,"file":"sanitize-Qj6LuZqp.cjs","names":["ERROR_OWN_KEYS","isDataField","set","toJson","require_error_like","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // 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 * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the 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. 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. 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. 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 a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The 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, replacing 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 don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be 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, or a repeated sibling would show\n // up 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":"A,iFA2CA,SAAgBK,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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