@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
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["DEFER_IDLE_TIMEOUT_MS","DEFER_QUEUE_LIMIT","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DIAGNOSTICS_NAMESPACE","isErrorLike","ERROR_OWN_KEYS","isDataField","isObject","nowUnixNano","currentUrl","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","DEFAULT_METRIC_UNIT","METRIC_KEYS","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","METRIC_DEFAULT_BOUNDARIES","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","METRIC_KEYS","METRIC_DEFAULT_BOUNDARIES","ATTR_METRIC_OVERFLOW","RECORD_LIMITS","hasOwn","LEVEL_ORDER","isLibraryConsole","sanitize","ATTR_DEBUG_BUFFER","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","attributeOf","ATTR_JOURNEY_ID","isActionRecord","isActionRecord","BUS_MAX_BOOT_BUFFER_ACTIONS","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","METRIC_KEYS","SPAN_KEYS","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","LEVEL_BYPASS_TYPES","levelFor","LEVEL_ORDER","shouldSampleInput","currentUrl","recordedUrl","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_SEQ","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","shouldSample","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","REFUSE_RECORDS","isLogRecord","isLogLevel","isObject","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","SPAN_KEYS","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","isObject","recordedUrl","TELEMETRY_SDK_VERSION","DIAGNOSTICS_NAMESPACE","BUS_PROTOCOL","memoryStores","STORAGE_NAMESPACE","detectPlatform","resolveConfig","newId","resolveIdentity","SessionTouch","sampleKey","JOURNEY_OPTIONS","JourneyEngine","truncate","sanitize","TRACE_NAMESPACE","METRIC_NAMESPACE","profilerCore","REFUSE_RECORDS","LIBRARY_LOG_PREFIX","ROUTING_KEYS","BROWSER_STORES","REMOTE_CAPTURE_FLAGS","CAPTURE_NAMESPACE","INSTRUMENT_OPTIONS_FAULT","runAsLibraryRequest","isLogRecord","shouldSample","ATTR_BREADCRUMBS","ATTR_PAGE_URL","FLUSH_REQUEST_SHARE","FLUSH_TIMEOUT_MS","hasOwn","isObject","TRANSPORT_WORKER_TYPE","TRANSPORT_WORKER_REFUSAL","INSTRUMENT_OPTIONS_FAULT","profilerCore","isObject","require_constants","require_log_record","require_error_like","require_guards","require_unref","require_platform","require_defineProperty","require_identity","require_profiler","require_library_console","require_sanitize","require_library_request","require_config","require_batch","require_journey","require_sampling","queues","cancel","idle","queue","schedule","drain","owner","deadline","work","index","deferWrite","capacity","limit","diagnostics","drainDeferred","cancelDeferred","_work","LIBRARY_NAMESPACES","toError","known","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","message","error","name","bind","options","runtime","level","type","body","snapshot","journey","input","copied","hooks","keepsCrumb","protectedCrumb","dropped","safe","record","crumb","ships","asPayload","attributes","asError","shown","clean","LibraryLogger","_args","recordOnly","unit","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","traceparent","traceId","spanId","traceFlags","toTraceContext","ambient","TraceEngine","maxAgeMs","load","spans","otel","span","spanContext","old","next","carrier","\"traceparent\"","fromOtel","ctx","kept","flags","client","TOTAL_DURATION","PHASE_DURATION","createMeasure","label","startMs","startedAt","open","ended","epoch","at","closePhase","sinks","now","outcome","fields","measureCall","result","fn","then","chained","handle","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","copyBounds","bounds","i","isAscending","bound","fieldsOf","point","def","start","series","readOptions","fault","scalarDef","makeCounter","makeGauge","makeHistogram","boundaries","Meter","intervalMs","emit","policy","instrument","instruments","one","found","maxInstruments","valid","set","maxSeries","size","buckets","METHOD","ConsoleSink","settings","limits","prefix","method","details","styles","Sequence","BreadcrumbBuffer","recent","keep","ContextStore","values","DebugBuffer","enabled","maxRecords","oldest","entry","Diagnostics","handler","throttleMs","consoleFallback","total","code","by","event","addCapped","list","DropReporter","config","records","batchIds","summary","id","summaries","onDrop","HoldBuffer","actions","others","action","kind","cap","held","first","second","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","HOOK_STAGES","isFiniteNumber","isNumberList","isNanos","isTraceId","isSpanId","isParentId","isCounter","isHistogram","isSpanKind","isSpanStatus","COUNTER_FIELDS","HISTOGRAM_FIELDS","SPAN_FIELDS","LINK_FIELDS","groupsOf","fixedOf","fixed","group","keys","asAttributes","RecordBuilder","deps","minLevel","debug","forConsole","traceCtx","tracing","activeJourney","sampled","remote","seq","sequence","url","pageUrl","bytes","fromContext","fromProvider","fromScope","fromPayload","stages","redact","leveled","stamped","hooked","keptBytes","breadcrumbs","crumbBytes","processors","hook","current","stage","remeasured","changed","refused","candidate","provider","given","platform","identity","US_PER_MS","ROOT_NAMES","unixNano","ms","rootSpan","spanFields","CAPTURE_LOADERS","pluginIds","lastPluginId","pluginId","plugin","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","LOGGED_CRUMBS","FAILED_START","SHUTDOWN_INVALID","FLUSH_INVALID","NOTICE_CODES","captureKey","capture","recordDetail","detail","consoleOnly","sends","flushResult","counts","settled","ownVersion","ObservabilityRuntime","locked","resolve","origin","bus","reply","batch","mismatch","keeps","points","core","sink","consent","local","pinned","stopped","implicit","live","foundText","sameConfig","accepted","probe","maxProbes","section","sections","adds","removes","built","sessionIdleMs","sessionId","tabId","traceMaxAgeMs","captures","journeyReady","Bus","rotating","shared","timeoutMs","sender","Sender","storage","state","carried","stored","wire","framePhases","framePacing","replay","generation","replayKey","names","profiler","classes","WebSocketCapture","CaptureModule","plugins","metric","cancelled","detach","worker","frame","discard","scope","closing","parked","read","unset","clearStorage","knownScope","flushes","pending","buffered","ids","clearStored","paused","fresh","redacted","run","update","settle","rotate","crumbs","configSummary","sent","issues","collect","ends","stop","expired","timer","loading","forwarder","forwarded","lost","share","answer","a","b","seen","ak","bk","active","serveTransportWorker","port","onMessage","incoming","module","createMemoryTransport","request","retryAfterMs","loggers","requireRuntime","configure","trimLoggerCache","setConfigurationLocked","rotateSecurityContext","getHealth","collectDebugBundle","health","max","getLogger","logger","root","trace","info","warn","err","fatal","logAction","logEvent","optionsFault","counter","gauge","histogram","startMeasure","measure","startReplay","stopReplay","addBreadcrumb","setContext","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","registerWorker","registerFrame","newTrace","getTraceHeaders","flush","newSession","getDiagnosticCounters","shutdown"],"sources":["../src/core/deferred.ts","../src/core/logger.ts","../src/utils/tracing.ts","../src/core/measure.ts","../src/core/meter.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/core/breadcrumbs.ts","../src/core/context.ts","../src/core/debug-buffer.ts","../src/core/diagnostics.ts","../src/core/drops.ts","../src/core/hold-buffer.ts","../src/core/record.ts","../src/core/spans.ts","../src/core/runtime.ts","../src/transport/worker-entry.ts","../src/transport/memory-transport.ts","../src/index.ts"],"sourcesContent":["import { DEFER_IDLE_TIMEOUT_MS, DEFER_QUEUE_LIMIT } from \"../constants\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One runtime's pending logger calls. A stopped runtime releases every payload reference. */\ninterface DeferredQueue {\n work: (() => void)[];\n diagnostics: Diagnostics;\n draining: boolean;\n idle?: number;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nconst queues = new WeakMap<object, DeferredQueue>();\n\n/** Cancels the scheduled callback before a synchronous drain or a shutdown. */\nfunction cancel(queue: DeferredQueue): void {\n const idle = queue.idle;\n if (idle !== undefined) {\n queue.diagnostics.guard(\"pipeline.crashed\", \"The idle callback could not be cancelled.\", () => {\n cancelIdleCallback(idle);\n });\n queue.idle = undefined;\n }\n\n clearTimeout(queue.timer);\n queue.timer = undefined;\n}\n\n/** Schedules one idle callback, or a timer in browsers without the idle API. */\nfunction schedule(owner: object, queue: DeferredQueue): void {\n if (typeof requestIdleCallback === \"function\" && typeof cancelIdleCallback === \"function\") {\n queue.idle = queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The idle callback could not be scheduled.\",\n () =>\n requestIdleCallback(\n (deadline) => {\n drain(owner, queue, deadline);\n },\n { timeout: DEFER_IDLE_TIMEOUT_MS },\n ),\n );\n if (queue.idle !== undefined) {\n return;\n }\n }\n\n queue.timer = setTimeout(() => {\n drain(owner, queue);\n }, 0);\n unrefTimer(queue.timer);\n}\n\n/** Builds a bounded group of calls. Reentrant calls wait for the next callback. */\nfunction drain(owner: object, queue: DeferredQueue, deadline?: IdleDeadline): void {\n if (queues.get(owner) !== queue || queue.draining) {\n return;\n }\n\n cancel(queue);\n queue.draining = true;\n const work = queue.work;\n queue.work = [];\n let index = 0;\n\n while (\n index < work.length &&\n (!deadline || (deadline.didTimeout && index === 0) || deadline.timeRemaining() > 0)\n ) {\n queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The library could not build a deferred record.\",\n work[index],\n );\n index++;\n if (queues.get(owner) !== queue) {\n return;\n }\n }\n\n queue.work = [...work.slice(index), ...queue.work];\n queue.draining = false;\n if (queue.work.length > 0) {\n schedule(owner, queue);\n } else {\n queues.delete(owner);\n }\n}\n\n/** Queues a call without reading its payload. A full queue builds its pending calls first. */\nexport function deferWrite(\n owner: object,\n work: () => void,\n diagnostics: Diagnostics,\n limit: number | null,\n): void {\n let queue = queues.get(owner);\n const capacity = limit === null ? DEFER_QUEUE_LIMIT : Math.min(limit, DEFER_QUEUE_LIMIT);\n if (queue && queue.work.length >= capacity && !queue.draining) {\n drain(owner, queue);\n queue = queues.get(owner);\n }\n\n if (queue) {\n if (queue.work.length >= capacity) {\n diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n queue.work.push(work);\n return;\n }\n\n queue = { work: [work], diagnostics, draining: false };\n queues.set(owner, queue);\n schedule(owner, queue);\n}\n\n/** Builds pending calls before a flush, a session change or a delivery identity change. */\nexport function drainDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n drain(owner, queue);\n }\n}\n\n/** Releases calls that a hook queues during shutdown. No records were built for them. */\nexport function cancelDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n cancel(queue);\n queues.delete(owner);\n for (const _work of queue.work) {\n queue.diagnostics.count(\"record.dropped_by_ceiling\");\n }\n queue.work = [];\n }\n}\n","// src/core/logger.ts\n//\n// Namespaced logger facade with scoped log methods. The capture modules' logger can also write\n// one metric record per call.\n\nimport {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n DIAGNOSTICS_NAMESPACE,\n METRIC_KEYS,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport {\n type LogLevel,\n type LogRecord,\n type LogType,\n type MetricType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason, RecordSnapshot } from \"./record\";\nimport { deferWrite } from \"./deferred\";\nimport { currentUrl } from \"../utils/platform\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** The library's own namespaces. Their records get log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [\n CAPTURE_NAMESPACE,\n STORAGE_NAMESPACE,\n DIAGNOSTICS_NAMESPACE,\n];\n\n/** Configuration options for a scoped OneLogger instance. */\nexport interface OneLoggerOptions {\n /** Contextual attributes merged into all records emitted by this logger. */\n scopedContext?: Record<string, unknown>;\n}\n\n/**\n * Turns any thrown value into an Error. A real error is copied with its name, message and stack.\n * @param value Caught error instance or primitive value.\n * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof and from any property read, and a Proxy around\n // an Error passes instanceof, so read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a throwing toString. log.error() runs\n // inside the consumer's catch block, so it must not throw out of it.\n const text = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not convert the error reason to text.\",\n () => String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Returns the error the console prints. The console shows a real Error's cause and own\n * fields, while the record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, otherwise the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads an error reason's data for the error.data attribute. Keeps only own fields whose\n * value is a string, number or boolean.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns An object reason's fields, a primitive reason, or undefined. A string reason\n * returns undefined because error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, such as an AxiosError's config, can hold credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\n}\n\n/**\n * Checks whether a value is an attribute bag rather than an error reason. Works across\n * realms, because an object literal from an iframe has that realm's Object.prototype, whose\n * own prototype is also null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!isObject(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/**\n * Picks the log.type the level methods use for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for one of the library's namespaces, \"log\" for any other.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload, so a Proxy with a throwing trap can't throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the payload can't be read.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type the level methods use. \"system\" only for the library's own namespaces. */\n private readonly levelType: LogType;\n\n /**\n * @param bind Returns the runtime for each write, so a logger created before configure()\n * still writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n protected readonly bind: () => ObservabilityRuntime,\n readonly namespace: string,\n private readonly options: OneLoggerOptions = {},\n ) {\n this.levelType = levelTypeFor(namespace);\n }\n\n /**\n * Creates a child logger with a nested namespace and merged scoped context.\n * @param namespace Sub-namespace appended with dot notation.\n * @param options Additional scoped context attributes.\n * @returns Nested child OneLogger instance.\n */\n child(namespace: string, options: OneLoggerOptions = {}): OneLogger {\n return new OneLogger(this.bind, `${this.namespace}.${namespace}`, {\n scopedContext: {\n ...this.options.scopedContext,\n ...options.scopedContext,\n },\n });\n }\n\n /**\n * Logs a trace-level debug record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n trace = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"TRACE\", this.levelType, message, payload);\n };\n\n /**\n * Logs a debug-level record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n debug = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"DEBUG\", this.levelType, message, payload);\n };\n\n /**\n * Logs an informational record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n info = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", this.levelType, message, payload);\n };\n\n /**\n * Logs a warning record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n warn = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"WARN\", this.levelType, message, payload);\n };\n\n /**\n * Logs an error record with the breadcrumb history. When payload is omitted, a plain\n * object in the error slot is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n error = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"ERROR\", message, error, payload);\n };\n\n /**\n * Logs a fatal error record. When payload is omitted, a plain object in the error slot\n * is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n fatal = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"FATAL\", message, error, payload);\n };\n\n /**\n * Logs a user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\n logAction = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"action\", name, payload);\n };\n\n /**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\n logEvent = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"event\", name, payload);\n };\n\n /**\n * Builds and emits a standard log record, and prints it to the console.\n * @param level Severity level.\n * @param type Record classification.\n * @param body Primary message.\n * @param payload Optional contextual attributes.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, type, (snapshot) => {\n this.writeNow(runtime, level, type, body, payload, false, snapshot);\n });\n }\n\n /** Runs a call right away, or queues it without reading its payload. */\n protected submit(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n work: (snapshot?: RecordSnapshot) => void,\n ): void {\n if (runtime.isDestroyed()) {\n return;\n }\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\n return;\n }\n\n if (\n runtime.config.payloadMode === \"defer\" &&\n runtime.config.enabled &&\n !runtime.config.debugBuffer.enabled &&\n // A deferred diagnostic record is built outside its loop guard, so a hook failure would loop.\n this.namespace !== DIAGNOSTICS_NAMESPACE\n ) {\n if (\n !runtime.builder.isEnabled(level, this.namespace, type) &&\n !this.mirrors(runtime, level)\n ) {\n return;\n }\n\n const journey = runtime.journey.current();\n const snapshot: RecordSnapshot = {\n timeUnixNano: nowUnixNano(),\n trace: runtime.tracing.resolve(),\n journey: journey ? { ...journey } : null,\n context: runtime.context.getAll(),\n url: currentUrl(runtime.diagnostics),\n };\n deferWrite(\n runtime,\n () => {\n work(snapshot);\n },\n runtime.diagnostics,\n runtime.config.buffering.maxPendingRecords,\n );\n return;\n }\n\n work();\n }\n\n /** Builds a standard record once the call's payload is ready to read. */\n protected writeNow(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n body: string,\n payload: Record<string, unknown> | undefined,\n copied: boolean,\n snapshot?: RecordSnapshot,\n ): void {\n // minLevel limits what we send, and the console level limits what we print. minLevel doesn't\n // apply to an action or a metric, and the debug buffer keeps records below it.\n const keepsDropped = runtime.config.enabled && runtime.config.debugBuffer.enabled;\n if (!keepsDropped && !runtime.builder.isEnabled(level, this.namespace, type)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null, undefined, snapshot);\n }\n\n return;\n }\n\n const input = {\n snapshot,\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: copied ? payload : copyPayload(payload, runtime.diagnostics),\n };\n const { record, dropped } = runtime.builder.build(input);\n const hooks = Boolean(runtime.config.redact) || runtime.config.processors.length > 0;\n // Only run the hooks on a sampled-out record if a breadcrumb keeps its message.\n const keepsCrumb = type !== \"metric\" && runtime.config.captureLimits.breadcrumbs > 0;\n const protectedCrumb =\n dropped === \"sampling\" && hooks && keepsCrumb\n ? runtime.builder.build(input, true)\n : undefined;\n const safe = record ?? protectedCrumb?.record ?? null;\n const crumb = safe ? safe.body : dropped === \"sampling\" && !hooks ? body : undefined;\n if (keepsCrumb && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: snapshot ? Number(snapshot.timeUnixNano.slice(0, -6)) : Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n this.print(\n runtime,\n level,\n body,\n payload,\n undefined,\n safe,\n protectedCrumb?.dropped ?? dropped,\n snapshot,\n );\n runtime.emit(record);\n }\n\n /**\n * Builds and emits an error record with breadcrumbs, and prints it to the console.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n private writeError(\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, this.levelType, (snapshot) => {\n this.writeErrorNow(runtime, level, message, error, payload, snapshot);\n });\n }\n\n /** Builds an error record once the deferred queue releases its payload. */\n private writeErrorNow(\n runtime: ObservabilityRuntime,\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload: Record<string, unknown> | undefined,\n snapshot?: RecordSnapshot,\n ): void {\n const ships = runtime.builder.isEnabled(level, this.namespace);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // Every sibling method takes (name, payload?), so callers expect log.error(\"failed\", { id })\n // to work. Treated as an error reason, that object would put \"[object Object]\" in\n // error.message and drop the caller's fields. A Proxy in the error slot can throw on the check.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null, undefined, snapshot);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped, snapshot);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook or processors, the line shows only what they\n * returned. A host can record console arguments, so the console must not show what the hooks\n * remove.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error The error from an error call.\n * @param record Built record, or null if it was never built or redact dropped it.\n * @param dropped Why the builder dropped the record, if it did.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n dropped?: DropReason,\n snapshot?: RecordSnapshot,\n ): void {\n if (!runtime.config.redact && runtime.config.processors.length === 0) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record's attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n // A record dropped by a hook or the shape check prints nothing. Its text never passed redact.\n if (dropped === \"processor\" || dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n if (!runtime.config.enabled || !runtime.console.accepts(level)) {\n return;\n }\n // Use the record builder without the delivery level and sampling checks. Don't process\n // a record again if a hook refused it, and don't send this one or add it as a breadcrumb.\n const clean = runtime.builder.build(\n {\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(payload, runtime.diagnostics),\n ...(error\n ? {\n \"error.type\": error.name,\n \"error.message\": error.message,\n \"error.stack_trace\": error.stack,\n }\n : {}),\n },\n },\n true,\n ).record;\n if (clean) {\n runtime.console.write(this.namespace, level, clean.body, clean.attributes);\n }\n }\n\n /**\n * Checks whether the console prints a level that we don't send.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\n }\n}\n\n/**\n * Logger for the capture modules. It also writes one metric record per call, which the public\n * Logger can't, because an app's metric goes through an instrument and its interval.\n */\nexport class LibraryLogger extends OneLogger {\n /**\n * Logs one metric measurement as its own record.\n * @param name Metric identifier.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes. With metricsEndpoint they're point attributes.\n * @param recordOnly Optional attributes for the record only. They stay off the OTLP point,\n * because a value that changes on each page load would start a new series each time.\n */\n logMetric = (\n name: string,\n value: number,\n unit = DEFAULT_METRIC_UNIT,\n type: MetricType = \"gauge\",\n attributes?: Record<string, unknown>,\n recordOnly?: Record<string, unknown>,\n ): void => {\n // NaN and Infinity become null in JSON, which a backend then reads as a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n const runtime = this.bind();\n this.submit(runtime, \"INFO\", \"metric\", (snapshot) => {\n // Copy the caller's attributes first so the metric fields win. The record-only ones aren't\n // in the key list, so the metrics format leaves them off the point.\n const copied = copyPayload(attributes, runtime.diagnostics);\n const payload = {\n ...copyPayload(recordOnly, runtime.diagnostics),\n ...copied,\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n [METRIC_KEYS.attributeKeys]: Object.keys(copied),\n };\n this.writeNow(runtime, \"INFO\", \"metric\", name, payload, true, snapshot);\n });\n };\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed trace contexts, OpenTelemetry span integration, and W3C\n// traceparent headers. Consecutive records share one trace id, because a new trace id for\n// every record would give each trace only one span.\n\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** The W3C format fixes these hex widths. A span context with any other width is unusable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Matches a digit that isn't zero. A span that hasn't started reports an all-zero id. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Checks whether a span context can carry correlation. Replaces isSpanContextValid from the\n * peer package, which isn't available when the peer isn't installed.\n * @param context The span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\n\n/** W3C trace context fields attached to log records and network headers. */\nexport interface TraceContext {\n /** Hexadecimal 32-character W3C trace identifier. */\n traceId: string;\n /** Hexadecimal 16-character W3C span identifier. */\n spanId: string;\n /** Bitfield byte containing W3C trace flags. */\n traceFlags: number;\n}\n\n/** Why the ambient trace context rotated. */\nexport type RotateReason = \"start\" | \"interaction\" | \"navigation\" | \"explicit\" | \"maxAge\";\n\n/** An ambient trace that ended. Its root span covers it. */\nexport interface EndedTrace {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the root span. */\n spanId: string;\n /** Why the trace started. */\n reason: RotateReason;\n /** Start time in epoch milliseconds. */\n startedAt: number;\n /** End time in epoch milliseconds. */\n endedAt: number;\n}\n\n/** The client span that a traceparent header names. */\nexport interface ClientSpan {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the client span. */\n spanId: string;\n /** Span ID of the trace's root span. */\n parentSpanId: string;\n}\n\n/** One request's headers, and the client span they name. */\nexport interface RequestTrace {\n /** Header map containing traceparent. */\n headers: Record<string, string>;\n /** The request's client span. Undefined when the library records no span for it. */\n span?: ClientSpan;\n}\n\n/** The runtime's span decisions. */\nexport interface SpanHooks {\n /**\n * Checks whether the library records spans.\n * @returns True when there is a traces endpoint.\n */\n enabled(): boolean;\n /**\n * Checks whether sampling keeps a trace's spans.\n * @param traceId Trace ID.\n * @returns True if the library sends the trace's spans.\n */\n keeps(traceId: string): boolean;\n /**\n * Receives an ambient trace that ended.\n * @param ended The trace.\n */\n onEnd(ended: EndedTrace): void;\n}\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n /** Why the trace started. */\n reason: RotateReason;\n /** True once the root span has ended. It ends only once. */\n ended: boolean;\n}\n\n/**\n * Generates a random 32-character hex string in the W3C trace ID format. Use it to start\n * your own trace. The backend drops an id with the wrong width without reporting an error.\n * @returns 32-character hexadecimal trace ID.\n */\nexport function newTraceId(): string {\n return randomHex(TRACE_ID_BYTES);\n}\n\n/**\n * Generates a random 16-character hex string conforming to W3C span ID format.\n * @returns 16-character hexadecimal span ID.\n */\nexport function newSpanId(): string {\n return randomHex(SPAN_ID_BYTES);\n}\n\n/**\n * Creates a new AmbientTrace with the sampled trace flag set. The flag is always set, because\n * sampling runs before the library builds the record.\n * @param reason Why the trace starts.\n * @returns The initialized AmbientTrace.\n */\nfunction mintAmbient(reason: RotateReason): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n reason,\n ended: false,\n };\n}\n\n/**\n * Formats a W3C traceparent value.\n * @param traceId Trace ID.\n * @param spanId The caller's span ID.\n * @param traceFlags Trace flags.\n * @returns The traceparent value.\n */\nfunction traceparent(traceId: string, spanId: string, traceFlags: number): string {\n // Mask the trace flags to a 2-digit hex byte, as the W3C specification requires.\n // trace-flags is a bitfield, not a boolean, and a fixed 00 or 01 would discard upstream flags.\n const flags = (traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n return `${TRACEPARENT_VERSION}-${traceId}-${spanId}-${flags}`;\n}\n\n/**\n * Creates a defensive copy of a TraceContext from an AmbientTrace.\n * @param ambient Source ambient trace object.\n * @returns Defensive copy of TraceContext.\n */\nfunction toTraceContext(ambient: AmbientTrace): TraceContext {\n return {\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n traceFlags: ambient.traceFlags,\n };\n}\n\n/** Manages ambient distributed trace contexts and resolves active OpenTelemetry spans. */\nexport class TraceEngine {\n /**\n * The active ambient trace context. This state lives on the instance, not the module,\n * because two runtimes in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient(\"start\");\n\n /** The optional peer, once loaded. Undefined while it loads or when it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it isn't set, OTel is off.\n * Do not import the peer by name, because the Vite dev server fails if the peer isn't\n * installed.\n * @param spans The runtime's span decisions. Without them, the library records no span.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private maxAgeMs = TRACE_MAX_AGE_MS,\n private load?: OtelLoader,\n private readonly spans?: SpanHooks,\n ) {}\n\n /**\n * Sets the trace age and the OpenTelemetry loader from the app's startup call. A log call\n * before configure() builds the engine before those settings exist.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it isn't set, OTel is off.\n */\n setup(maxAgeMs: number, load: OtelLoader | undefined): void {\n this.maxAgeMs = maxAgeMs;\n this.load = load;\n }\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns A promise that resolves when the attempt settles.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"The library could not load @opentelemetry/api. Records use the trace ids of the library.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.\n * @returns Active TraceContext.\n */\n resolve(): TraceContext {\n return this.activeSpanContext() ?? this.ambientContext();\n }\n\n /**\n * Reads the ambient trace, rotating it first if it is too old.\n * @returns The ambient TraceContext.\n */\n private ambientContext(): TraceContext {\n // Rotate the ambient trace once it is older than maxAgeMs. This is checked on read, not on\n // a timer, because a timer would keep this instance alive for the life of the document.\n if (Date.now() - this.ambient.startedAt > this.maxAgeMs) {\n this.rotate(\"maxAge\");\n }\n return toTraceContext(this.ambient);\n }\n\n /**\n * Reads the host's active span, if the peer module loaded and a span is running.\n * @returns The active span's trace context, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not read the active OpenTelemetry span.\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\n }\n\n /**\n * Rotates the ambient trace context to mark the start of a new logical operation, and ends\n * the old trace's root span.\n * @param reason The event that triggers the rotation.\n * @returns The newly created TraceContext.\n */\n rotate(reason: RotateReason): TraceContext {\n // Set the new trace first, so a record that a hook makes inside onEnd joins the new trace.\n // Otherwise that record would rotate again, and its trace would get no root span.\n const old = this.ambient;\n this.ambient = mintAmbient(reason);\n const next = toTraceContext(this.ambient);\n this.finish(old);\n return next;\n }\n\n /**\n * Ends the ambient trace's root span, once. Later records can still use the trace. The exit\n * flush calls this, because a closing document has no later rotation.\n */\n end(): void {\n this.finish(this.ambient);\n }\n\n /**\n * Ends a trace's root span, once.\n * @param ambient The trace to end.\n */\n private finish(ambient: AmbientTrace): void {\n if (ambient.ended) {\n return;\n }\n\n ambient.ended = true;\n this.spans?.onEnd({\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n reason: ambient.reason,\n startedAt: ambient.startedAt,\n endedAt: Date.now(),\n });\n }\n\n /**\n * Generates W3C traceparent headers with the registered OpenTelemetry propagators. Falls\n * back to the ambient trace when OpenTelemetry provides no traceparent.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n return this.trace(false).headers;\n }\n\n /**\n * Generates the headers for one request from the network capture. With spans on, the\n * traceparent names a new client span of the ambient trace.\n * @returns The headers, and the client span that the library records.\n */\n request(): RequestTrace {\n return this.trace(true);\n }\n\n /**\n * Generates the trace headers.\n * @param client True to name a new client span in the traceparent.\n * @returns The headers, and the client span that the library records.\n */\n private trace(client: boolean): RequestTrace {\n const carrier: Record<string, string> = {};\n const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not add the OpenTelemetry headers.\",\n () => {\n otel.propagation.inject(otel.context.active(), carrier);\n },\n );\n }\n if (carrier[TRACEPARENT_HEADER]) {\n return { headers: carrier };\n }\n\n // The peer keeps its own spans, so the library records no span for one of the peer's traces.\n const fromOtel = this.activeSpanContext();\n const ctx = fromOtel ?? this.ambientContext();\n const spans = fromOtel ? undefined : this.spans;\n\n if (!spans?.enabled()) {\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, ctx.spanId, ctx.traceFlags);\n return { headers: carrier };\n }\n\n // Clear the sampled flag on a trace that sampling drops, so a downstream service drops its\n // spans too. The whole trace stays or goes.\n const kept = spans.keeps(ctx.traceId);\n const flags = kept ? ctx.traceFlags : ctx.traceFlags & ~TRACE_FLAGS_SAMPLED;\n const spanId = client ? newSpanId() : ctx.spanId;\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, spanId, flags);\n\n if (!client || !kept) {\n return { headers: carrier };\n }\n\n return { headers: carrier, span: { traceId: ctx.traceId, spanId, parentSpanId: ctx.spanId } };\n }\n}\n","// src/core/measure.ts\n//\n// Times one operation with named phases. Every phase and the total go into duration histograms.\n// With a span, the operation is that span, with one child span per phase. measure() times a\n// single function call with one.\n\nimport { METRIC_DEFAULT_BOUNDARIES } from \"../constants\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport { type ClientSpan, newSpanId } from \"../utils/tracing\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { SpanData } from \"./spans\";\n\n/** Total duration of each measure, in milliseconds. */\nconst TOTAL_DURATION: InstrumentDef = {\n name: \"ui.measure.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Duration of each phase, in milliseconds. */\nconst PHASE_DURATION: InstrumentDef = {\n name: \"ui.measure.phase.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Where the values of one measure go. */\nexport interface MeasureSinks {\n /** Adds a value to a histogram. */\n metric(def: InstrumentDef, value: number, attributes: MetricAttributes): void;\n /** Records one span. */\n span(span: SpanData): void;\n}\n\n/**\n * Starts the clock for one operation.\n * @param name Operation name. A JavaScript caller can pass any type.\n * @param attributes Copy of the app's attribute set.\n * @param span The operation's span, or undefined when spans are off or the trace was dropped.\n * @param sinks Where the values go.\n * @returns The operation's handle.\n */\nexport function createMeasure(\n name: unknown,\n attributes: MetricAttributes,\n span: ClientSpan | undefined,\n sinks: MeasureSinks,\n): Measure {\n // The record builder needs text.\n const label = String(name);\n const startMs = Date.now();\n const startedAt = performance.now();\n let open: { name: string; at: number } | undefined;\n let ended = false;\n\n // The histograms use the monotonic clock, but a span needs epoch times.\n const epoch = (at: number): number => startMs + at - startedAt;\n\n const closePhase = (now: number, error: boolean): void => {\n if (!open) {\n return;\n }\n\n sinks.metric(PHASE_DURATION, now - open.at, {\n ...attributes,\n \"measure.name\": label,\n \"measure.phase\": open.name,\n });\n if (span) {\n sinks.span({\n name: open.name,\n kind: \"internal\",\n traceId: span.traceId,\n spanId: newSpanId(),\n parentSpanId: span.spanId,\n startMs: epoch(open.at),\n endMs: epoch(now),\n error,\n attributes: { \"measure.name\": label },\n });\n }\n open = undefined;\n };\n\n return {\n phase: (next: unknown) => {\n if (ended) {\n return;\n }\n\n const now = performance.now();\n closePhase(now, false);\n open = { name: String(next), at: now };\n },\n end: (outcome = \"ok\") => {\n if (ended) {\n return;\n }\n\n ended = true;\n const now = performance.now();\n const error = outcome === \"error\";\n closePhase(now, error);\n const fields = { ...attributes, \"measure.outcome\": outcome };\n sinks.metric(TOTAL_DURATION, now - startedAt, { ...fields, \"measure.name\": label });\n if (span) {\n sinks.span({\n ...span,\n name: label,\n kind: \"internal\",\n startMs,\n endMs: epoch(now),\n error,\n attributes: fields,\n });\n }\n },\n };\n}\n\n/**\n * Calls a function and ends the measure when the call returns. If the result has a `then`\n * function, the measure ends when it settles. A throw or a rejection ends it with the outcome\n * \"error\" and goes to the caller.\n * @param handle The measure of the call.\n * @param fn The app's function.\n * @param diagnostics Reports a result whose `then` can't be read.\n * @returns Whatever fn returned, or the result of its then() call.\n */\nexport function measureCall<T>(handle: Measure, fn: () => T, diagnostics: Diagnostics): T {\n // finally sees a throw from fn or from the result's then(), so the error goes to the caller\n // unchanged and the measure still ends.\n let outcome: string | undefined = \"error\";\n try {\n const result = fn();\n // A hostile result can throw from its then getter. The measure then ends now.\n const then = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read what the function of the measure returned. The measure ends now.\",\n (): unknown => (result as { then?: unknown } | null | undefined)?.then,\n );\n\n if (typeof then !== \"function\") {\n outcome = \"ok\";\n return result;\n }\n\n // Hand back the chained result, so a rejection has exactly one owner: the caller.\n const chained = (then as PromiseLike<unknown>[\"then\"]).call(\n result,\n (value) => {\n handle.end();\n return value;\n },\n (error: unknown) => {\n handle.end(\"error\");\n throw error;\n },\n ) as T;\n // The settle ends the measure from here.\n outcome = undefined;\n return chained;\n } finally {\n if (outcome !== undefined) {\n handle.end(outcome);\n }\n }\n}\n","// src/core/meter.ts\n//\n// Sums counter and histogram values and keeps the last gauge value in memory. At every interval\n// it emits one point per instrument and attribute set, so a thousand adds produce one record.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_METRIC_OVERFLOW,\n ATTR_PAGE_URL,\n DEFAULT_METRIC_UNIT,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n} from \"../constants\";\nimport type { MetricsOptions } from \"../models/config\";\nimport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n MetricAttributes,\n} from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One attribute set's sums in the current interval. */\ninterface Series {\n /** The series' attribute set. */\n attributes: MetricAttributes;\n /** Number of values. */\n count: number;\n /** Sum of the values. */\n sum: number;\n /** Smallest value. */\n min: number;\n /** Largest value. */\n max: number;\n /** Last value. A gauge sends it. */\n last: number;\n /** Count per histogram bucket. A counter and a gauge have none. */\n buckets: number[];\n}\n\n/** One instrument's series in the current interval. */\ninterface Instrument {\n /** Definition taken from the interval's first value. */\n def: InstrumentDef;\n /** Series by attribute set key. */\n series: Map<string, Series>;\n}\n\n/** Key of the overflow series. An attribute set's key is JSON text, which starts with \"{\". */\nconst OVERFLOW_KEY = \"overflow\";\n\n/** Keys the record builder sets. It overwrites a call attribute with the same name. */\nconst RECORD_KEYS = new Set<string>([\n ATTR_LOG_TYPE,\n ATTR_LOG_SEQ,\n ATTR_APP_NAMESPACE,\n ATTR_PAGE_URL,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n]);\n\n/**\n * Keeps the string, finite number and boolean attributes, in key order. Two calls with the same\n * set in a different key order then share one series.\n * @param attributes The call's attribute set.\n * @returns The clean attribute set.\n */\nfunction cleanAttributes(attributes: MetricAttributes = {}): MetricAttributes {\n const clean: MetricAttributes = {};\n\n for (const key of Object.keys(attributes).sort()) {\n // The builder replaces the metric fields, so keeping one would give every value its own\n // series with the same output. An app's other metric. keys stay reserved for the library.\n if (key.startsWith(\"metric.\") || RECORD_KEYS.has(key)) {\n continue;\n }\n\n const value: unknown = attributes[key];\n const finite = typeof value === \"number\" && Number.isFinite(value);\n if (typeof value === \"string\" || typeof value === \"boolean\" || finite) {\n clean[key] = value;\n }\n }\n\n return clean;\n}\n\n/**\n * Copies a list of boundaries by index, so a custom iterator on the app's array has no effect.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. null means no limit.\n * @returns A plain array with at most one value more than the limit, or null if the value\n * isn't an array.\n */\nfunction copyBounds(bounds: unknown, limit: number | null): unknown[] | null {\n if (!Array.isArray(bounds)) {\n return null;\n }\n\n // One more than the limit, so isAscending rejects a list that is too long.\n const count = limit === null ? bounds.length : Math.min(bounds.length, limit + 1);\n return Array.from({ length: count }, (_unused, i): unknown => bounds[i]);\n}\n\n/**\n * Checks a list of histogram boundaries.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. null means no limit.\n * @returns True for finite numbers in ascending order, no more of them than the limit.\n */\nfunction isAscending(bounds: unknown, limit: number | null): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n (limit === null || bounds.length <= limit) &&\n bounds.every(\n (bound: unknown, i) =>\n typeof bound === \"number\" &&\n Number.isFinite(bound) &&\n (i === 0 || bound > (bounds[i - 1] as number)),\n )\n );\n}\n\n/**\n * Builds the metric fields for one point. The call's attributes stay out.\n * @param def The instrument's definition.\n * @param series The attribute set's sums.\n * @param start Start of the interval, in Unix nanoseconds.\n * @returns The point's metric fields.\n */\nfunction fieldsOf(def: InstrumentDef, series: Series, start: string): Record<string, unknown> {\n const point: Record<string, unknown> = {\n \"metric.name\": def.name,\n \"metric.unit\": def.unit,\n \"metric.type\": def.kind,\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: Object.keys(series.attributes),\n };\n\n if (def.kind !== \"histogram\") {\n point[\"metric.value\"] = def.kind === \"gauge\" ? series.last : series.sum;\n return point;\n }\n\n return {\n ...point,\n [METRIC_KEYS.count]: series.count,\n [METRIC_KEYS.sum]: series.sum,\n [METRIC_KEYS.min]: series.min,\n [METRIC_KEYS.max]: series.max,\n [METRIC_KEYS.bounds]: def.boundaries,\n [METRIC_KEYS.buckets]: series.buckets,\n };\n}\n\n/** Adds a value to one of the runtime's instruments. */\nexport type RecordMetric = (\n def: InstrumentDef,\n value: number,\n attributes?: MetricAttributes,\n) => void;\n\n/** Called with whatever reading an options object threw. */\nexport type OptionsFault = (error: unknown) => void;\n\n/**\n * Reads an instrument's options. A getter or a Proxy trap on them can throw, and a JavaScript\n * caller can pass null.\n * @param options Options from the app.\n * @param fault Reports options that couldn't be read.\n * @returns The unit and the boundaries. Anything the app didn't set is undefined.\n */\nfunction readOptions(\n options: HistogramOptions,\n fault: OptionsFault,\n): { unit: string | undefined; boundaries: readonly number[] | undefined } {\n try {\n return { unit: options.unit, boundaries: options.boundaries };\n } catch (error) {\n fault(error);\n return { unit: undefined, boundaries: undefined };\n }\n}\n\n/**\n * Builds the definition of an instrument with one value per point.\n * @param name Metric name.\n * @param kind \"counter\" or \"gauge\".\n * @param options Unit for the values.\n * @param fault Reports options that couldn't be read.\n * @returns The definition.\n */\nfunction scalarDef(\n name: string,\n kind: \"counter\" | \"gauge\",\n options: InstrumentOptions,\n fault: OptionsFault,\n): InstrumentDef {\n return {\n name,\n kind,\n unit: readOptions(options, fault).unit ?? DEFAULT_METRIC_UNIT,\n boundaries: [],\n };\n}\n\n/**\n * Creates a counter handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The counter.\n */\nexport function makeCounter(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Counter {\n const def = scalarDef(name, \"counter\", options, fault);\n\n return {\n add: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Creates a gauge handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values.\n * @param record Sets the instrument's value.\n * @param fault Reports options that couldn't be read.\n * @returns The gauge.\n */\nexport function makeGauge(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Gauge {\n const def = scalarDef(name, \"gauge\", options, fault);\n\n return {\n set: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Creates a histogram handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values, and the bucket boundaries.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The histogram.\n */\nexport function makeHistogram(\n name: string,\n options: HistogramOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Histogram {\n const { unit, boundaries } = readOptions(options, fault);\n const def: InstrumentDef = {\n name,\n kind: \"histogram\",\n unit: unit ?? DEFAULT_METRIC_UNIT,\n boundaries: boundaries ?? METRIC_DEFAULT_BOUNDARIES,\n fromApp: boundaries !== undefined,\n };\n\n return {\n record: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/** Sums the counter and histogram values and keeps the gauge values of one interval. */\nexport class Meter {\n /** Instruments with a value in the current interval. */\n private readonly instruments = new Map<string, Instrument>();\n\n /** Timer for the current interval. Runs only while a value is waiting. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Time of the interval's first value, in epoch milliseconds. */\n private startedAt = 0;\n\n /**\n * @param intervalMs Returns the interval length, in milliseconds.\n * @param emit Builds and sends the record for one point from the call attributes and the\n * metric fields.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly intervalMs: () => number,\n private readonly emit: (\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ) => void,\n private readonly diagnostics: Diagnostics,\n private readonly policy: Omit<MetricsOptions, \"intervalMs\"> = {\n maxSeries: 100,\n maxInstruments: 1000,\n maxHistogramBoundaries: 50,\n },\n ) {}\n\n /**\n * Adds a value to the series for its attribute set. Never throws into the app.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // NaN and Infinity become null in JSON, and a negative add breaks a counter's sum.\n if (!Number.isFinite(value) || (def.kind === \"counter\" && value < 0)) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The value of the metric ${def.name} is not valid. The library dropped it.`,\n { \"metric.name\": def.name },\n );\n return;\n }\n\n // A getter or a Proxy trap on the attributes can throw.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n `The library could not read the attributes of the metric ${def.name}.`,\n () => {\n const instrument = this.instrumentOf(def);\n if (instrument) {\n this.add(instrument, value, cleanAttributes(attributes));\n this.arm();\n }\n },\n );\n }\n\n /** Sends one point per series in the interval, then starts a new interval. */\n collect(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n const start = `${String(this.startedAt)}000000`;\n const instruments = [...this.instruments.values()];\n this.instruments.clear();\n\n for (const { def, series } of instruments) {\n for (const one of series.values()) {\n this.emit(def.name, one.attributes, fieldsOf(def, one, start));\n }\n }\n }\n\n /**\n * Finds the interval's instrument. The first value of the interval sets its definition.\n * @param def The call's definition.\n * @returns The instrument, or null when the name has another kind.\n */\n private instrumentOf(def: InstrumentDef): Instrument | null {\n const found = this.instruments.get(def.name);\n\n if (found) {\n if (found.def.kind === def.kind) {\n return found;\n }\n\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The metric ${def.name} is a ${found.def.kind} and a ${def.kind}. The library dropped the value.`,\n { \"metric.name\": def.name },\n );\n return null;\n }\n\n const { maxInstruments } = this.policy;\n if (maxInstruments !== null && this.instruments.size >= maxInstruments) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return null;\n }\n // Copy before the check, so a later change to the app's array can't change the buckets. The\n // limit is for the app's lists. The library's own lists always fit, or a low limit would\n // report every histogram without custom boundaries.\n const limit = def.fromApp === true ? this.policy.maxHistogramBoundaries : null;\n const copy = copyBounds(def.boundaries, limit);\n const valid = isAscending(copy, limit);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`,\n );\n }\n\n const instrument: Instrument = {\n def: { ...def, boundaries: valid ? copy : [...METRIC_DEFAULT_BOUNDARIES] },\n series: new Map(),\n };\n this.instruments.set(def.name, instrument);\n return instrument;\n }\n\n /**\n * Adds a value to an attribute set's series.\n * @param instrument The value's instrument.\n * @param value Value to add.\n * @param attributes Clean attribute set.\n */\n private add(instrument: Instrument, value: number, attributes: MetricAttributes): void {\n let key = JSON.stringify(attributes);\n let series = instrument.series.get(key);\n let set = attributes;\n\n // Cap the series, or a storm of attribute sets grows memory and the payload without limit.\n const { maxSeries } = this.policy;\n if (!series && maxSeries !== null && instrument.series.size >= maxSeries) {\n key = OVERFLOW_KEY;\n series = instrument.series.get(key);\n set = { [ATTR_METRIC_OVERFLOW]: true };\n }\n\n if (!series) {\n // A histogram has one more bucket than it has boundaries. The last has no upper bound.\n const size = instrument.def.kind === \"histogram\" ? instrument.def.boundaries.length + 1 : 0;\n const buckets = new Array<number>(size).fill(0);\n series = { attributes: set, count: 0, sum: 0, min: value, max: value, last: value, buckets };\n instrument.series.set(key, series);\n }\n\n series.count += 1;\n series.sum += value;\n series.min = Math.min(series.min, value);\n series.max = Math.max(series.max, value);\n series.last = value;\n\n if (series.buckets.length > 0) {\n const index = instrument.def.boundaries.findIndex((bound) => value <= bound);\n series.buckets[index === -1 ? series.buckets.length - 1 : index] += 1;\n }\n }\n\n /** Starts the interval's timer on its first value. An idle meter has no timer. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n this.startedAt = Date.now();\n this.timer = setTimeout(() => {\n this.collect();\n }, this.intervalMs());\n unrefTimer(this.timer);\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { LEVEL_ORDER, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConsole } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { hasOwn } from \"./guards\";\nimport { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, sanitize } from \"./sanitize\";\n\n/** Maps each log level to its console method. */\nconst METHOD: Record<LogLevel, \"debug\" | \"info\" | \"warn\" | \"error\"> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warn\",\n ERROR: \"error\",\n FATAL: \"error\",\n};\n\n/** Mirrors log records directly to browser or Node console methods based on severity. */\nexport class ConsoleSink {\n /**\n * @param settings Console level and styles. A null level prints nothing.\n * @param diagnostics Diagnostics reporter.\n * @param limits Size limits for the printed payload. Same as the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\n ) {}\n\n /**\n * Replaces the console level and styles.\n * @param settings Console level and styles. A null level prints nothing.\n */\n update(settings: ResolvedConsole): void {\n this.settings = settings;\n }\n\n /**\n * Checks whether a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.settings.level];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\n return;\n }\n // Guard against a missing console. Some worker realms don't define it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n // Guard against a loop: a host console wrapper can call the logger, which would print again.\n // The console capture also records inside this scope, and its line is already in devtools.\n if (isLibraryConsole()) {\n return;\n }\n\n // Pass the namespace as a %s argument, so a %o or %c in the namespace prints as text.\n // The last %c resets the style, so the message prints in the default style.\n const prefix = `%c[%s]%c[${level}]%c`;\n const { styles } = this.settings;\n const method = METHOD[level];\n\n // A host can replace console methods with ones that throw. The guard keeps that error\n // from breaking the caller's log call.\n this.diagnostics.guard(\n \"handler.threw\",\n `The library could not print to console.${method}.`,\n () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to every logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, this.limits, this.diagnostics));\n }\n\n // The console capture skips calls in this scope, so it doesn't record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\n });\n },\n );\n }\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers that order each context's records. Timestamps can't\n// order records, because a clock can step and two records can share a millisecond. Each\n// context has its own counter, because a shared counter shows gaps and a gap looks like a\n// lost record. The counter never resets, because a reset would repeat numbers in one context.\n\n/** Monotonic sequence counter establishing total record ordering within an execution context. */\nexport class Sequence {\n /** Last emitted sequence counter value. */\n private value = 0;\n\n /**\n * Increments and returns the next monotonic sequence number starting at 1.\n * @returns Next sequence number.\n */\n next(): number {\n return ++this.value;\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// A ring buffer that keeps a bounded, time-ordered trail of recent user and system events.\n// Breadcrumbs are never sent as records of their own. They reach the backend inside the\n// payload of an error record. Nothing in this file throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category of a breadcrumb event. */\nexport type BreadcrumbCategory =\n | \"log\"\n | \"action\"\n | \"event\"\n | \"click\"\n | \"navigation\"\n | \"http\"\n | \"console\"\n | \"frame\"\n | \"profile\"\n | \"custom\";\n\n/** Short summary of one event, kept so an error record can carry it. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Category of the event. */\n category: BreadcrumbCategory;\n /** Human-readable description of the event. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Fixed-size ring buffer that keeps recent breadcrumbs in time order. */\nexport class BreadcrumbBuffer {\n /** The ring's backing array. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * True once the pointer has wrapped past the capacity. The pointer alone can't tell an\n * empty ring from one that wrapped back to index 0.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs the buffer keeps. */\n private capacity: number;\n\n /**\n * @param capacity Maximum number of breadcrumbs. 0 turns the buffer off. Any other value\n * below the minimum size is raised to it.\n */\n constructor(capacity: number) {\n this.capacity = capacity === 0 ? 0 : Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Changes the capacity, keeping the most recent breadcrumbs that fit.\n * @param capacity New capacity. Pass 0 to drop the stored breadcrumbs and turn the buffer off.\n */\n resize(capacity: number): void {\n const recent = this.snapshot().slice(-capacity);\n this.capacity = capacity;\n this.buffer = new Array<Breadcrumb | undefined>(capacity);\n this.pointer = 0;\n this.filled = false;\n if (capacity) {\n for (const crumb of recent) {\n this.push(crumb);\n }\n }\n }\n\n /**\n * Adds a breadcrumb. When the buffer is full, it overwrites the oldest one.\n * @param crumb Breadcrumb to add.\n */\n push(crumb: Breadcrumb): void {\n if (this.capacity === 0) {\n return;\n }\n this.buffer[this.pointer] = crumb;\n this.pointer = (this.pointer + 1) % this.capacity;\n if (this.pointer === 0) {\n this.filled = true;\n }\n }\n\n /**\n * Keeps only the breadcrumbs that pass the test, in their order.\n * @param keep Returns true for a breadcrumb to keep.\n */\n retain(keep: (crumb: Breadcrumb) => boolean): void {\n const kept = this.snapshot().filter(keep);\n this.clear();\n for (const crumb of kept) {\n this.push(crumb);\n }\n }\n\n /** Removes all breadcrumbs, so a new session never carries the previous user's trail. */\n clear(): void {\n this.buffer.fill(undefined);\n this.pointer = 0;\n this.filled = false;\n }\n\n /**\n * Returns all stored breadcrumbs, oldest to newest.\n * @returns The breadcrumbs in time order.\n */\n snapshot(): Breadcrumb[] {\n const ordered = this.filled\n ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)]\n : this.buffer.slice(0, this.pointer);\n return ordered.filter((crumb): crumb is Breadcrumb => crumb !== undefined);\n }\n}\n","// src/core/context.ts\n//\n// Stores the ambient context attributes that the logger merges into every later record.\n// Keep the store per instance, not at module level: all runtimes in a realm share a module Map.\n\n/** Key-value store for ambient context attributes attached to log records. */\nexport class ContextStore {\n /** Backing store mapping attribute keys to raw values. */\n private readonly map = new Map<string, unknown>();\n\n /**\n * Merges attributes into the ambient context. null removes a key, and undefined keeps the\n * current value, as in configure().\n * @param values Attributes to merge.\n */\n merge(values: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(values)) {\n if (value === null) {\n this.map.delete(key);\n } else if (value !== undefined) {\n this.map.set(key, value);\n }\n }\n }\n\n /**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to remove.\n */\n remove(key: string): void {\n this.map.delete(key);\n }\n\n /** Removes all ambient context attributes. */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Returns a copy of all ambient context attributes, so a merge target or a sanitizer\n * can't change the store.\n * @returns Plain object with the stored key-value pairs.\n */\n getAll(): Record<string, unknown> {\n return Object.fromEntries(this.map);\n }\n}\n","// src/core/debug-buffer.ts\n//\n// Keeps the recent records that minLevel or sampling dropped. An error record from this context\n// sends them out first, so they show what happened before the error.\n\nimport { ATTR_DEBUG_BUFFER } from \"../constants\";\nimport type { DebugBufferOptions } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One kept record, with the time the buffer took it. */\ninterface Kept {\n /** Epoch time in milliseconds when the buffer took the record. */\n at: number;\n /** Built record. The privacy hooks have already run on it. */\n record: LogRecord;\n}\n\n/** Bounded list of the records that were dropped by level or by sampling. */\nexport class DebugBuffer {\n /** Kept records, oldest first. Can grow to twice maxRecords between trims. */\n private kept: Kept[] = [];\n\n /**\n * @param policy Returns the current settings. A later configure() can change them.\n */\n constructor(private readonly policy: () => DebugBufferOptions) {}\n\n /**\n * Keeps a record. When the buffer is full, the oldest record goes first.\n * @param record Built record. The privacy hooks have already run on it.\n */\n push(record: LogRecord): void {\n const { enabled, maxRecords } = this.policy();\n if (!enabled) {\n return;\n }\n\n this.kept.push({ at: Date.now(), record });\n // Trim in steps. Trimming on every push would copy the whole list each time.\n if (this.kept.length >= maxRecords * 2) {\n this.kept = this.kept.slice(-maxRecords);\n }\n }\n\n /**\n * Takes the kept records that aren't too old and empties the buffer.\n * @returns The records, oldest first, each with `uiobs.debug_buffer: true`.\n */\n drain(): LogRecord[] {\n const kept = this.live();\n this.kept = [];\n\n return kept.map(({ record }) => ({\n ...record,\n attributes: { ...record.attributes, [ATTR_DEBUG_BUFFER]: true },\n }));\n }\n\n /**\n * Returns the kept records without taking them.\n * @returns The records, oldest first.\n */\n snapshot(): LogRecord[] {\n return this.live().map(({ record }) => record);\n }\n\n /**\n * Returns the kept records that the current settings allow. A disabled buffer empties itself.\n * @returns The records, oldest first.\n */\n private live(): Kept[] {\n const { enabled, maxRecords, maxAgeMs } = this.policy();\n if (!enabled) {\n this.kept = [];\n return [];\n }\n\n const oldest = maxAgeMs === null ? -Infinity : Date.now() - maxAgeMs;\n\n return this.kept.slice(-maxRecords).filter((entry) => entry.at >= oldest);\n }\n\n /** Removes every kept record, so nothing from an old session or identity goes out. */\n clear(): void {\n this.kept = [];\n }\n}\n","// src/core/diagnostics.ts\n//\n// Reports the library's internal errors. Emits are rate limited, but every event is counted.\n\nimport { DIAGNOSTIC_THROTTLE_MS, LIBRARY_LOG_PREFIX } from \"../constants\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\n\n/** Closed set of diagnostic event codes emitted by library subsystems. */\nexport type DiagnosticCode =\n | \"config.locked\"\n | \"security.rotated\"\n | \"security.rotation_failed\"\n | \"security.context_mismatch\"\n | \"record.dropped_during_rotation\"\n | \"bus.rejected_message\"\n | \"config.invalid\"\n | \"config.reconfigured\"\n | \"record.sanitize_failed\"\n | \"record.truncated\"\n | \"record.dropped_by_level\"\n | \"record.dropped_by_sampling\"\n | \"record.dropped_by_ceiling\"\n | \"record.dropped_by_processor\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_full\"\n | \"record.dropped_malformed\"\n | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\n | \"journey.expired\"\n | \"journey.adopted\"\n | \"journey.token_too_large\"\n | \"trace.otel_failed\"\n | \"bus.role_resolved\"\n | \"bus.no_owner\"\n | \"bus.handshake_timeout\"\n | \"bus.untrusted_origin\"\n | \"bus.send_failed\"\n | \"bus.protocol_mismatch\"\n | \"transport.http_error\"\n | \"transport.timeout\"\n | \"transport.batch_split\"\n | \"transport.partial_success\"\n | \"transport.throttled\"\n | \"transport.dropped_permanent\"\n | \"transport.rejected_credentials\"\n | \"transport.serialize_failed\"\n | \"storage.unavailable\"\n | \"storage.degraded\"\n | \"storage.quota_exceeded\"\n | \"storage.evicted\"\n | \"storage.dead_lettered\"\n | \"pipeline.crashed\"\n | \"capture.install_failed\"\n | \"capture.rate_limited\"\n | \"capture.header_failed\"\n | \"capture.trace_header_kept\"\n | \"capture.record_failed\"\n | \"capture.transport_request\"\n | \"openfin.unavailable\"\n | \"platform.api_blocked\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Human-readable description. */\n message: string;\n /** Structured context metadata. */\n detail?: Record<string, unknown>;\n /** Caught error instance or reason. */\n cause?: unknown;\n /** Event timestamp in epoch milliseconds. */\n at: number;\n /** Total count of this code since startup, including rate-limited occurrences. */\n count: number;\n}\n\n/** Consumer callback for receiving rate-limited diagnostic events. */\nexport type DiagnosticHandler = (event: DiagnosticEvent) => void;\n\n/** Reports internal errors. Dispatch is rate limited, but every event is counted. */\nexport class Diagnostics {\n /** Running occurrence counts per diagnostic code. */\n private readonly counters = new Map<DiagnosticCode, number>();\n\n /** Timestamp of the last emitted event per code, in epoch milliseconds. */\n private readonly lastEmitted = new Map<DiagnosticCode, number>();\n\n /**\n * @param handler Optional listener for diagnostic events.\n * @param throttleMs Minimum time in milliseconds between emitted events for one code.\n * @param consoleFallback True to print a fixed warning if the diagnostic handler throws.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private throttleMs = DIAGNOSTIC_THROTTLE_MS,\n private consoleFallback = false,\n ) {}\n\n /**\n * Changes the report interval and the console fallback rule.\n * @param throttleMs Minimum wait between reports of one code, in milliseconds.\n * @param consoleFallback True to print a fixed warning if the handler throws.\n */\n setPolicy(throttleMs: number, consoleFallback: boolean): void {\n this.throttleMs = throttleMs;\n this.consoleFallback = consoleFallback;\n }\n\n /**\n * Replaces or removes the active diagnostic event handler.\n * @param handler New diagnostic event handler.\n */\n setHandler(handler?: DiagnosticHandler): void {\n this.handler = handler;\n }\n\n /**\n * Increments the count for a code without calling the handler.\n * @param code Diagnostic code to increment.\n * @param by Amount to add.\n * @returns New total for the code.\n */\n count(code: DiagnosticCode, by = 1): number {\n const total = (this.counters.get(code) ?? 0) + by;\n this.counters.set(code, total);\n return total;\n }\n\n /**\n * Bumps the counter for the code and, once the throttle window has passed, sends the event\n * to the handler. Never throws.\n * @param code Diagnostic code.\n * @param message Event description.\n * @param detail Optional structured metadata.\n * @param cause Caught error instance or reason.\n * @returns False if the throttle dropped the event.\n */\n report(\n code: DiagnosticCode,\n message: string,\n detail?: Record<string, unknown>,\n cause?: unknown,\n ): boolean {\n const count = this.count(code);\n const now = Date.now();\n const last = this.lastEmitted.get(code) ?? 0;\n if (now - last < this.throttleMs) {\n return false;\n }\n this.lastEmitted.set(code, now);\n\n const event: DiagnosticEvent = {\n code,\n message,\n detail,\n cause,\n at: now,\n count,\n };\n\n const { handler } = this;\n\n if (!handler) {\n return true;\n }\n try {\n // Console capture skips anything the handler logs inside this scope. Without the scope,\n // the line becomes a record, and a failed send of that record raises a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\n } catch (_handlerError) {\n // Bump the counter directly. Calling report() here would recurse when the handler throws.\n this.count(\"handler.threw\");\n if (this.consoleFallback && typeof console !== \"undefined\") {\n // Console capture skips calls made in this scope.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- Fallback sink when diagnostic handler throws.\n console.warn(`${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`);\n });\n }\n }\n\n return true;\n }\n\n /**\n * Runs a synchronous function and reports anything it throws to diagnostics.\n * @param code Diagnostic code to report on throw.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Function to run.\n * @returns The function's return value, or undefined if it threw.\n */\n guard<T>(code: DiagnosticCode, message: string, fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Runs an asynchronous function and reports a rejected promise to diagnostics.\n * @param code Diagnostic code to report on rejection.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Async function to run.\n * @returns Promise that resolves to the return value, or to undefined on rejection.\n */\n async guardAsync<T>(\n code: DiagnosticCode,\n message: string,\n fn: () => Promise<T>,\n ): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Returns a copy of the cumulative diagnostic counts since initialization.\n * @returns Map of diagnostic codes to occurrence counts.\n */\n snapshot(): Record<string, number> {\n return Object.fromEntries(this.counters);\n }\n}\n","// src/core/drops.ts\n//\n// Collects lost records into onDrop summaries and sends one summary per reason after the\n// current task. A storm of losses then makes one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value once, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and hands the onDrop hook one summary per reason. */\nexport class DropReporter {\n /** Summaries waiting for the end of the task, one per reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask is waiting to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss the hook itself causes isn't reported again. */\n private reporting = false;\n\n /** Lost records since the start, per reason. getHealth() reports them. */\n private readonly lost: Partial<Record<LossReason, number>> = {};\n\n /**\n * @param config Active configuration. `onDrop` is read from it on every call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Counts lost records, and adds them to the summary for their reason. The summary needs an\n * onDrop hook.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n * @param count Number of lost records when the caller can't name them, for example after an\n * OTLP partial rejection. Defaults to the length of `records`.\n */\n add(\n reason: LossReason,\n records: readonly LogRecord[],\n batchIds: readonly string[] = [],\n count = records.length,\n ): void {\n // Count first, so getHealth() shows a loss also without an onDrop hook.\n if (count > 0) {\n this.lost[reason] = (this.lost[reason] ?? 0) + count;\n }\n\n // A hook that logs can fill a buffer again, and reporting that loss would start a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing, and a corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += count;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt: null, or missing its attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /**\n * Returns the lost record counts since the start.\n * @returns A copy of the count for each reason. A reason with no loss has no key.\n */\n counts(): Partial<Record<LossReason, number>> {\n return { ...this.lost };\n }\n\n /** Hands every waiting summary to the hook. A hook that throws doesn't stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip any request or console line the hook makes. A captured line\n // would become a record, and that record could evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// Holds records while the runtime can't deliver them. A full buffer keeps its first records,\n// because the first error of a failed startup is usually the cause, and drops the oldest record\n// after them. An action is an audit fact, so actions have their own lists with their own cap,\n// and a storm of other records can't push one out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, HOLD_BUFFER_HEAD_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One held record. The arrival number puts the lists back into one order. */\ninterface Held {\n /** The record. */\n record: LogRecord;\n /** Counts up with every push. */\n arrival: number;\n}\n\n/** The held records of one kind, oldest first in each list. */\ninterface Kind {\n /** The first HOLD_BUFFER_HEAD_RECORDS records. A full buffer never drops one of them. */\n head: Held[];\n /** Every later record. A full buffer drops the oldest of them. */\n tail: Held[];\n}\n\n/** Holds records and returns them in arrival order. Each kind keeps its head when it is full. */\nexport class HoldBuffer {\n /** Held actions. */\n private actions: Kind = { head: [], tail: [] };\n\n /** Held records of every other kind. */\n private others: Kind = { head: [], tail: [] };\n\n /** Arrival number of the next record. */\n private arrivals = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.inOrder();\n }\n\n /** Number of held records. */\n get length(): number {\n const { actions, others } = this;\n return actions.head.length + actions.tail.length + others.head.length + others.tail.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind after the head.\n * @param record Record to hold.\n * @param maxRecords Cap on records that aren't actions. The caller reads it from the config\n * on each push, because a record can arrive before the app's configure() sets the cap.\n */\n push(record: LogRecord, maxRecords: number): void {\n const action = isActionRecord(record);\n const kind = action ? this.actions : this.others;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : maxRecords;\n const held = { record, arrival: this.arrivals };\n this.arrivals += 1;\n\n if (kind.head.length < HOLD_BUFFER_HEAD_RECORDS) {\n kind.head.push(held);\n return;\n }\n\n kind.tail.push(held);\n\n if (kind.head.length + kind.tail.length > cap) {\n // The tail holds at least the record just pushed, so it always has a front to drop. It is\n // shift() and not splice(0, 1), because splice moves the whole tail on every drop of a storm.\n const dropped = kind.tail[0];\n kind.tail.shift();\n this.onDrop(dropped.record);\n }\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.inOrder();\n this.actions = { head: [], tail: [] };\n this.others = { head: [], tail: [] };\n this.arrivals = 0;\n return records;\n }\n\n /**\n * Builds one list from the four. Each list is already sorted, so the sort only merges runs.\n * @returns The held records in arrival order.\n */\n private inOrder(): LogRecord[] {\n const { actions, others } = this;\n return [...actions.head, ...actions.tail, ...others.head, ...others.tail]\n .sort((first, second) => first.arrival - second.arrival)\n .map((held) => held.record);\n }\n}\n","// src/core/record.ts\n//\n// Builds structured log records from ambient context, journey data, trace context and\n// resource attributes. Never throws to the caller.\n// The builder caches the resource block, so call invalidateResource after its inputs change.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_ATTRIBUTES_BYTES,\n ATTR_ATTRIBUTES_DROPPED,\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_SANITIZE_FAILED,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_METRIC,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n METRIC_NAMESPACE,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_CONTEXT_ID,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_HOST_PLATFORM,\n RESOURCE_OPENFIN_NAME,\n RESOURCE_OPENFIN_UUID,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n RESOURCE_SESSION_ID,\n RESOURCE_TAB_ID,\n RESOURCE_TELEMETRY_SDK_LANGUAGE,\n RESOURCE_TELEMETRY_SDK_NAME,\n RESOURCE_TELEMETRY_SDK_VERSION,\n SEVERITY_NUMBER,\n SPAN_KEYS,\n TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n TRACE_NAMESPACE,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport {\n isLogLevel,\n isLogRecord,\n type LogLevel,\n type LogRecord,\n type LogType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { type SanitizeLimits, sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceContext, TraceEngine } from \"../utils/tracing\";\nimport { REFUSE_RECORDS } from \"./config\";\nimport type { ContextStore } from \"./context\";\nimport type { DebugBuffer } from \"./debug-buffer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { Journey, JourneyEngine } from \"./journey\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { levelFor, shouldSample, shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields, which an oversized error record keeps. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps as redact left them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Ambient context store. */\n context: ContextStore;\n /** Active journey engine. */\n journey: JourneyEngine;\n /** Distributed tracing engine. */\n tracing: TraceEngine;\n /** Monotonic sequence counter. */\n sequence: Sequence;\n /** Context, session and tab identity. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n /** Slot for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Keeps the records that minLevel or sampling drops, for the next error. */\n debug?: DebugBuffer;\n}\n\n/** Per-record size limits. The builder applies them after sanitize and after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/**\n * Reason a record was not built. \"malformed\" means a processor or the redact hook broke the\n * record shape or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"processor\" | \"redact\" | \"malformed\";\n\n/** Consumer hook that changes or drops a record. */\ntype RecordHook = (record: LogRecord) => LogRecord | null;\n\n/** Stage of a consumer hook. */\ntype HookStage = \"processor\" | \"redact\";\n\n/** Message subject, drop code and refusal text for each hook stage. */\nconst HOOK_STAGES = {\n processor: {\n label: \"A processor\",\n code: \"record.dropped_by_processor\",\n refused:\n \"processors is not a list of functions. The library drops each record until processors is a list of functions or [].\",\n },\n redact: {\n label: \"The redact hook\",\n code: \"record.dropped_by_redact\",\n refused:\n \"redact is not a function. The library drops each record until redact is a function or null.\",\n },\n} as const;\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\n record: LogRecord | null;\n /** Reason for the drop. Absent when a record was built. */\n dropped?: DropReason;\n}\n\n/** Metadata captured before a deferred logger call reads its payload. */\nexport interface RecordSnapshot {\n timeUnixNano: string;\n trace: TraceContext;\n journey: Journey | null;\n context: Record<string, unknown>;\n url: string;\n}\n\n/** Input parameters for constructing a single log record. */\nexport interface BuildInput {\n /** Severity level of the log entry. */\n level: LogLevel;\n /** Telemetry type classification. */\n type: LogType;\n /** Primary log message body. */\n body: string;\n /** Originating application namespace. */\n namespace: string;\n /** Pre-merged scoped context from logger instance. */\n scoped?: Record<string, unknown>;\n /** Call-site payload attributes. */\n payload?: Record<string, unknown>;\n /**\n * Fields the library builds with a fixed size bound, for example a point's buckets.\n * The record limits don't trim them, and they override a payload key of the same name.\n */\n fixed?: Record<string, unknown>;\n /** True for a counter or histogram point. Sampling keeps it. */\n aggregated?: boolean;\n /** A span's trace IDs. Without them the builder reads the active trace. */\n trace?: TraceContext;\n /** The call's metadata, captured before the deferred build. */\n snapshot?: RecordSnapshot;\n}\n\n/** Checks whether a forwarded value has the shape the library writes for one field. */\ntype FieldCheck = (value: unknown) => boolean;\n\n/** Fields the library writes together on one kind of record, each with its check. */\ntype FieldGroup = Readonly<Record<string, FieldCheck>>;\n\nconst isFiniteNumber: FieldCheck = (value) => typeof value === \"number\" && Number.isFinite(value);\nconst isNumberList: FieldCheck = (value) => Array.isArray(value) && value.every(isFiniteNumber);\n// An int64 time travels as a digit string because a JavaScript number can't hold it.\nconst isNanos: FieldCheck = (value) => typeof value === \"string\" && /^\\d{1,20}$/.test(value);\nconst isTraceId: FieldCheck = (value) => typeof value === \"string\" && /^[0-9a-f]{32}$/.test(value);\nconst isSpanId: FieldCheck = (value) => typeof value === \"string\" && /^[0-9a-f]{16}$/.test(value);\n// A root span's parent id is empty.\nconst isParentId: FieldCheck = (value) => value === \"\" || isSpanId(value);\nconst isCounter: FieldCheck = (value) => value === \"counter\";\nconst isHistogram: FieldCheck = (value) => value === \"histogram\";\nconst isSpanKind: FieldCheck = (value) => value === \"client\" || value === \"internal\";\nconst isSpanStatus: FieldCheck = (value) => value === \"error\" || value === \"unset\";\n\n// metric.name, metric.unit and metric.attribute_keys are app text, so they aren't in a group\n// and the sender's redact has the last word on them.\nconst COUNTER_FIELDS: FieldGroup = {\n \"metric.type\": isCounter,\n \"metric.value\": isFiniteNumber,\n [METRIC_KEYS.start]: isNanos,\n};\n\nconst HISTOGRAM_FIELDS: FieldGroup = {\n \"metric.type\": isHistogram,\n [METRIC_KEYS.start]: isNanos,\n [METRIC_KEYS.count]: isFiniteNumber,\n [METRIC_KEYS.sum]: isFiniteNumber,\n [METRIC_KEYS.min]: isFiniteNumber,\n [METRIC_KEYS.max]: isFiniteNumber,\n [METRIC_KEYS.bounds]: isNumberList,\n [METRIC_KEYS.buckets]: isNumberList,\n};\n\nconst SPAN_FIELDS: FieldGroup = {\n [SPAN_KEYS.kind]: isSpanKind,\n [SPAN_KEYS.parentId]: isParentId,\n [SPAN_KEYS.start]: isNanos,\n [SPAN_KEYS.end]: isNanos,\n [SPAN_KEYS.status]: isSpanStatus,\n};\n\n// A span only has a link when both ids are there, so a lone id is the app's own attribute.\nconst LINK_FIELDS: FieldGroup = {\n [SPAN_KEYS.linkTraceId]: isTraceId,\n [SPAN_KEYS.linkSpanId]: isSpanId,\n};\n\n/**\n * Picks the field groups the library wrote on a forwarded record. The builder sets log.type and\n * app.namespace after it merges the app's attributes, so an attribute can't fake them, but an app\n * logger named uiobs.metrics can. A capture's single metric record writes its fields as payload,\n * so it gets none, as on the local path.\n * @param attributes A forwarded record's attributes, before the sender's hooks.\n * @returns The groups to check.\n */\nfunction groupsOf(attributes: Record<string, unknown>): FieldGroup[] {\n const type = attributes[ATTR_LOG_TYPE];\n const namespace = attributes[ATTR_APP_NAMESPACE];\n\n if (type === LOG_TYPE_SPAN && namespace === TRACE_NAMESPACE) {\n return [SPAN_FIELDS, LINK_FIELDS];\n }\n\n if (type !== LOG_TYPE_METRIC || namespace !== METRIC_NAMESPACE) {\n return [];\n }\n\n if (attributes[\"metric.type\"] === \"histogram\") {\n return [HISTOGRAM_FIELDS];\n }\n\n return [COUNTER_FIELDS];\n}\n\n/**\n * Reads the encoding fields of a metric point or a span from another context, so the sender's\n * redact can't break the point and the limits can't trim its buckets. A group comes back whole\n * or not at all, and only when each value has the library's shape. Otherwise a caller attribute\n * named like a library field would undo the sender's redact.\n * @param attributes A forwarded record's attributes, before the sender's hooks.\n * @returns The fields to put back after the hooks.\n */\nfunction fixedOf(attributes: Record<string, unknown>): Record<string, unknown> {\n const fixed: Record<string, unknown> = {};\n\n for (const group of groupsOf(attributes)) {\n const keys = Object.keys(group);\n if (keys.every((key) => group[key](attributes[key]))) {\n for (const key of keys) {\n fixed[key] = attributes[key];\n }\n }\n }\n\n return fixed;\n}\n\n/**\n * Casts a sanitized plain object value to an attribute record.\n * @param value Sanitized object value.\n * @returns Attribute record.\n */\nfunction asAttributes(value: unknown): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\n/** Builds validated and sanitized LogRecord instances from logger inputs. */\nexport class RecordBuilder {\n /** Cached resource attributes block. */\n private resourceCache: Record<string, unknown> | null = null;\n\n /**\n * @param deps Injected builder dependencies.\n */\n constructor(private readonly deps: RecordBuilderDeps) {}\n\n /** Clears the cached resource attributes, so the next build computes them again. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Checks whether logging is on and the level is at or above the namespace's minimum level.\n * The minimum level doesn't apply to an action or a metric.\n * @param level Target log severity level.\n * @param namespace Logger namespace. `minLevels` can set its level.\n * @param type Record type. Without it, the minimum level applies.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, namespace: string, type?: LogType): boolean {\n return this.deps.config.enabled && this.passesLevel(level, namespace, type);\n }\n\n /**\n * Checks the level against the namespace's minimum level, whatever `enabled` says.\n * @param level Target log severity level.\n * @param namespace Logger namespace.\n * @param type Record type. An action, a metric or a span passes.\n * @returns True if the level is high enough.\n */\n private passesLevel(level: LogLevel, namespace: string, type?: LogType): boolean {\n const { config } = this.deps;\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower the level during an incident.\n const minLevel =\n this.deps.remote.sampling?.minLevelFor(namespace) ?? levelFor(namespace, config);\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];\n }\n\n /**\n * Keeps a record that minLevel or sampling dropped, when the debug buffer is on. The privacy\n * hooks run now, and an error record from this context sends the kept record later.\n * @param input The dropped record's input.\n */\n private keepForDebug(input: BuildInput): void {\n const { config, debug } = this.deps;\n if (!debug || !config.enabled || !config.debugBuffer.enabled) {\n return;\n }\n\n const { record } = this.build(input, true);\n if (record) {\n debug.push(record);\n }\n }\n\n /**\n * Builds a structured LogRecord from the input, sanitizing attributes and applying size limits.\n * @param input Logger call input parameters.\n * @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.\n * @returns The record, or null with the reason for the drop.\n */\n build(input: BuildInput, forConsole = false): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!forConsole && !this.isEnabled(input.level, input.namespace, input.type)) {\n diagnostics.count(\"record.dropped_by_level\");\n this.keepForDebug(input);\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = input.trace ?? input.snapshot?.trace ?? tracing.resolve();\n const activeJourney = input.snapshot ? input.snapshot.journey : journey.current();\n\n // Sample delivery records before the attribute walk. A record for the console or a\n // breadcrumb skips this check: the privacy hooks still process it, but it is never sent.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n aggregated: input.aggregated,\n },\n config,\n remote.sampling?.current() ?? null,\n );\n if (!forConsole && !sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n this.keepForDebug(input);\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // The query and fragment can contain tokens and user input. The path is what groups records.\n const url = input.snapshot?.url ?? currentUrl(diagnostics);\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(url, config.capture.fullUrls, config.capture.urlTransform, diagnostics)\n : \"\";\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(\n input.snapshot?.context ?? this.deps.context.getAll(),\n limits,\n diagnostics,\n );\n const fromProvider = sanitizeWithSize(this.provided(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromProvider.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence: the provider overrides the context, scope overrides\n // the provider, and payload overrides scope.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromProvider.value),\n ...asAttributes(fromScope.value),\n ...asAttributes(fromPayload.value),\n };\n } catch (error) {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"The library could not sanitize the attributes.\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // A trimmed bucket list would make the serializer drop the point.\n Object.assign(attributes, input.fixed);\n\n // Set reserved attributes after the payload merge. If they went first, a payload key\n // named journey.id would replace the ID that correlates the records.\n attributes[ATTR_LOG_TYPE] = input.type;\n attributes[ATTR_LOG_SEQ] = seq;\n attributes[ATTR_APP_NAMESPACE] = input.namespace;\n attributes[ATTR_PAGE_URL] = pageUrl;\n if (activeJourney) {\n attributes[ATTR_JOURNEY_ID] = activeJourney.id;\n attributes[ATTR_JOURNEY_NAME] = activeJourney.name;\n if (activeJourney.parentId !== undefined) {\n attributes[ATTR_JOURNEY_PARENT_ID] = activeJourney.parentId;\n }\n }\n\n const body = truncate(input.body, limits.maxBodyChars);\n if (body !== input.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n let record: LogRecord = {\n timeUnixNano: input.snapshot?.timeUnixNano ?? nowUnixNano(),\n traceId: traceCtx.traceId,\n spanId: traceCtx.spanId,\n traceFlags: traceCtx.traceFlags,\n severityNumber: SEVERITY_NUMBER[input.level],\n severityText: input.level,\n body,\n attributes,\n resource: this.resource(),\n };\n\n const stages = this.hookStages();\n if (stages.length > 0) {\n const outcome = this.applyHooks(record, stages, input.fixed);\n if (typeof outcome === \"string\") {\n return { record: null, dropped: outcome };\n }\n\n ({ record, bytes } = outcome);\n }\n\n const index = {\n [ATTR_LOG_TYPE]: input.type,\n [ATTR_LOG_SEQ]: seq,\n [ATTR_APP_NAMESPACE]: input.namespace,\n };\n return { record: this.fit(record, bytes, index, input.fixed) };\n }\n\n /**\n * Runs the redact hook on a record from another context. A child context without redact\n * forwards raw records, so the sender is the last privacy gate.\n * @param record Forwarded record.\n * @returns The record to deliver, or null when the hook drops it.\n */\n redactForwarded(record: LogRecord): LogRecord | null {\n const { redact } = this.deps.config;\n if (!redact) {\n return record;\n }\n\n const stages: [RecordHook, HookStage][] = [[redact, \"redact\"]];\n const outcome = this.applyHooks(record, stages, fixedOf(record.attributes));\n return typeof outcome === \"string\" ? null : outcome.record;\n }\n\n /**\n * Runs the hooks on a record that a log call built before the app's first configure(), and\n * gives it the configured resource. That record never met the app's hooks, so the processors\n * run as well as redact. The resource goes on first, so redact sees the record that leaves.\n * @param record Held record.\n * @returns The record to deliver, or null when a hook drops it.\n */\n rehook(record: LogRecord): LogRecord | null {\n const { config, diagnostics, limits, remote, debug } = this.deps;\n const { attributes } = record;\n const namespace = String(attributes[ATTR_APP_NAMESPACE]);\n // The app's levels and sampling decide now, as they would have at the call.\n const leveled = this.passesLevel(\n record.severityText,\n namespace,\n attributes[ATTR_LOG_TYPE] as LogType,\n );\n const sampled = leveled && shouldSample(record, config, remote.sampling?.current() ?? null);\n\n // The stored page.url already lost its query to the default rule, so it can't come back.\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(\n String(attributes[ATTR_PAGE_URL]),\n config.capture.fullUrls,\n config.capture.urlTransform,\n diagnostics,\n )\n : \"\";\n const body = truncate(record.body, limits.maxBodyChars);\n if (body !== record.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n const fixed = fixedOf(attributes);\n const stamped = {\n ...record,\n body,\n attributes: { ...attributes, [ATTR_PAGE_URL]: pageUrl },\n resource: this.resource(),\n };\n const outcome = this.applyHooks(stamped, this.hookStages(), fixed);\n const hooked =\n typeof outcome === \"string\"\n ? null\n : this.fit(outcome.record, outcome.bytes, attributes, fixed);\n\n // A refused record goes where build() sends one: a count, and the debug buffer if it's on.\n if (!sampled) {\n diagnostics.count(leveled ? \"record.dropped_by_sampling\" : \"record.dropped_by_level\");\n if (hooked && debug && config.enabled && config.debugBuffer.enabled) {\n debug.push(hooked);\n }\n return null;\n }\n\n return hooked;\n }\n\n /**\n * Drops the caller attributes of a record over maxRecordBytes, but keeps the index keys: a\n * search can't find a record without journey.id and trace_id. Keeps the error fields, then\n * the breadcrumbs if they fit, because they say why the record exists.\n * @param record Record after the hooks.\n * @param bytes Size of its attributes.\n * @param index The type, the sequence and the namespace the library set on the record.\n * @param fixed Fields the library builds. A point without its metric fields is lost.\n * @returns The record, cut down when it's over the limit.\n */\n private fit(\n record: LogRecord,\n bytes: number,\n index: Record<string, unknown>,\n fixed: Record<string, unknown> | undefined,\n ): LogRecord {\n const { diagnostics, limits } = this.deps;\n if (bytes <= limits.maxRecordBytes) {\n return record;\n }\n\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\n { bytes, body: record.body },\n );\n\n const kept: Record<string, unknown> = {\n [ATTR_LOG_TYPE]: index[ATTR_LOG_TYPE],\n [ATTR_LOG_SEQ]: index[ATTR_LOG_SEQ],\n [ATTR_APP_NAMESPACE]: index[ATTR_APP_NAMESPACE],\n [ATTR_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact, because the hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large, so drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\n\n Object.assign(kept, fixed);\n record.attributes = kept;\n return record;\n }\n\n /**\n * Lists the app's hooks in the order they see a record.\n * @returns The processors, then redact, which is the last privacy gate.\n */\n private hookStages(): [RecordHook, HookStage][] {\n const { processors, redact } = this.deps.config;\n const stages = processors.map((hook): [RecordHook, HookStage] => [hook, \"processor\"]);\n if (redact) {\n stages.push([redact, \"redact\"]);\n }\n\n return stages;\n }\n\n /**\n * Runs the hooks in order, then sanitizes and measures the attributes again.\n * @param record Built record.\n * @param stages Hooks and their stages.\n * @param fixed Fields the library builds. The hooks can't change them.\n * @returns The record and the size of its attributes, or the reason for the drop.\n */\n private applyHooks(\n record: LogRecord,\n stages: readonly [RecordHook, HookStage][],\n fixed: Record<string, unknown> | undefined,\n ): { record: LogRecord; bytes: number } | DropReason {\n let current = record;\n\n for (const [hook, stage] of stages) {\n const outcome = this.runHook(hook, stage, current);\n if (typeof outcome === \"string\") {\n return outcome;\n }\n current = outcome;\n }\n\n // A hook can change the attributes in place or replace them. A cycle, a hostile getter or\n // a BigInt from a hook would throw at serialization, and the transport would lose the batch.\n const { diagnostics, limits } = this.deps;\n const remeasured = sanitizeWithSize(current.attributes, limits, diagnostics);\n const attributes = asAttributes(remeasured.value);\n // The limits must not trim the fields the library builds.\n Object.assign(attributes, fixed);\n\n return { record: { ...current, attributes }, bytes: remeasured.bytes };\n }\n\n /**\n * Runs one consumer hook on a record. A processor and the redact hook have the same contract.\n * @param hook Processor or redact hook.\n * @param stage Stage of the hook.\n * @param record Record before the hook.\n * @returns The record after the hook, or the reason for the drop.\n */\n private runHook(hook: RecordHook, stage: HookStage, record: LogRecord): LogRecord | DropReason {\n const { diagnostics } = this.deps;\n const { label, code, refused } = HOOK_STAGES[stage];\n\n // A plain JavaScript hook can edit the record in place and return nothing.\n let changed: unknown;\n try {\n changed = hook(record);\n } catch (error) {\n // Drop the record. A record the hook didn't clean must not leave the page.\n diagnostics.report(\n code,\n `${label} threw an error. The library dropped the record.`,\n undefined,\n error,\n );\n return stage;\n }\n\n if (changed === null) {\n // The stand-in for a hook value that isn't valid drops every record, and says why.\n if (hook === REFUSE_RECORDS) {\n diagnostics.report(code, refused);\n } else {\n diagnostics.count(code);\n }\n return stage;\n }\n\n const candidate: unknown = changed ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place, so we have no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} changed the record to a shape that is not a record. The library dropped it.`,\n );\n return \"malformed\";\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record didn't pass the hook.\n diagnostics.report(\n code,\n `${label} returned a value that is not a record. The library dropped the record.`,\n );\n return stage;\n }\n\n if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number, so the serializer can't map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} set a severityText that is not a log level. The library dropped the record.`,\n );\n return \"malformed\";\n }\n\n // The hook can change severityText, so keep the number in step with the text.\n return { ...candidate, severityNumber: SEVERITY_NUMBER[candidate.severityText] };\n }\n\n /**\n * Calls the config's contextProvider. A provider that throws or returns something that isn't\n * an object adds nothing, and the record is still built. undefined means no attributes.\n * @returns The attributes from the provider, or an empty object.\n */\n private provided(): unknown {\n const provider = this.deps.config.contextProvider;\n if (!provider) {\n return {};\n }\n\n const { diagnostics } = this.deps;\n const value = diagnostics.guard(\n \"handler.threw\",\n \"The contextProvider threw an error. The record has no attributes from it.\",\n () => {\n const given: unknown = provider();\n if (given === undefined) {\n return {};\n }\n\n // A promise is an object, but its fields aren't attributes.\n return isObject(given) && typeof given.then !== \"function\" ? given : null;\n },\n );\n\n if (value === null) {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must return an object of attributes. The library ignores the value.\",\n );\n }\n\n return value ?? {};\n }\n\n /**\n * Computes or returns cached resource metadata for this runtime context.\n * @returns Resource attributes record.\n */\n private resource(): Record<string, unknown> {\n if (this.resourceCache) {\n return this.resourceCache;\n }\n const { config, identity, platform } = this.deps;\n\n this.resourceCache = {\n [RESOURCE_SERVICE_NAME]: config.serviceName,\n [RESOURCE_SERVICE_VERSION]: config.serviceVersion,\n [RESOURCE_DEPLOYMENT_ENVIRONMENT]: config.environment,\n [RESOURCE_TELEMETRY_SDK_NAME]: TELEMETRY_SDK_NAME,\n [RESOURCE_TELEMETRY_SDK_VERSION]: TELEMETRY_SDK_VERSION,\n [RESOURCE_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE,\n [RESOURCE_HOST_PLATFORM]: platform.platform,\n [RESOURCE_SESSION_ID]: identity.sessionId,\n [RESOURCE_TAB_ID]: identity.tabId,\n [RESOURCE_CONTEXT_ID]: identity.contextId,\n ...(config.metadata.userAgent ? { [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent } : {}),\n // Omits undefined OpenFin properties from resource attributes.\n ...(!config.metadata.openfin || platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(!config.metadata.openfin || platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/spans.ts\n//\n// Builds the span data for a root span and the span fields for a span record. The runtime\n// builds every span as a record of type \"span\", and the traces serializer reads the span fields.\n\nimport { SPAN_KEYS } from \"../constants\";\nimport type { EndedTrace, RotateReason } from \"../utils/tracing\";\n\n/** Microseconds in one millisecond. */\nconst US_PER_MS = 1000;\n\n/** Root span name for each reason a trace can start. */\nconst ROOT_NAMES: Record<RotateReason, string> = {\n start: \"ui.start\",\n interaction: \"ui.interaction\",\n navigation: \"ui.navigation\",\n explicit: \"ui.trace\",\n maxAge: \"ui.trace\",\n};\n\n/** One span recorded by the runtime. */\nexport interface SpanData {\n /** Span name. */\n name: string;\n /** \"internal\" for a root span, \"client\" for a request. */\n kind: \"internal\" | \"client\";\n /** Trace ID. */\n traceId: string;\n /** Span ID. */\n spanId: string;\n /** The parent's span ID, or \"\" for a root span. */\n parentSpanId: string;\n /** Start time in epoch milliseconds. */\n startMs: number;\n /** End time in epoch milliseconds. */\n endMs: number;\n /** True for a failed operation. */\n error: boolean;\n /** The span's attributes. */\n attributes: Record<string, unknown>;\n /** Server span linked through a response traceparent entry. */\n link?: { traceId: string; spanId: string };\n}\n\n/**\n * Converts epoch milliseconds to nanoseconds as a decimal string, keeping microseconds.\n * @param ms Epoch time in milliseconds. May have a fraction.\n * @returns Epoch time in nanoseconds.\n */\nfunction unixNano(ms: number): string {\n return `${String(Math.round(ms * US_PER_MS))}000`;\n}\n\n/**\n * Builds the root span for an ambient trace that has ended.\n * @param ended The trace.\n * @returns The span data.\n */\nexport function rootSpan(ended: EndedTrace): SpanData {\n return {\n name: ROOT_NAMES[ended.reason],\n kind: \"internal\",\n traceId: ended.traceId,\n spanId: ended.spanId,\n parentSpanId: \"\",\n startMs: ended.startedAt,\n endMs: ended.endedAt,\n error: false,\n attributes: {},\n };\n}\n\n/**\n * Builds the span fields for a span record. The record limits don't trim them.\n * @param span The span data.\n * @returns The fields.\n */\nexport function spanFields(span: SpanData): Record<string, unknown> {\n return {\n [SPAN_KEYS.kind]: span.kind,\n [SPAN_KEYS.parentId]: span.parentSpanId,\n [SPAN_KEYS.start]: unixNano(span.startMs),\n [SPAN_KEYS.end]: unixNano(span.endMs),\n [SPAN_KEYS.status]: span.error ? \"error\" : \"unset\",\n ...(span.link\n ? {\n [SPAN_KEYS.linkTraceId]: span.link.traceId,\n [SPAN_KEYS.linkSpanId]: span.link.spanId,\n }\n : {}),\n };\n}\n","// src/core/runtime.ts\n//\n// Coordinates the subsystems. Manages their lifecycles, the configuration and record routing.\n\nimport type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n ATTR_BREADCRUMBS,\n ATTR_DEBUG_BUFFER,\n ATTR_PAGE_URL,\n BUS_PROTOCOL,\n CAPTURE_NAMESPACE,\n LIBRARY_LOG_PREFIX,\n REMOTE_CAPTURE_FLAGS,\n DIAGNOSTICS_NAMESPACE,\n FLUSH_REQUEST_SHARE,\n FLUSH_TIMEOUT_MAX_MS,\n FLUSH_TIMEOUT_MS,\n GAP_REPORT_THROTTLE_MS,\n METRIC_NAMESPACE,\n ROUTING_KEYS,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n TRACE_FLAGS_SAMPLED,\n TRACE_NAMESPACE,\n INSTRUMENT_OPTIONS_FAULT,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type { FrameOptions, SourceOptions } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n ShutdownOptions,\n StorageScope,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { DebugBundle, FlushResult, FlushStatus, ObservabilityHealth } from \"../models/health\";\nimport type { PruneResult, StorageAdapter, StoragePersistence } from \"../models/storage\";\nimport type { StoreAccess } from \"../storage/stored-context\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { hasOwn, isObject } from \"../utils/guards\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} from \"../utils/identity\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { detectPlatform, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { sanitize, truncate } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { type Breadcrumb, BreadcrumbBuffer } from \"./breadcrumbs\";\nimport { applyResolvedConfig, REFUSE_RECORDS, resolveConfig } from \"./config\";\nimport { ContextStore } from \"./context\";\nimport { DebugBuffer } from \"./debug-buffer\";\nimport { cancelDeferred, drainDeferred } from \"./deferred\";\nimport {\n type DiagnosticCode,\n type DiagnosticEvent,\n type DiagnosticHandler,\n Diagnostics,\n} from \"./diagnostics\";\nimport { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { LibraryLogger, OneLogger } from \"./logger\";\nimport { createMeasure } from \"./measure\";\nimport { makeCounter, makeHistogram, Meter, type RecordMetric } from \"./meter\";\nimport { profilerCore, type ProfilerSink } from \"./profiler\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport type { RotationHost, rotateContext } from \"./rotation\";\nimport { sampleKey, shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\nimport { rootSpan, type SpanData, spanFields } from \"./spans\";\n\n/** Constructor for a capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** The import for each capture module. Each one is its own chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\n uncleanExit: async (): Promise<CaptureClass> =>\n (await import(\"../capture/unclean-exit\")).UncleanExitCapture,\n userTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/user-timing\")).UserTimingCapture,\n reports: async (): Promise<CaptureClass> => (await import(\"../capture/reports\")).ReportCapture,\n resourceTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/resource-timing\")).ResourceTimingCapture,\n lifecycle: async (): Promise<CaptureClass> =>\n (await import(\"../capture/lifecycle\")).LifecycleCapture,\n framePhases: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePhasesCapture,\n framePacing: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePacingCapture,\n replay: async (): Promise<CaptureClass> => (await import(\"../capture/replay\")).ReplayCapture,\n};\n\n/** Name of a capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** The parts of the session replay capture the runtime calls. */\ninterface ReplayControl extends Capture {\n /** Loads the recorder and starts it. */\n start(): Promise<void>;\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void;\n /** Drops the buffer and, if the recorder was running, starts a fresh recording. */\n reset(): void;\n}\n\n/** Constructor for the WebSocket capture plugin. */\ntype WebSocketClass = new (diagnostics: Diagnostics, config: ResolvedConfig) => CapturePlugin;\n\n/** An id per plugin object, so a new plugin object changes the capture key. */\nconst pluginIds = new WeakMap<object, number>();\n\n/** The last id pluginId() handed out. */\nlet lastPluginId = 0;\n\n/**\n * Returns a plugin object's id. The capture key can't hold the plugin itself, because a\n * plugin can contain a cycle and JSON.stringify would throw.\n * @param plugin The app's plugin.\n * @returns The object's id.\n */\nfunction pluginId(plugin: object): number {\n let id = pluginIds.get(plugin);\n\n if (id === undefined) {\n id = ++lastPluginId;\n pluginIds.set(plugin, id);\n }\n\n return id;\n}\n\n/** Global symbol key for the singleton runtime. All federated bundles share it. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key for the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_KEY);\n\n/** Config sections the delivery stack reads once, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections a later configure() can't change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/** Crumbs that log calls add. Before the start, they hold a body that no hook has seen. */\nconst LOGGED_CRUMBS: readonly string[] = [\"log\", \"event\", \"action\"];\n\n/** Text of the warning and the report after a failed first configure() call. */\nconst FAILED_START =\n \"configure() could not read its options. The library drops each record and installs no capture until a configure() call sets redact to a function or null.\";\n\n/** Text of the report for shutdown() options the library can't use. */\nconst SHUTDOWN_INVALID =\n 'shutdown() got invalid options. The library discards the records in memory. An invalid clearStorage removes the \"context\" scope.';\n\n/** Text of the report for flush() options the library can't use. */\nconst FLUSH_INVALID = \"flush() got invalid options. The library waits the default 5000 ms.\";\n\n/** Diagnostic codes for a normal event rather than a fault. Their records are logged at INFO. */\nconst NOTICE_CODES: ReadonlySet<DiagnosticCode> = new Set([\n \"bus.role_resolved\",\n \"config.reconfigured\",\n \"security.rotated\",\n \"journey.adopted\",\n \"journey.expired\",\n]);\n\n/**\n * Builds a text key for the capture section. A later configure() reinstalls the capture\n * modules only when the key changes, because a reinstall unpatches and repatches every host\n * function.\n * @param capture Capture section.\n * @returns The key. A function or a RegExp becomes fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n urlTransform: capture.urlTransform ? pluginId(capture.urlTransform) : undefined,\n // Only a loader's presence counts, so a new inline loader on each call reinstalls nothing.\n webVitals:\n typeof capture.webVitals === \"object\"\n ? { loader: capture.webVitals.loader !== undefined }\n : capture.webVitals,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n // A RegExp has no JSON form.\n userTiming:\n typeof capture.userTiming === \"object\"\n ? { include: capture.userTiming.include?.map(String) }\n : capture.userTiming,\n plugins: capture.plugins.map(pluginId),\n });\n}\n\n/**\n * Trims the URL fields of a diagnostic detail, because their query can hold a key.\n * onDiagnostic stays local and keeps them.\n * @param detail A diagnostic event's detail.\n * @returns The detail to put in a record.\n */\nfunction recordDetail(detail: unknown): unknown {\n if (!isObject(detail)) {\n return detail;\n }\n\n const copy = { ...detail };\n for (const key of [\"url\", \"endpoint\"]) {\n const value = copy[key];\n if (typeof value === \"string\") {\n copy[key] = recordedUrl(value, false);\n }\n }\n\n return copy;\n}\n\n/**\n * Removes the routing settings from a configuration. A console-only runtime must not send\n * or join a bus, because the other version's runtime does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n metricsEndpoint: null,\n tracesEndpoint: null,\n transport: null,\n transportOnExit: null,\n transportWorker: null,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Checks whether a configuration names a destination.\n * @param input Consumer configuration options.\n * @returns True if it has an endpoint, a signal endpoint or a transport.\n */\nfunction sends(input: Partial<ObservabilityConfig>): boolean {\n return (\n Boolean(input.endpoint) ||\n Boolean(input.metricsEndpoint) ||\n Boolean(input.tracesEndpoint) ||\n Boolean(input.transport) ||\n Boolean(input.transportWorker)\n );\n}\n\n/**\n * Builds a flush result. The counts that aren't given are 0.\n * @param status How the call ended.\n * @param counts The counts to set.\n * @returns The result.\n */\nfunction flushResult(\n status: FlushStatus,\n counts: Partial<Omit<FlushResult, \"status\">>,\n): FlushResult {\n return { status, accepted: 0, stored: 0, dropped: 0, forwarded: 0, pending: 0, ...counts };\n}\n\n/**\n * Builds the result of a flush that ran. It's \"timeout\" while a record waits, so \"timeout\"\n * always has pending records.\n * @param counts The counts to set.\n * @returns The result.\n */\nfunction settled(counts: Partial<Omit<FlushResult, \"status\">> & { pending: number }): FlushResult {\n return flushResult(counts.pending > 0 ? \"timeout\" : \"complete\", counts);\n}\n\n/**\n * Checks whether a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime older than 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the runtime's methods.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /** True while the security context is changing. */\n private rotating = false;\n /** Number of the latest rotateSecurityContext() call, so a queued call keeps `rotating` up. */\n private rotationSeq = 0;\n /**\n * True while this runtime has the profiler core attached. Tracking it keeps configure() from\n * restarting the sampling every time, and keeps a runtime with the profiler off from ever\n * creating the core and its global symbol.\n */\n private profilerOn = false;\n /** True while the old context's last records are being collected. */\n private closingContext = false;\n /** Version of another SDK copy that owns the page runtime, or null. */\n private mismatchVersion: string | null = null;\n /** True if the configured context id differs from the owner's context id. */\n private contextMismatch = false;\n /** The context change in progress. Shutdown waits for this promise. */\n private rotation?: Promise<void>;\n /** Memory store kept for later context changes. */\n private memoryStorage?: StorageAdapter;\n /** State of the persistent storage request. getHealth() reports it. */\n private storagePersistence: StoragePersistence = \"off\";\n /** True while a diagnostic record goes out. Diagnostics raised meanwhile produce no record. */\n private recordingDiagnostic = false;\n /** Logger for the records that diagnostics.records produces. */\n private readonly diagnosticLogger = new OneLogger(() => this, DIAGNOSTICS_NAMESPACE);\n /** Records that minLevel or sampling dropped. An error in this context sends them first. */\n private readonly debugBuffer = new DebugBuffer(() => this.config.debugBuffer);\n /** True if the app supplied a context id at startup. */\n private explicitSecurityContext: boolean;\n /** True once this forwarder has taken a context id from its owner. */\n private ownerAdopted = false;\n\n /**\n * Checks whether a security context change is in progress.\n * @returns True until the current change completes.\n */\n isRotating(): boolean {\n return this.rotating;\n }\n\n /**\n * Locks or unlocks configuration when the app asks. Any other code on this origin can call\n * this too, so the lock is not access control.\n * @param locked True to refuse changes through configure().\n */\n setConfigurationLocked(locked: boolean): void {\n if (typeof locked === \"boolean\") {\n this.config.lockConfiguration = locked;\n }\n }\n /**\n * This copy's runtime when another version of the library owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * This runtime's library version. Another copy reads it from the global key, because two\n * versions sharing one runtime would call methods the other version doesn't have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\n /**\n * This runtime's bus protocol tag. A same-origin child frame reads it from the global key\n * before it opens a direct link, because a direct call has no envelope to carry the tag.\n */\n readonly protocol: string = BUS_PROTOCOL;\n\n /** Diagnostics reporter for internal faults. */\n readonly diagnostics: Diagnostics;\n\n /** Active configuration instance. A reconfigure changes it in place. */\n readonly config: ResolvedConfig;\n\n /** Detected host platform metadata. */\n readonly platform: PlatformMetadata;\n\n /** Identity context containing session, tab, and context identifiers. */\n readonly identity: Identity;\n\n /** Where the ids and the journey live. Memory until the start, so nothing touches storage. */\n private backing: IdentityStores = memoryStores();\n\n /** Stores for identity and journey keys. They read the backing on every call. */\n private readonly stores: IdentityStores = {\n local: () => this.backing.local(),\n session: () => this.backing.session(),\n };\n\n /** The identity strategy that the start uses. The app's startup call fixes it. */\n private identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. The start builds it again. */\n private sessionTouch: SessionTouch;\n\n /** Store for ambient application context attributes. */\n readonly context = new ContextStore();\n\n /** Ring buffer holding contextual user breadcrumbs. */\n readonly breadcrumbs: BreadcrumbBuffer;\n\n /** Distributed tracing context engine. */\n readonly tracing: TraceEngine;\n\n /** Monotonic sequence counter for records emitted in this context. */\n readonly sequence = new Sequence();\n\n /** Journey tracking engine managing workflow correlation. */\n readonly journey: JourneyEngine;\n\n /** Record builder assembling structured log records. */\n readonly builder: RecordBuilder;\n\n /** Slot for the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = {\n sampling: null,\n changed: () => {\n this.refreshCaptures();\n },\n };\n\n /** Number of delivery identity changes. A context's first id doesn't count as a change. */\n private identityEpoch = 0;\n\n /** Session replay's hook. It gets every ERROR and FATAL record. */\n private errorHook: ((record: LogRecord) => void) | undefined;\n\n /**\n * True after startReplay(), false after stopReplay(), undefined until either is called. The\n * app's last choice survives a reinstall of the capture modules.\n */\n private replayConsent: boolean | undefined;\n\n /** The installed session replay capture. */\n private replay: ReplayControl | undefined;\n\n /** Timer that restores the local capture switches once the remote TTL ends. */\n private remoteCaptureTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Settings of the current capture load or install. */\n private installedCaptureKey = \"\";\n\n /** The replay settings the running replay capture was built with. */\n private replayBuiltKey = \"\";\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\n\n /** Sums the values of the counter and histogram instruments. */\n private readonly meter: Meter;\n\n /**\n * Cross-realm communication bus. Null until its chunk loads. In bus.mode \"off\", it loads\n * only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Promise for the bus load and construction. Undefined until first needed. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Promise for the bus load and start. Undefined until first needed. */\n private busLoad?: Promise<Bus | null>;\n\n /**\n * Delivery stack. Set in the sender role with an endpoint or a custom transport, once the\n * chunk has loaded.\n */\n private sender?: Sender;\n\n /** The delivery stack load. Undefined when nothing loads, so records have no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads, or while a pause holds them. */\n private readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Records that dropPaused() reported, so a second pagehide doesn't count them again. */\n private readonly pausedLoss = new WeakSet<LogRecord>();\n\n /** Stored batches that a carry during a pause left for the next sender to adopt. */\n private carried: LogBatch[] = [];\n\n /** True once resetSession() ran. start() then keeps that session over the stored one. */\n private sessionPicked = false;\n\n /**\n * True after a rotation fails. The app asked to leave the context, so the runtime sends no\n * record with its endpoint or headers until a rotation succeeds.\n */\n private deliveryClosed = false;\n\n /**\n * The stopped sender of the context that a failed rotation closed. The next rotation that\n * succeeds retires it with its own rule, so the old records don't stay or move by accident.\n */\n private parkedSender: Sender | undefined;\n\n /** The sender that a rotation retires. Its records wait for the rotation's rule. */\n private retiring: Sender | undefined;\n\n /**\n * True after the first configure() call failed. The runtime stays unconfigured and refuses\n * each record, because it can't know what the app needs to redact.\n */\n private startFailed = false;\n\n /**\n * True once the runtime has started: the first configure() call that works, with enabled true.\n * Before that, nothing is patched, stored or sent.\n */\n private running = false;\n\n /** Opens the start gate below. Its promise sets it, and start() calls it. */\n private openGate!: () => void;\n\n /** Resolves at the start. A frame or worker that registers before it joins the bus then. */\n private readonly startGate = new Promise<void>((resolve) => {\n this.openGate = resolve;\n });\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Number of capture installs. An install replaced by a later one stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that rebuilding the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n uncleanExit: false,\n userTiming: false,\n };\n\n /** Holds records created before the bus role is resolved. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Records staged for forwarding on the next microtask. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True once startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. Set by init(), awaited by flush(). */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if shutdown stopped the runtime. */\n private destroyed = false;\n\n /** The first shutdown. A later shutdown() waits for it before it removes the stored data. */\n private stopping?: Promise<void>;\n\n /** When the server last accepted a batch, in epoch milliseconds. A rotation keeps it. */\n private lastSendAt: number | null = null;\n\n /** When the last storage gap warning was reported, in epoch milliseconds. */\n private lastGapAt = 0;\n\n /** Record limits for the builder and the console. The app's first configure() sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules for the journey engine. The app's first configure() sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /**\n * False until the app's startup call, the first configure() call that works. That call sets\n * every startup-fixed setting, also after an early log call.\n */\n private tunablesLocked = false;\n\n /**\n * True for a console-only runtime, which sends nothing, joins no bus and installs no capture.\n * That happens next to another version of the library on the page, or on a server.\n */\n private readonly degraded: boolean;\n\n /** True once a destination on a server has been reported. It is reported only once. */\n private serverReported = false;\n\n /**\n * Ends a forwarder's root span when its document unloads. The exit flush only ends it in the\n * sender, so without this the client spans of a frame or a view have no parent.\n */\n private readonly onPageHide = (): void => {\n drainDeferred(this);\n this.dropPaused();\n if (this.role() !== \"forwarder\") {\n return;\n }\n\n this.tracing.end();\n this.sendForwarded();\n };\n\n /**\n * @param input Initial consumer configuration options.\n * @param mismatch True for a console-only runtime next to another version.\n */\n private constructor(input: Partial<ObservabilityConfig>, mismatch: boolean) {\n // resolveConfig() checks the hook below. Until then, a value that isn't a function gets no\n // events, otherwise each report would call it and count a false handler.threw.\n this.diagnostics = new Diagnostics(\n typeof input.onDiagnostic === \"function\" ? input.onDiagnostic : undefined,\n );\n\n this.platform = detectPlatform(this.diagnostics);\n // A server has no page to capture and no storage, so it only writes to the console.\n this.degraded = mismatch || this.onServer();\n this.config = resolveConfig(this.allowed(input), this.diagnostics);\n this.explicitSecurityContext = Boolean(input.securityContext?.id);\n this.config.securityContext.id ||= newId(this.diagnostics);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n this.identityBuiltAs = this.config.identity;\n this.identity = resolveIdentity(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.sessionTouch = new SessionTouch(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.breadcrumbs = new BreadcrumbBuffer(this.config.captureLimits.breadcrumbs);\n // Sample a span by its trace, so the whole trace stays or goes.\n const keeps = (traceId: string): boolean =>\n sampleKey(traceId, this.config.sampling.defaultRate);\n this.tracing = new TraceEngine(\n this.diagnostics,\n this.config.correlation.traceMaxAgeMs ?? Infinity,\n this.config.otelLoader,\n {\n enabled: () => this.config.tracesEndpoint !== null,\n keeps,\n onEnd: (ended) => {\n if (keeps(ended.traceId)) {\n this.recordSpan(rootSpan(ended));\n }\n },\n },\n );\n // The startup values stick. A later configure() can't change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.consoleOutput, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n remote: this.remote,\n config: this.config,\n limits: this.limits,\n diagnostics: this.diagnostics,\n context: this.context,\n journey: this.journey,\n tracing: this.tracing,\n sequence: this.sequence,\n identity: this.identity,\n platform: this.platform,\n debug: this.debugBuffer,\n });\n\n this.meter = new Meter(\n () => this.config.metrics.intervalMs,\n (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n this.diagnostics,\n this.config.metrics,\n );\n // The record builder exists now, so a diagnostic can become a record.\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.syncProfiler();\n }\n\n /**\n * Returns the diagnostics handler. With diagnostics.records, it also sends every event as\n * a record.\n * @returns The handler, or undefined with no onDiagnostic and no diagnostic records.\n */\n private diagnosticHandler(): DiagnosticHandler | undefined {\n if (this.config.diagnostics.records === false) {\n return this.config.onDiagnostic;\n }\n\n return (event) => {\n this.recordDiagnostic(event);\n this.config.onDiagnostic?.(event);\n };\n }\n\n /**\n * Sends a diagnostic event as a record when diagnostics.records selects its code.\n * A diagnostic raised during that send produces no record, which stops a loop.\n * @param event Diagnostic event.\n */\n private recordDiagnostic(event: DiagnosticEvent): void {\n const { records } = this.config.diagnostics;\n const selected = records === true || (records !== false && records.includes(event.code));\n if (!selected || this.recordingDiagnostic) {\n return;\n }\n\n this.recordingDiagnostic = true;\n try {\n const write = NOTICE_CODES.has(event.code)\n ? this.diagnosticLogger.info\n : this.diagnosticLogger.warn;\n write(event.message, {\n \"diagnostic.code\": event.code,\n \"diagnostic.count\": event.count,\n \"diagnostic.detail\": recordDetail(event.detail),\n });\n } finally {\n this.recordingDiagnostic = false;\n }\n }\n\n /**\n * Adds a breadcrumb from app code. The data is copied now, so a later change to the app's\n * object doesn't change the trail.\n * @param message Description of the event. A JavaScript caller can pass a non-string, which\n * is converted.\n * @param data Optional metadata.\n */\n addBreadcrumb(message: unknown, data?: Record<string, unknown>): void {\n if (this.rotating || this.destroyed) {\n return;\n }\n // A message whose toString() throws, or a data getter that throws, must not throw into\n // the app's call.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not add the breadcrumb.\",\n () => {\n const crumb: Breadcrumb = {\n t: Date.now(),\n category: \"custom\",\n message: truncate(String(message), this.limits.maxBodyChars),\n };\n\n if (data !== undefined) {\n const clean = sanitize(data, this.limits, this.diagnostics);\n crumb.data = isObject(clean) ? clean : { value: clean };\n }\n\n this.breadcrumbs.push(crumb);\n },\n );\n }\n\n /**\n * Adds a value to a counter or a histogram. The meter sends one point per interval.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // Guard against a value after shutdown, whose interval timer would outlive the runtime.\n // A pause records nothing, as a log call does nothing.\n if (!this.destroyed && !this.rotating && this.config.enabled) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Starts a timed operation. Its values are dropped if the runtime has shut down or a rotation\n * is running when it ends. With `securityContext.isolation`, a new delivery identity before\n * the end drops them too.\n * @param name Operation name.\n * @param attributes Attribute set for every histogram point.\n * @returns The operation's handle.\n */\n startMeasure(name: string, attributes?: MetricAttributes): Measure {\n const epoch = this.identityEpoch;\n const current = (): boolean =>\n !this.destroyed &&\n !this.rotating &&\n (!this.config.securityContext.isolation || this.identityEpoch === epoch);\n const copied = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the attributes of the measure.\",\n () => ({ ...attributes }),\n );\n\n // The name's toString() can throw. If it does, the measure gets an empty name.\n const label = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the name of the measure.\",\n () => \"\".concat(name),\n );\n\n return createMeasure(label ?? \"\", copied ?? {}, this.tracing.request().span, {\n metric: (def, value, points) => {\n if (current()) {\n this.recordMetric(def, value, points);\n }\n },\n span: (span) => {\n if (current()) {\n this.recordSpan(span);\n }\n },\n });\n }\n\n /**\n * Builds and emits the record for one span. The console doesn't print it and minLevel\n * doesn't drop it. The trace engine already sampled the trace before the span existed.\n * @param span The span data.\n */\n private recordSpan(span: SpanData): void {\n if (this.config.tracesEndpoint === null) {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"span\",\n body: span.name,\n namespace: TRACE_NAMESPACE,\n payload: span.attributes,\n fixed: spanFields(span),\n trace: { traceId: span.traceId, spanId: span.spanId, traceFlags: TRACE_FLAGS_SAMPLED },\n });\n this.emit(record);\n }\n\n /**\n * Builds and emits the record for one aggregated point. The console doesn't print it.\n * @param name Metric name.\n * @param attributes The call's attributes. The record limits apply to them.\n * @param fields The point's metric fields. The record limits don't truncate them.\n */\n private emitPoint(\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ): void {\n // A discard at shutdown drops the open interval, so don't build its points.\n if (this.destroyed) {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"metric\",\n body: name,\n namespace: METRIC_NAMESPACE,\n payload: attributes,\n fixed: fields,\n aggregated: true,\n });\n this.emit(record);\n }\n\n /**\n * Turns the profiler on or off to match profiler.enabled. Before switching off it sends the\n * points that are waiting, because the switch would otherwise drop them.\n */\n private syncProfiler(): void {\n // A pause detaches the probes, so they read no clock until enabled is true again.\n const enabled = this.config.profiler.enabled && this.config.enabled;\n if (enabled === this.profilerOn) {\n return;\n }\n\n this.profilerOn = enabled;\n const core = profilerCore();\n if (!enabled) {\n core.collect(false);\n core.detach();\n return;\n }\n\n // Profiler points take the same path as meter points, so hooks and transports apply.\n const sink: ProfilerSink = {\n capacity: this.config.profiler.maxProbes,\n intervalMs: () => this.config.metrics.intervalMs,\n emit: (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n diagnostics: this.diagnostics,\n // Same rule as emit(): the first collect of a rotation still goes to the old sender.\n ready: () => !this.rotating || this.closingContext,\n outlier: (name, ms) => {\n this.breadcrumbs.push({\n t: Date.now(),\n category: \"profile\",\n message: `${name} ${String(Math.round(ms))} ms`,\n });\n },\n };\n core.attach(sink);\n }\n\n /**\n * Gives or withdraws consent for session replay, and starts or stops the recorder if the\n * capture is installed.\n * @param consent True starts the recorder, false stops it.\n */\n setReplay(consent: boolean): void {\n this.replayConsent = consent;\n\n if (consent) {\n void this.replay?.start();\n } else {\n this.replay?.stop();\n }\n }\n\n /**\n * Sends the open interval of the meter and the profiler. The profiler doesn't calibrate here,\n * which keeps flush and the exit path short and synchronous.\n */\n private collectPoints(): void {\n this.meter.collect();\n if (this.profilerOn) {\n profilerCore().collect(false);\n }\n }\n\n /**\n * Starts a new identity epoch. With isolation on, the profiler also drops its data and open\n * spans, so a span from the old identity can't add to the new one. The old identity's remote\n * rules and capture switches don't apply to the new one.\n */\n private advanceIdentity(): void {\n this.identityEpoch++;\n if (this.profilerOn && this.config.securityContext.isolation) {\n profilerCore().reset();\n }\n this.remote.sampling = null;\n this.refreshCaptures();\n }\n\n /**\n * Checks the source policy before a direct child link opens.\n * @param source Child window.\n * @param origin The child window's origin.\n * @returns True if the bus allows this source.\n */\n readonly busCanAccept = (source: Window, origin: string): boolean =>\n this.bus?.isRegistered(source, origin) ?? false;\n\n /**\n * Receives direct messages from same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n * @param source The child frame's window.\n */\n readonly busAccept = (message: BusMessage, reply: Receive, source?: Window): void => {\n if (this.destroyed) {\n return;\n }\n\n // Messages wait for the bus in arrival order, because a promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The bus could not accept a direct message from a child frame.\",\n () => {\n bus.acceptDirect(message, reply, source);\n },\n );\n });\n };\n\n /**\n * Returns the runtime on this realm's global key. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns this copy's local runtime, or the pinned runtime if there is none. A pinned\n * runtime from another version returns null, and a log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime from another version returns null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Checks whether shutdown() stopped this runtime.\n * @returns True once destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /**\n * Initializes a new runtime instance or updates the existing singleton.\n * @param input Consumer configuration options.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n try {\n return ObservabilityRuntime.startOrUpdate(input, implicit);\n } catch (error) {\n const live = ObservabilityRuntime.current();\n // A getter in a later call threw before anything changed, so the current settings stay.\n if (live?.tunablesLocked) {\n live.diagnostics.report(\n \"config.invalid\",\n \"configure() could not read its options. The library keeps the current settings.\",\n undefined,\n error,\n );\n return live;\n }\n\n // An early log call's runtime takes the refusal too, otherwise its held records and a\n // later call without redact would go out unredacted.\n const runtime = live ?? ObservabilityRuntime.startOrUpdate({}, true);\n runtime.refuse(error);\n return runtime;\n }\n }\n\n /**\n * Fails closed after the app's first configure() call couldn't be read. The library can't\n * tell what the app must redact, so it refuses each record, the held ones too, until a call\n * sets redact itself. The runtime stays unconfigured, so it writes no id to storage.\n * @param error What reading the options threw.\n */\n private refuse(error: unknown): void {\n this.startFailed = true;\n // A quiet reporter, so the stand-in doesn't report the missing endpoint a second time.\n const next = resolveConfig({ redact: REFUSE_RECORDS }, new Diagnostics(), this.config);\n applyResolvedConfig(this.config, next);\n // The app's onDiagnostic may not exist yet, so the console gets the warning too.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- The only sink before an onDiagnostic exists.\n console.warn(`${LIBRARY_LOG_PREFIX} ${FAILED_START}`);\n });\n this.diagnostics.report(\"config.invalid\", FAILED_START, undefined, error);\n // The stand-in drops each held record, as it drops every new one.\n this.rehookHeld();\n }\n\n /**\n * Starts a runtime, or updates the one that runs. A getter in the input can throw here.\n * @param input Consumer configuration options.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns Active runtime instance.\n */\n private static startOrUpdate(\n input: Partial<ObservabilityConfig>,\n implicit: boolean,\n ): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() twice.\n local.reconfigure(input);\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime older than 0.9.0 has no sdkVersion, which also counts as another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion, implicit);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input, false);\n (globalThis as Record<symbol, unknown>)[RUNTIME_KEY] = runtime;\n Reflect.deleteProperty(globalThis, STOPPED_KEY);\n // An early log call's runtime waits for the app's configure().\n if (!implicit) {\n runtime.launch();\n }\n return runtime;\n }\n\n /**\n * Starts a console-only runtime next to another version's runtime. It sends nothing, joins\n * no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found The pinned runtime's sdkVersion. A runtime older than 0.9.0 has none.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n implicit: boolean,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(input, true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.mismatchVersion = foundText;\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\n if (!implicit) {\n runtime.launch();\n }\n return runtime;\n }\n\n /**\n * Updates runtime configuration and refreshes affected subsystems.\n * @param input Partial configuration to merge.\n */\n private reconfigure(input: Partial<ObservabilityConfig>): void {\n if (this.rotating) {\n this.diagnostics.report(\n \"config.locked\",\n \"Configuration cannot change during security-context rotation.\",\n );\n return;\n }\n if (this.config.lockConfiguration) {\n const next = resolveConfig(input, this.diagnostics, this.config);\n if (!sameConfig(this.config, next)) {\n this.diagnostics.report(\n \"config.locked\",\n \"Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.\",\n );\n }\n return;\n }\n drainDeferred(this);\n const accepted = this.keepDestination(this.keepRouting(this.allowed(input)));\n // The app's startup call names its own id, so the id is explicit.\n if (!this.tunablesLocked && accepted.securityContext?.id) {\n this.explicitSecurityContext = true;\n }\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n // Nothing reads these sections before the start, so the app's startup call can set them.\n const fixed = this.tunablesLocked ? ([\"correlation\", \"storage\"] as const) : [];\n for (const key of fixed) {\n // Compare resolved values, so an undefined or invalid key isn't a change. Restore the\n // section in the next config, never in the app's own object.\n if (!sameConfig(next[key], this.config[key])) {\n this.diagnostics.report(\n \"config.invalid\",\n `${key} cannot change after startup. The library keeps the current settings.`,\n );\n Object.assign(next, { [key]: this.config[key] });\n }\n }\n this.keepStartupTunables(next);\n const { redact, processors, enabled } = this.config;\n // A pause sends the open interval first. Built now, those points go out after the pause.\n if (enabled && !next.enabled) {\n this.collectPoints();\n }\n applyResolvedConfig(this.config, next);\n // After a failed first call the library can't know which redact the app meant, so only a\n // call that sets redact itself, to a function or null, ends the refusal.\n if (this.config.redact !== REFUSE_RECORDS) {\n this.startFailed = false;\n }\n // A kept record only saw the hooks from its own log call. New hooks must not miss it.\n if (this.config.redact !== redact || this.config.processors !== processors) {\n this.debugBuffer.clear();\n }\n this.breadcrumbs.resize(this.config.captureLimits.breadcrumbs);\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n\n this.builder.invalidateResource();\n this.console.update(this.config.consoleOutput);\n this.keepBuiltIdentity();\n // The handler and the resource are up to date now, and points and diagnostics use both.\n this.syncProfiler();\n this.launch();\n // A pause keeps the sender's records, so they go out once enabled is true again.\n if (this.running && enabled !== this.config.enabled) {\n this.sender?.hold(!this.config.enabled);\n }\n\n // Reinstall only on a change, because a reinstall unpatches and repatches every host\n // function. A stale capture load stops at its generation check, so a reinstall is safe\n // at any time.\n this.refreshCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\"config.reconfigured\", \"A later configure() call updated the runtime.\");\n }\n\n /**\n * Checks whether the runtime is on a server, for example Node during server-side rendering.\n * @returns True on Node.\n */\n private onServer(): boolean {\n return this.platform.platform === \"node\";\n }\n\n /**\n * Removes the routing settings from a console-only runtime's input. On a server, it\n * reports a destination once.\n * @param input Consumer configuration options.\n * @returns The options the runtime accepts.\n */\n private allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.degraded) {\n return input;\n }\n\n if (this.onServer() && !this.serverReported && sends(input)) {\n this.serverReported = true;\n this.diagnostics.report(\n \"config.invalid\",\n \"The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.\",\n );\n }\n\n return consoleOnly(input);\n }\n\n /**\n * Removes routing and identity changes while isolation is on. The other settings still apply.\n * @param input Consumer configuration options.\n * @returns The options without the refused routing or identity changes.\n */\n private keepRouting(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.tunablesLocked || this.degraded || !this.config.securityContext.isolation) {\n return input;\n }\n\n // Compare resolved values. An unset endpoint keeps the current endpoint, so it isn't a\n // change. A separate reporter keeps the real resolve's diagnostics from being counted twice.\n const probe = resolveConfig(input, new Diagnostics(), this.config);\n const refused: string[] = ROUTING_KEYS.filter(\n (key) => !sameConfig(probe[key], this.config[key]),\n );\n if (probe.securityContext.id !== this.config.securityContext.id) {\n refused.push(\"securityContext.id\");\n }\n if (refused.length === 0) {\n return input;\n }\n\n const kept: Partial<ObservabilityConfig> = { ...input };\n for (const key of ROUTING_KEYS) {\n if (refused.includes(key)) {\n Reflect.deleteProperty(kept, key);\n }\n }\n if (refused.includes(\"securityContext.id\")) {\n const context = { ...input.securityContext };\n Reflect.deleteProperty(context, \"id\");\n kept.securityContext = context;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `Isolation refuses changes to ${refused.join(\", \")}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`,\n );\n return kept;\n }\n\n /**\n * Restores the startup tunables in the next config. Each tunable is read once by some part\n * of the runtime, so a later change would have no effect and is refused.\n * @param next The resolved config from a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The app's startup call sets that\n // runtime's limits, journey age and bus role settings.\n if (!this.tunablesLocked) {\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n // The bus reads its role settings once, when it starts.\n for (const key of [\"mode\", \"openFinRole\"] as const) {\n if (next.bus[key] !== this.config.bus[key]) {\n this.diagnostics.report(\n \"config.invalid\",\n `bus.${key} cannot change after startup. The library keeps \"${this.config.bus[key]}\".`,\n { requested: next.bus[key] },\n );\n Object.assign(next.bus, { [key]: this.config.bus[key] });\n }\n }\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n\n const { maxProbes } = this.config.profiler;\n if (next.profiler.maxProbes !== maxProbes) {\n this.diagnostics.report(\n \"config.invalid\",\n `profiler.maxProbes cannot change after startup. It stays ${String(maxProbes)}.`,\n { requested: next.profiler.maxProbes },\n );\n next.profiler.maxProbes = maxProbes;\n }\n }\n\n /**\n * Refuses a change to config sections by restoring the current values in the next config.\n * @param next The resolved config from a later configure() call.\n * @param sections Sections that can't change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (sameConfig(next[section], this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The current values stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\n }\n\n /**\n * Refuses a change that leaves the built delivery stack with no destination.\n * Without one, the retry engine removes every stored batch as if it were delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n // The stack picks its transport once. A rotation can pick another one. undefined keeps the\n // current transport, so only a value or null can add or remove one.\n for (const key of [\"transport\", \"transportWorker\"] as const) {\n const value = input[key];\n // A value that isn't a function adds nothing, so resolveConfig() reports its type instead.\n const adds = typeof value === \"function\" && this.config[key] === undefined;\n const removes = value === null && this.config[key] !== undefined;\n if (adds || removes) {\n this.diagnostics.report(\n \"config.invalid\",\n `You cannot add or remove ${key} after the delivery stack loads. The current transport stays.`,\n );\n accepted = { ...accepted };\n Reflect.deleteProperty(accepted, key);\n }\n }\n\n // \"\" is the value for \"not set\", so it removes the endpoint too.\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot remove the endpoint after the delivery stack loads. The current endpoint stays.\",\n );\n // An undefined endpoint keeps the current endpoint, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\n }\n\n /**\n * Restores the identity strategy from startup. The ids have existed since startup, and a\n * later change can't move them to another store.\n */\n private keepBuiltIdentity(): void {\n // The stores switch at the start, so the app's startup call can still pick the strategy.\n if (!this.tunablesLocked) {\n this.identityBuiltAs = this.config.identity;\n return;\n }\n\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /**\n * Fixes the startup settings at the first configure() call that works, then starts the\n * runtime once enabled is true. A failed first call leaves the runtime unconfigured.\n */\n private launch(): void {\n if (this.startFailed) {\n return;\n }\n\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n // These records never met the app's hooks, so they reach onDrop only after redact.\n if (!this.config.enabled) {\n this.drops.add(\"disabled\", this.rehookHeld());\n }\n }\n\n if (!this.running && this.config.enabled) {\n this.start();\n }\n }\n\n /**\n * Starts the runtime: reads the configured ids, gives the held records the app's hooks and\n * resource, then installs the captures and starts the bus and the sender. Runs once.\n */\n private start(): void {\n this.running = true;\n // The ids lived in memory until now, so a page that never calls configure() stores nothing.\n if (this.identityBuiltAs === \"storage\" && !this.onServer()) {\n this.backing = BROWSER_STORES;\n }\n\n const { sessionIdleMs, traceMaxAgeMs } = this.config.correlation;\n const { sessionId, tabId } = resolveIdentity(this.diagnostics, this.stores, sessionIdleMs);\n this.sessionTouch = new SessionTouch(this.diagnostics, this.stores, sessionIdleMs);\n // A newSession() before the start chose a new session, so the stored one mustn't replace it.\n if (this.sessionPicked) {\n this.sessionTouch.restart(this.identity.sessionId);\n } else {\n this.identity.sessionId = sessionId;\n }\n this.identity.tabId = tabId;\n this.builder.invalidateResource();\n // A log call's crumb holds its raw body, because no hook existed yet. The app's own crumbs stay.\n this.breadcrumbs.retain((crumb) => !LOGGED_CRUMBS.includes(crumb.category));\n this.tracing.setup(traceMaxAgeMs ?? Infinity, this.config.otelLoader);\n // Don't await. Without OTel, records use the ambient trace and nothing is lost.\n void this.tracing.loadOtel();\n\n for (const record of this.rehookHeld()) {\n this.bootBuffer.push(record, this.config.buffering.maxHeldRecords);\n }\n\n this.openGate();\n void this.init();\n }\n\n /**\n * Takes the records that log calls held before the app's startup call, and runs the app's\n * hooks on them now.\n * @returns The records the hooks kept, with the configured resource.\n */\n private rehookHeld(): LogRecord[] {\n return this.bootBuffer\n .take()\n .map((record) => this.builder.rehook(record))\n .filter((record) => record !== null);\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // A console-only runtime never forwards, and Node has no addEventListener.\n if (!this.degraded) {\n addEventListener(\"pagehide\", this.onPageHide);\n }\n\n // Start the capture imports now so they download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n // Set before the first await, so a flush() right after configure() waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /**\n * Resolves the bus role, loads the delivery stack and releases the boot records.\n * Never rejects.\n */\n private async boot(): Promise<void> {\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"Startup failed. The runtime continues with reduced function.\",\n undefined,\n error,\n );\n } finally {\n // Release the boot records before the captures load, so the exit flush can find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n }\n\n /**\n * Starts the bus load once.\n * @returns Promise that resolves to the started bus, or null if it didn't load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus once. Does not call start().\n * @returns Promise that resolves to the constructed bus, or null if it didn't load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. Never rejects.\n * @returns Promise that resolves to the started bus, or null if it didn't load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. Never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n // A frame or a worker can register before configure(), and the bus waits for the start.\n await this.startGate;\n const { Bus } = await import(\"../bus/bus\");\n\n // A shutdown can happen during the load, and a bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const bus = new Bus(\n this.config,\n this.diagnostics,\n this.platform,\n this.identity.contextId,\n this.identity.tabId,\n {\n onSecurityContext: (id) => {\n if (this.explicitSecurityContext && this.config.securityContext.id !== id) {\n this.contextMismatch = true;\n this.diagnostics.report(\n \"security.context_mismatch\",\n \"The configured security context differs from the upstream owner.\",\n );\n return false;\n }\n this.contextMismatch = false;\n if (this.config.securityContext.id !== id) {\n // The first owner id keeps the startup records and the app's context, because\n // those records had no other identity. A later change retires them, even before\n // ready.\n if (this.ownerAdopted) {\n drainDeferred(this);\n this.drops.add(\"security_context\", [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ]);\n this.forwardBuffer = [];\n this.context.clear();\n this.breadcrumbs.clear();\n // collect() removes the open measurements, and emit() refuses them during this\n // reset.\n const rotating = this.rotating;\n this.rotating = true;\n this.collectPoints();\n // The profiler holds on to its data while emit() refuses records. Don't let the\n // old owner's data reach the new owner.\n if (this.profilerOn) {\n profilerCore().reset();\n }\n // A same-origin owner stores its new session before it sends the new id, so use\n // that session. Otherwise every frame starts a different session.\n const shared = this.sessionTouch.stored();\n this.resetSession(\n shared !== undefined && shared !== this.identity.sessionId\n ? shared\n : newId(this.diagnostics),\n );\n this.rotating = rotating;\n this.advanceIdentity();\n }\n this.config.securityContext.id = id;\n }\n this.ownerAdopted = true;\n return true;\n },\n onRecords: (records) => {\n this.ingestForwarded(records);\n },\n paused: () => !this.config.enabled,\n onJourney: (journey) => {\n this.journey.applyRemote(journey);\n },\n onJourneyRequest: () => this.journey.current(),\n onTabConflict: () => {\n this.regenerateTabId();\n },\n onFlush: (timeoutMs) => this.flushFor(timeoutMs, false),\n remote: this.remote,\n },\n );\n\n this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has a destination, that is an\n * endpoint or a custom transport.\n * @returns Promise that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n // Nothing sends before the start or during a pause. A pause that ends calls this again. A\n // shutdown during startup loads nothing, so the held records reach onDrop and don't wait.\n const sends = this.running && this.config.enabled && !this.deliveryClosed && !this.destroyed;\n if (!sends || !this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Checks whether the config names a destination for the records.\n * @returns True if it has an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the delivery stack load once.\n * @returns Promise that resolves when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /**\n * Imports and builds the delivery stack, then moves the held records into it.\n * Never rejects.\n */\n private async buildSender(): Promise<void> {\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n storage: this.memoryStorage,\n onStorage: (storage) => {\n if (storage.name === \"memory\") {\n this.memoryStorage = storage;\n }\n },\n onPersistence: (state) => {\n this.storagePersistence = state;\n },\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n onLoss: this.reportLoss,\n remote: this.remote,\n beforeExit: () => {\n drainDeferred(this);\n this.collectPoints();\n this.tracing.end();\n },\n onSent: (at) => {\n this.lastSendAt = at;\n },\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime. Its\n // pipeline is empty, because the shutdown took the held records, so it sends nothing.\n if (!sender || this.destroyed) {\n await sender?.discard();\n return;\n }\n\n // A failed rotation closed the context during the load. This sender must not send the\n // old context's batches, so it stops and keeps them for the next rotation's rule.\n if (this.deliveryClosed) {\n await this.parkSender(sender);\n return;\n }\n\n this.sender = sender;\n // A pause that started during the load holds the new sender too.\n if (!this.config.enabled) {\n sender.hold(true);\n }\n } catch (error) {\n // Clear the load so a later configure() can try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The delivery stack did not load. The library does not send records.\",\n { held: this.pendingRecords.length },\n error,\n );\n this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\n this.sender?.push(record);\n }\n\n // A carry during a pause left its stored batches for this sender.\n const carried = this.carried;\n this.carried = [];\n if (this.sender && carried.length > 0) {\n await this.adoptStored(this.sender, carried);\n }\n }\n\n /**\n * Stores an earlier context's batches under this context.\n * @param sender The sender that adopts them.\n * @param stored The earlier context's stored batches.\n */\n private async adoptStored(sender: Sender, stored: readonly LogBatch[]): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the carried batches under the new context.\",\n () => sender.adopt(stored, this.config.securityContext.id),\n );\n }\n\n /** Refreshes temporary switches and restores local settings when their TTL ends. */\n private refreshCaptures(): void {\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n if (this.destroyed) {\n return;\n }\n\n const wire = this.remote.sampling?.wire();\n if (wire) {\n this.remoteCaptureTimer = setTimeout(() => {\n this.refreshCaptures();\n }, wire.ttlMs);\n unrefTimer(this.remoteCaptureTimer);\n }\n\n if (this.captureState(this.effectiveCapture()) !== this.installedCaptureKey) {\n void this.installCaptures();\n }\n }\n\n /**\n * Serializes the current capture settings and profiler observers into one string. When the\n * string changes, the captures are reinstalled.\n * @param settings Current capture settings.\n * @returns The string.\n */\n private captureState(settings: CaptureOptions): string {\n const { enabled, framePhases, framePacing } = this.config.profiler;\n\n return `${String(this.config.enabled)}${captureKey(settings)}${String(enabled && framePhases)}${String(enabled && framePacing)}${this.replayState(settings)}`;\n }\n\n /**\n * Serializes what the replay recorder reads when it starts. The replay capture has its own\n * key because a restart drops the buffer, so an unrelated capture change must not cause one.\n * The other replay values are read on use and apply without a restart.\n * @param settings Current capture settings.\n * @returns The string. Empty while replay is off, so a replay change then installs nothing.\n */\n private replayState(settings: CaptureOptions): string {\n const { replay } = this.config;\n\n if (!replay.enabled) {\n return \"\";\n }\n\n // Functions and recordOptions go in by identity: a function doesn't stringify, and the\n // app's recordOptions can have a cycle or a throwing getter. The endpoint and onSegment are\n // in, so a buffer never goes to a destination it wasn't recorded for. fullUrls and\n // ignoreUrls are in because the kept capture reads them from its install-time settings,\n // and a buffer recorded with full URLs must not survive the app turning them off.\n // replay.headers stays out, so a refreshed token doesn't drop the buffer.\n return JSON.stringify([\n replay.loader && pluginId(replay.loader),\n replay.onSegment && pluginId(replay.onSegment),\n pluginId(replay.recordOptions),\n replay.endpoint,\n replay.requireConsent,\n replay.mode,\n replay.maskText,\n replay.maskInputs,\n replay.maskSelectors,\n replay.blockSelectors,\n replay.recordCanvas,\n replay.bufferMs,\n replay.plugins.map(pluginId),\n settings.fullUrls,\n settings.ignoreUrls.map(String),\n ]);\n }\n\n /** Returns local capture settings with the permitted remote switches. */\n private effectiveCapture(): CaptureOptions {\n const settings = { ...this.config.capture };\n const remote = this.remote.sampling?.current()?.capture;\n for (const key of REMOTE_CAPTURE_FLAGS) {\n const value = remote?.[key];\n if (settings.remoteToggles.includes(key) && value !== undefined) {\n if (value && typeof settings[key] === \"object\") {\n continue;\n }\n settings[key] = value;\n }\n }\n\n return settings;\n }\n\n /** Loads, builds and installs the enabled capture modules. Never rejects. */\n private async installCaptures(): Promise<void> {\n // A console-only runtime next to another version patches nothing. The other version does.\n // Nothing is patched before the start.\n if (this.degraded || !this.running) {\n return;\n }\n\n const generation = ++this.captureGeneration;\n const settings = this.effectiveCapture();\n this.installedCaptureKey = this.captureState(settings);\n\n // A pause removes every patch and the recorder, so the page runs as if the library weren't\n // there. The replay buffer goes with the recorder, and enabled true starts a new recording.\n if (!this.config.enabled) {\n this.uninstallCaptures();\n return;\n }\n const replayKey = this.replayState(settings);\n\n // The recorder reads the live config whenever it starts, and newSession() or startReplay()\n // can restart it at any time. So once any install has asked for different settings, the\n // running recorder may no longer match the key it was built with, and it is never kept.\n if (replayKey !== this.replayBuiltKey) {\n this.replayBuiltKey = \"\";\n }\n\n // A running recorder whose start settings didn't change stays as it is. Reinstalling it\n // would drop the buffer, and with it the \"before\" of the next error.\n const kept = replayKey !== \"\" && replayKey === this.replayBuiltKey ? this.replay : undefined;\n const names: CaptureName[] = [];\n const { profiler } = this.config;\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing, so don't load the chunk for it.\n const consoleOn =\n typeof settings.console === \"object\"\n ? settings.console.levels?.length !== 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\n }\n if (settings.uncleanExit) {\n names.push(\"uncleanExit\");\n }\n if (settings.userTiming) {\n names.push(\"userTiming\");\n }\n\n if (settings.reports) {\n names.push(\"reports\");\n }\n if (settings.resourceTiming) {\n names.push(\"resourceTiming\");\n }\n if (settings.lifecycle) {\n names.push(\"lifecycle\");\n }\n // The profiler's observers share one chunk, and it only loads with the profiler on.\n if (profiler.enabled && profiler.framePhases) {\n names.push(\"framePhases\");\n }\n if (profiler.enabled && profiler.framePacing) {\n names.push(\"framePacing\");\n }\n if (this.config.replay.enabled && !kept) {\n names.push(\"replay\");\n }\n\n const [classes, WebSocketCapture] = await Promise.all([\n Promise.all(names.map((name) => this.loadCapture(name))),\n settings.webSocket ? this.loadWebSocket() : undefined,\n ]);\n\n // Guard against a later install or a shutdown during the load. A stale capture would\n // leak its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new one in one synchronous step, leaving no gap without capture.\n this.uninstallCaptures(kept);\n\n const ctx: CaptureContext = {\n isActive: () => !this.destroyed && !this.rotating,\n config: Object.assign(Object.create(this.config) as ResolvedConfig, { capture: settings }),\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new LibraryLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n recordMetric: (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n },\n recordSpan: (span) => {\n this.recordSpan(span);\n },\n sessionId: () => this.identity.sessionId,\n onError: (hook) => {\n this.errorHook = hook;\n },\n setContext: (key, value) => {\n // undefined removes the key, so the replay id goes when the recorder stops.\n this.context.merge({ [key]: value ?? null });\n },\n replayConsent: () => this.replayConsent,\n };\n\n classes.forEach((CaptureModule, index) => {\n if (CaptureModule) {\n const capture = new CaptureModule(ctx);\n this.captures.push(capture);\n\n // Find the replay capture by its loader, not by its name. A plugin could use that name.\n if (names[index] === \"replay\") {\n this.replay = capture as ReplayControl;\n this.replayBuiltKey = replayKey;\n }\n }\n });\n\n const plugins = WebSocketCapture\n ? [...settings.plugins, new WebSocketCapture(this.diagnostics, ctx.config)]\n : settings.plugins;\n\n for (const plugin of plugins) {\n this.captures.push(this.pluginCapture(plugin));\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not install the ${capture.name} capture.`,\n () => {\n capture.install();\n },\n );\n }\n }\n\n /**\n * Uninstalls the active capture modules.\n * @param kept A replay capture that stays installed, if there is one.\n */\n private uninstallCaptures(kept?: ReplayControl): void {\n for (const capture of this.captures) {\n if (capture !== kept) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not uninstall the ${capture.name} capture.`,\n () => {\n capture.uninstall();\n },\n );\n }\n }\n this.captures.length = 0;\n this.replay = kept;\n\n if (kept) {\n this.captures.push(kept);\n }\n }\n\n /**\n * Imports the WebSocket capture plugin. A failed import is reported and skipped.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadWebSocket(): Promise<WebSocketClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the webSocket capture.\",\n async () => (await import(\"../capture/web-socket\")).WebSocketCapture,\n );\n }\n\n /**\n * Wraps a plugin as a capture module. The plugin only gets public tools.\n * @param plugin The app's plugin, or a built-in one.\n * @returns The capture module.\n */\n private pluginCapture(plugin: CapturePlugin): Capture {\n const { name } = plugin;\n const record: RecordMetric = (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n };\n const fault = (error: unknown): void => {\n this.diagnostics.report(\"config.invalid\", INSTRUMENT_OPTIONS_FAULT, undefined, error);\n };\n const ctx: PluginContext = {\n logger: new OneLogger(() => this, `${CAPTURE_NAMESPACE}.${name}`),\n counter: (metric, options = {}) => makeCounter(metric, options, record, fault),\n histogram: (metric, options = {}) => makeHistogram(metric, options, record, fault),\n addBreadcrumb: (message, data) => {\n this.addBreadcrumb(message, data);\n },\n ownRequest: runAsLibraryRequest,\n };\n\n return {\n name,\n install: () => {\n plugin.install(ctx);\n },\n uninstall: () => {\n plugin.uninstall();\n },\n };\n }\n\n /**\n * Imports one capture module. A failed import is reported and skips only that module.\n * @param name Capture module name.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `The library could not load the ${name} capture.`,\n CAPTURE_LOADERS[name],\n );\n }\n\n /**\n * Attaches a Web Worker or MessagePort to the bus for record forwarding.\n * @param worker Target Worker or MessagePort instance.\n */\n registerWorker(worker: WorkerLike, options: SourceOptions = {}): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n if (this.destroyed) {\n return () => undefined;\n }\n\n // Attach on construction, because the worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n detach = bus.attachWorker(worker, options);\n },\n );\n\n // In bus.mode \"off\" startup didn't start the bus, so start it now.\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Registers a frame after the bus loads. Early removal cancels the registration.\n * @param frame Child frame or window.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n detach = this.diagnostics.guard(\"bus.send_failed\", \"The frame could not be registered.\", () =>\n bus.registerFrame(frame, options),\n );\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Stops every subsystem and unpins the runtime. By default it flushes the records first. A\n * discard sends nothing, and a clearStorage scope also removes the stored batches and ids. A\n * later call stops nothing more, but its clearStorage scope still applies.\n * @param options What to do with the records that wait, and which storage to remove.\n */\n async destroy(options?: ShutdownOptions): Promise<void> {\n const { discard, scope } = this.shutdownRule(options);\n // The removal waits for the first call, otherwise a late save of its flush or of its exit\n // flush could land after it.\n this.stopping ??= this.stop(discard);\n await this.stopping;\n if (scope !== undefined) {\n await this.clearStorage(scope);\n }\n }\n\n /**\n * Stops every subsystem once, then unpins the runtime.\n * @param discard True to send nothing and report the records in memory as discarded.\n */\n private async stop(discard: boolean): Promise<void> {\n // A flush sends the open interval's points and the root span. A discard builds neither.\n if (!discard) {\n drainDeferred(this);\n this.collectPoints();\n this.tracing.end();\n }\n // After shutdown() probes stop reading the clock until the next configure(), and their\n // data goes with the detach.\n if (this.profilerOn) {\n this.profilerOn = false;\n profilerCore().detach();\n }\n this.destroyed = true;\n // A journey call on the stopped runtime then writes to memory only, as each call records\n // nothing until the next configure().\n this.backing = memoryStores();\n cancelDeferred(this);\n // emitPoint() builds nothing now, so this only stops the meter's timer after a discard.\n this.collectPoints();\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n\n if (!this.degraded) {\n removeEventListener(\"pagehide\", this.onPageHide);\n }\n\n // The replay capture drops its buffer and its upload queue here.\n this.uninstallCaptures();\n const closing = discard ? this.discardHeld() : this.flushHeld();\n this.journey.destroy();\n this.bus?.destroy();\n await closing;\n // A load in progress stops its own stack, and shutdown() resolves only after that.\n await this.senderLoad;\n await this.rotation?.catch(() => undefined);\n // A parked sender keeps its records stored, and only its store needs to close.\n const parked = this.parkedSender;\n this.parkedSender = undefined;\n await this.diagnostics.guardAsync(\n \"pipeline.crashed\",\n \"The delivery stack of the old context did not stop at shutdown. The library leaves its stored batches in storage.\",\n async () => {\n await (discard\n ? parked?.discard()\n : parked?.retire(\"retain\", 0, this.config.securityContext.id));\n },\n );\n await this.memoryStorage?.close();\n\n // A local runtime must not remove the other version's runtime from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime would drop the app's settings.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\n }\n }\n\n /**\n * Reads the shutdown() options. A value it can't use reports config.invalid and discards,\n * because an app that asks to discard or to remove storage doesn't want a send.\n * @param options The app's options.\n * @returns True to discard, and the storage scope to remove.\n */\n private shutdownRule(options: unknown): { discard: boolean; scope?: StorageScope } {\n const read = this.readOptions(options, SHUTDOWN_INVALID);\n if (read === undefined) {\n return { discard: true };\n }\n\n const { pending, clearStorage } = read;\n // null turns the removal off, as null turns off other options.\n const unset = clearStorage === undefined || clearStorage === null;\n const knownScope = unset || clearStorage === \"context\" || clearStorage === \"namespace\";\n let scope: StorageScope | undefined;\n if (!unset) {\n // A value it can't use still removes the narrower scope, because the app asked for one.\n scope = clearStorage === \"namespace\" ? \"namespace\" : \"context\";\n }\n\n const flushes = pending === undefined || pending === \"flush\";\n // clearStorage always discards, so it can't honour an explicit \"flush\".\n if (!knownScope || !(flushes || pending === \"discard\") || (pending === \"flush\" && scope)) {\n this.diagnostics.report(\"config.invalid\", SHUTDOWN_INVALID);\n }\n\n return { discard: !flushes || scope !== undefined, scope };\n }\n\n /** Flushes the sender's records and runs the exit flush. Reports what can't go out. */\n private async flushHeld(): Promise<void> {\n // A paused sender sends nothing at shutdown either.\n this.dropPaused();\n // Sender.destroy awaits a normal flush, then runs the exit flush. The records already hold\n // their journey, so the journey and the bus can stop first.\n const closing = this.sender?.destroy();\n // A record in the forward buffer waits for its microtask, so the bus takes it before it stops.\n this.sendForwarded();\n // The delivery stack didn't load before shutdown(), so the held records are lost. A pause\n // already reported its own.\n this.drops.add(\"load_failed\", this.unreported(this.pendingRecords.take()));\n await closing;\n }\n\n /**\n * Drops the records in memory without a send and reports each one as \"discarded\". A record\n * in a request that is in flight isn't reported, because the request can still arrive.\n */\n private async discardHeld(): Promise<void> {\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take(), ...this.forwardBuffer];\n this.forwardBuffer = [];\n // The stopped runtime stays reachable until the next configure(), so the next user on a\n // shared device must not find the previous user's trail or attributes in it.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n this.context.clear();\n // The stores are memory now, so this writes no browser store and tells no peer.\n this.journey.applyRemote(null);\n const buffered = (await this.sender?.discard()) ?? [];\n this.drops.add(\"discarded\", this.unreported([...held, ...buffered]));\n }\n\n /**\n * Removes the stored batches, the emergency queue entries and the stored ids. Before the\n * first configure() call that works, no store is known, so it removes nothing.\n * @param scope Whose stored batches to remove.\n */\n private async clearStorage(scope: StorageScope): Promise<void> {\n if (!this.tunablesLocked) {\n return;\n }\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches at shutdown.\",\n async () => {\n const { clearStored } = await import(\"../storage/stored-context\");\n // A carry during a pause left its batches under an older context id. A first-call pause\n // hasn't switched to the browser stores yet, but an earlier page can have written the\n // ids there.\n const ids = this.carried.map((batch) => batch.id);\n this.carried = [];\n await clearStored(\n this.storeAccess(),\n scope,\n ids,\n this.identityBuiltAs === \"storage\" && !this.onServer(),\n );\n },\n );\n }\n\n /**\n * Routes a completed log record to the pipeline or forward buffer.\n * @param record Log record to emit, or null when the build dropped it.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed) {\n return;\n }\n\n // A record built during a rotation belongs to neither context.\n if (this.rotating && !this.closingContext) {\n this.drops.add(\"security_context\", [record]);\n return;\n }\n\n this.sessionTouch.touch(this.identity.sessionId);\n\n // An error first sends the records that minLevel or sampling dropped before it.\n const error = record.severityText === \"ERROR\" || record.severityText === \"FATAL\";\n const records = error ? [...this.debugBuffer.drain(), record] : [record];\n\n // Session replay uploads its buffer on an error. The hook has its own guard.\n if (error) {\n this.errorHook?.(record);\n }\n\n for (const one of records) {\n if (this.ready) {\n this.route(one);\n } else {\n this.bootBuffer.push(one, this.config.buffering.maxHeldRecords);\n }\n }\n }\n\n /**\n * Sends a record to the forward buffer or to the local pipeline, depending on the bus role.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.deliveryClosed) {\n this.drops.add(\"security_context\", [record]);\n return;\n }\n\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n // Console-only mode has no destination. Count the drop, otherwise no counter shows the loss.\n // A pause loads no sender, so it holds the record until enabled: true loads one.\n const paused = !this.config.enabled && this.hasDestination();\n if (!this.senderLoad && !paused) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record, this.config.buffering.maxHeldRecords);\n }\n\n /**\n * Reports the sender's records in memory as lost during a pause. A pause has no exit flush,\n * so a pagehide or a shutdown leaves nothing to send them.\n */\n private dropPaused(): void {\n if (this.config.enabled) {\n return;\n }\n\n // The records stay, and a page back from the back/forward cache sends them, so count once.\n const fresh = this.unreported([\n ...this.pendingRecords.records,\n ...(this.sender?.records() ?? []),\n ]);\n for (const record of fresh) {\n this.pausedLoss.add(record);\n }\n this.drops.add(\"disabled\", fresh);\n }\n\n /**\n * Leaves out the records that a pause already reported, so onDrop counts each loss once.\n * @param records Lost records.\n * @returns The records with no report yet.\n */\n private unreported(records: readonly LogRecord[]): LogRecord[] {\n return records.filter((record) => !this.pausedLoss.has(record));\n }\n\n /**\n * Counts a record dropped by a full hold buffer and passes it to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [record]);\n }\n\n /**\n * Batches records for asynchronous transmission to the upstream sender.\n * @param record Log record to forward.\n */\n private forward(record: LogRecord): void {\n this.forwardBuffer.push(record);\n if (this.forwardScheduled) {\n return;\n }\n this.forwardScheduled = true;\n\n queueMicrotask(() => {\n this.forwardScheduled = false;\n this.sendForwarded();\n });\n }\n\n /**\n * Hands the forward buffer's records to the bus.\n * @returns How many records went upstream.\n */\n private sendForwarded(): number {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n // An empty buffer makes no message. A forwarder always has a bus.\n const { bus } = this;\n if (records.length === 0 || !bus) {\n return 0;\n }\n\n return bus.sendRecords(records);\n }\n\n /**\n * Validates, samples and queues records from child frames or workers. A forwarded record\n * arrives already built, so this is the first point in this context where sampling can run.\n * Local records are sampled by RecordBuilder.\n * @param records Inbound payload from bus.\n */\n private ingestForwarded(records: unknown): void {\n if (this.destroyed) {\n return;\n }\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n const accepted: LogRecord[] = [];\n for (const record of records) {\n if (!isLogRecord(record)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n continue;\n }\n // A debug buffer record explains an error. Sampling by its key would drop it again.\n if (\n record.attributes[ATTR_DEBUG_BUFFER] !== true &&\n !shouldSample(record, this.config, this.remote.sampling?.current() ?? null)\n ) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n\n // A child context without redact forwards raw records, so the sender is the last gate.\n const redacted = this.builder.redactForwarded(record);\n if (redacted) {\n accepted.push(redacted);\n }\n }\n\n // Records that arrive while the context changes belong to neither identity. Report the\n // loss after sampling and redact, so onDrop never gets action names or journey ids that\n // redact masks.\n if (this.rotating) {\n this.drops.add(\"security_context\", accepted);\n return;\n }\n\n // The bus stays connected during a pause, but the sender sends nothing.\n if (!this.config.enabled) {\n this.drops.add(\"disabled\", accepted);\n return;\n }\n\n for (const record of accepted) {\n this.deliver(record);\n }\n }\n\n /** Flushes the startup records, adding the active journey to records that have none. */\n private releaseBootBuffer(): void {\n const buffered = this.bootBuffer.take();\n // The hooks have already seen every record, so a key added now would bypass redact.\n const { processors, redact } = this.config;\n const journey = processors.length === 0 && redact === undefined ? this.journey.current() : null;\n\n for (const record of buffered) {\n if (journey && !record.attributes[\"journey.id\"]) {\n record.attributes[\"journey.id\"] = journey.id;\n record.attributes[\"journey.name\"] = journey.name;\n }\n this.route(record);\n }\n }\n\n /**\n * Passes lost records to the onDrop report.\n * @param reason Why they were lost.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds, count) => {\n this.drops.add(reason, records, batchIds, count);\n };\n\n /**\n * Passes the evicted batches to the onDrop report and emits a warning record. The warning\n * records are throttled.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\n const now = Date.now();\n if (now - this.lastGapAt < GAP_REPORT_THROTTLE_MS) {\n return;\n }\n this.lastGapAt = now;\n\n new OneLogger(() => this, STORAGE_NAMESPACE).warn(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\n );\n };\n\n /** Creates and stores a new tab ID after a tab ID collision. */\n private regenerateTabId(): void {\n const fresh = newId(this.diagnostics);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n persistTabId(fresh, this.diagnostics, this.stores);\n this.builder.invalidateResource();\n }\n\n /**\n * Starts a new session in this context. Sends the open metric points, starts a new trace,\n * ends the active journey and clears the breadcrumbs. Other tabs pick up the new id at\n * their next startup.\n */\n newSession(): void {\n if (this.destroyed) {\n return;\n }\n\n drainDeferred(this);\n this.resetSession(newId(this.diagnostics));\n }\n\n /**\n * Closes the old session's work and starts the given session.\n * @param sessionId Id of the session to start.\n */\n private resetSession(sessionId: string): void {\n this.sessionPicked = true;\n // Close the old session's work first, so its points and root span keep the old id.\n this.collectPoints();\n this.tracing.rotate(\"explicit\");\n this.journey.end();\n // On a shared machine, the next user must not see the previous user's trail.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n // The replay buffer still shows the previous user's page. Drop it and start a new recording.\n this.replay?.reset();\n\n (this.identity as { sessionId: string }).sessionId = sessionId;\n this.sessionTouch.restart(sessionId);\n this.builder.invalidateResource();\n }\n\n /**\n * Changes the delivery context in one operation. Rotations run in call order, so a logout\n * that starts during a login still runs, after the login.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with the old context's records, and the flush deadline.\n * @returns Promise that resolves when the change completes. Invalid settings reject it.\n */\n rotateSecurityContext(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions = {},\n ): Promise<void> {\n if (this.destroyed) {\n return Promise.reject(new Error(\"The runtime has stopped.\"));\n }\n // Before a configure() call works, there's no context to leave and no routing to replace.\n if (!this.tunablesLocked) {\n return Promise.reject(\n new Error(\n \"The runtime is not configured. Call configure() before rotateSecurityContext().\",\n ),\n );\n }\n\n // A record from this call on belongs to neither context, so it's dropped from here.\n drainDeferred(this);\n this.rotating = true;\n const seq = ++this.rotationSeq;\n // Check the promise, not the flag. \"carry\" clears the flag before it stores old batches again.\n const run = (this.rotation ?? Promise.resolve())\n .catch(() => undefined)\n .then(() => this.runRotation(update, options, seq));\n this.rotation = run;\n const settle = (): void => {\n if (this.rotation === run) {\n this.rotation = undefined;\n this.rotating = false;\n this.retiring = undefined;\n }\n };\n run.then(settle, settle);\n return run;\n }\n\n /**\n * Runs one rotation once the earlier ones are done. The rotation code loads on the first call.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with the old context's records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the change completes.\n */\n private async runRotation(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n ): Promise<void> {\n if (this.destroyed) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // A forwarder sends through its owner, so this is a usage error and its delivery stays open.\n await this.started;\n if (this.role() === \"forwarder\") {\n throw new Error(\n \"Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.\",\n );\n }\n\n let rotate: typeof rotateContext;\n try {\n rotate = (await import(\"./rotation\")).rotateContext;\n } catch (error) {\n // The app asked to leave this context, so a rotation that can't run closes it.\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The library could not load the security-context rotation.\",\n undefined,\n error,\n );\n await this.closeDelivery();\n throw error;\n }\n\n // shutdown() ran during the load, so a rotation now would delete stored batches unreported.\n if (this.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n await rotate(this.rotationHost(), update, options, seq);\n }\n\n /**\n * Returns the changes the rotation code can make to this runtime's private state.\n * @returns The rotation host.\n */\n private rotationHost(): RotationHost {\n return {\n runtime: this,\n quiet: new Diagnostics(),\n senderLoaded: async () => {\n await this.senderLoad;\n },\n allowed: (input) => this.allowed(input),\n closeDelivery: () => this.closeDelivery(),\n closeContext: () => {\n // The old context's last points and root span still go to its own sender.\n this.closingContext = true;\n try {\n this.collectPoints();\n this.tracing.end();\n this.journey.end();\n } finally {\n this.closingContext = false;\n }\n },\n takeOld: () => {\n const held = [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ];\n const sender = this.sender ?? this.parkedSender;\n // A flush during the retire still sees these records, so it doesn't call them lost.\n this.retiring = sender;\n const carried = this.carried;\n this.forwardBuffer = [];\n this.carried = [];\n this.sender = undefined;\n this.senderLoad = undefined;\n this.parkedSender = undefined;\n return { held, sender, closed: this.deliveryClosed, carried };\n },\n drop: (records) => {\n this.drops.add(\"security_context\", this.unreported(records));\n },\n storeAccess: () => this.storeAccess(),\n advanceIdentity: () => {\n this.advanceIdentity();\n },\n openDelivery: async () => {\n this.deliveryClosed = false;\n await this.syncSender();\n this.bus?.rotateContext();\n },\n endRotation: (seq) => {\n // A queued rotation keeps the flag up, because a later record belongs to its context.\n this.rotating = seq !== this.rotationSeq;\n },\n route: (record) => {\n this.route(record);\n },\n adopt: async (stored) => {\n // A pause loads no sender, so the next sender adopts them. With no destination, they\n // stay parked under the old id, so none is lost.\n if (!this.config.enabled) {\n this.carried = [...stored];\n return;\n }\n await this.sender?.adopt(stored, this.config.securityContext.id);\n },\n };\n }\n\n /**\n * Stops delivery after a rotation fails. The app asked to leave this context, so its endpoint\n * and headers send no record until a rotation succeeds. The old records stay stored under\n * the old id, and the next rotation that succeeds applies its rule to them.\n */\n private async closeDelivery(): Promise<void> {\n this.deliveryClosed = true;\n this.diagnostics.report(\n \"security.rotation_failed\",\n \"The security-context rotation failed. The library sends no record until a rotation succeeds.\",\n );\n\n // A load in progress sees the closed flag and parks its own sender.\n await this.senderLoad;\n const old = this.sender;\n this.sender = undefined;\n this.senderLoad = undefined;\n if (old) {\n await this.parkSender(old);\n }\n\n // These records arrived during the rotation, so they belong to the context the app left.\n this.drops.add(\"security_context\", this.unreported(this.pendingRecords.take()));\n }\n\n /**\n * Stops a sender of a closed context and keeps it, so the next rotation that succeeds can\n * apply its rule to the records of that context.\n * @param sender The sender to stop.\n */\n private async parkSender(sender: Sender): Promise<void> {\n this.parkedSender = sender;\n\n await this.diagnostics.guardAsync(\n \"pipeline.crashed\",\n \"The delivery stack of the old context did not stop. The next rotation that succeeds retires it.\",\n () => sender.pause(this.config.securityContext.id),\n );\n }\n\n /**\n * Collects this runtime's state for a support ticket. The app decides where to send it.\n * @param health Health snapshot from the facade, with the logger cache counts.\n * @returns Promise that resolves to the JSON-safe bundle.\n */\n async debugBundle(health: ObservabilityHealth): Promise<DebugBundle> {\n const { configSummary } = await import(\"./debug-bundle\");\n // Build the breadcrumbs as a record so the privacy hooks run, as they do for an error record.\n const { record } = this.builder.build(\n {\n level: \"INFO\",\n type: \"system\",\n body: \"debug bundle\",\n namespace: DIAGNOSTICS_NAMESPACE,\n payload: { [ATTR_BREADCRUMBS]: this.breadcrumbs.snapshot() },\n },\n true,\n );\n const attributes = record?.attributes ?? {};\n const crumbs = attributes[ATTR_BREADCRUMBS];\n const pageUrl = attributes[ATTR_PAGE_URL];\n\n return {\n createdAt: new Date().toISOString(),\n sdkVersion: this.sdkVersion,\n health,\n diagnostics: this.diagnostics.snapshot(),\n resource: record?.resource ?? {},\n pageUrl: typeof pageUrl === \"string\" ? pageUrl : \"\",\n breadcrumbs: Array.isArray(crumbs) ? crumbs : [],\n debugBuffer: this.debugBuffer.snapshot(),\n config: configSummary(this.config, this.limits, this.diagnostics),\n };\n }\n\n /**\n * Reads this runtime's state. Doesn't wait for startup or for the sender to load.\n * @returns State, delivery counts and policies. The facade adds the logger cache counts.\n */\n async health(): Promise<Omit<ObservabilityHealth, \"loggerCache\">> {\n const sent = this.sender?.stats();\n const issues: ObservabilityHealth[\"issues\"] = [];\n if (this.mismatchVersion) {\n issues.push(\"runtime.version_mismatch\");\n }\n if (this.contextMismatch) {\n issues.push(\"security.context_mismatch\");\n }\n const { redact, processors } = this.config;\n if (redact === REFUSE_RECORDS || processors.includes(REFUSE_RECORDS)) {\n issues.push(\"records.refused\");\n }\n if (this.deliveryClosed) {\n issues.push(\"security.rotation_failed\");\n } else if (\n // A pause loads no sender, and that isn't a fault.\n this.ready &&\n this.config.enabled &&\n this.hasDestination() &&\n this.role() === \"sender\" &&\n !this.sender\n ) {\n issues.push(\"sender.unavailable\");\n }\n const { sourcePolicy, maxMessageBytes, maxRecordsPerMessage, maxMessagesPerSecond } =\n this.config.bus;\n return {\n delivery: {\n pending: (sent?.pending ?? 0) + this.heldRecords(),\n inFlight: sent?.inFlight ?? 0,\n stored: await this.storedBatches(),\n lastSendAt: this.lastSendAt,\n // A rotation builds a new sender, so these start again with it.\n lastFailureAt: sent?.lastFailureAt ?? null,\n consecutiveFailures: sent?.consecutiveFailures ?? 0,\n throttledUntil: sent?.throttledUntil ?? null,\n dropped: this.drops.counts(),\n },\n sdkVersion: this.sdkVersion,\n owningSdkVersion: this.mismatchVersion,\n status: this.destroyed\n ? \"stopped\"\n : !this.tunablesLocked\n ? \"unconfigured\"\n : !this.config.enabled\n ? \"disabled\"\n : this.rotating\n ? \"rotating\"\n : issues.length\n ? \"degraded\"\n : !this.ready\n ? \"starting\"\n : \"ready\",\n mode:\n this.role() === \"forwarder\"\n ? \"forwarder\"\n : this.hasDestination()\n ? \"sender\"\n : \"console-only\",\n senderReady:\n this.sender !== undefined &&\n this.config.enabled &&\n !this.destroyed &&\n !this.rotating &&\n !this.deliveryClosed,\n configurationLocked: this.config.lockConfiguration,\n issues,\n securityContext: { ...this.config.securityContext },\n storagePersistence: this.storagePersistence,\n bus: { sourcePolicy, maxMessageBytes, maxRecordsPerMessage, maxMessagesPerSecond },\n };\n }\n\n /**\n * Returns what opening the store needs when no sender runs.\n * @returns The config, the reporter and the kept memory store.\n */\n private storeAccess(): StoreAccess {\n return { config: this.config, diagnostics: this.diagnostics, memory: this.memoryStorage };\n }\n\n /**\n * Counts the stored batches. After a failed rotation, the parked sender's store still holds\n * the closed context's batches, and they count until a rotation retires them.\n * @returns Promise that resolves to the number of stored batches.\n */\n private async storedBatches(): Promise<number> {\n return (await (this.sender ?? this.parkedSender)?.queueDepth()) ?? 0;\n }\n\n /**\n * Sends the records in memory and waits until each one has a final state or the time limit\n * passes. A forwarder hands its records to its sender, then asks the sender to flush.\n * @param options How long to wait. A value it can't use reports config.invalid.\n * @returns Promise that resolves to what became of the records in memory at the call. It\n * never rejects.\n */\n flush(options?: unknown): Promise<FlushResult> {\n return this.flushFor(this.flushTimeout(options), true);\n }\n\n /**\n * Runs a flush with a time limit that is already in range.\n * @param timeoutMs How long to wait, in milliseconds.\n * @param collect True to send the open interval of the meter and the profiler first. A flush\n * that a child asks for doesn't, otherwise each request would make this context build points.\n * @returns Promise that resolves to the flush result.\n */\n private async flushFor(timeoutMs: number, collect: boolean): Promise<FlushResult> {\n drainDeferred(this);\n if (collect) {\n this.collectPoints();\n }\n\n const idle = this.idle();\n if (idle) {\n return idle;\n }\n\n const ends = Date.now() + timeoutMs;\n let stop!: () => void;\n const expired = new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n unrefTimer(timer);\n stop = () => {\n clearTimeout(timer);\n };\n });\n\n try {\n return await this.flushBefore(ends, expired);\n } finally {\n stop();\n }\n }\n\n /**\n * Waits for startup and the delivery stack, then flushes the sender or asks the upstream one.\n * @param ends Epoch time in milliseconds of the deadline.\n * @param expired Resolves at the deadline.\n * @returns The flush result.\n */\n private async flushBefore(ends: number, expired: Promise<void>): Promise<FlushResult> {\n // These records wait for startup or for the sender, and they're lost if no sender loads.\n const held = this.heldRecords();\n\n // A record waits in a hold buffer during startup, which loads the first sender, and while a\n // later configure() loads one. The flush would miss it without this wait. Otherwise don't\n // wait, so the snapshot and the forward buffer handover happen in the call itself.\n const loading = this.ready ? this.senderLoad : this.started;\n if (loading && (!this.ready || !this.sender)) {\n const loaded = await Promise.race([loading.then(() => true), expired.then(() => false)]);\n if (!loaded) {\n return settled({ pending: this.waiting() });\n }\n }\n\n const { bus } = this;\n const forwarder = bus?.getRole() === \"forwarder\";\n\n // A pause or a shutdown during the wait leaves nothing to send.\n const idle = this.idle();\n if (idle) {\n return idle;\n }\n\n if (forwarder) {\n // The records go before the request on the same link, so they're in the sender's snapshot.\n // A record that the bus doesn't send, for its size or for no owner, is lost here.\n const total = this.forwardBuffer.length;\n const forwarded = this.sendForwarded();\n const lost = total - forwarded;\n // The sender gets a share of the time left, so its answer arrives before this call ends.\n const share = Math.floor(Math.max(0, ends - Date.now()) * FLUSH_REQUEST_SHARE);\n const answer = await bus.requestFlush(share, expired);\n return answer\n ? { ...answer, forwarded, dropped: answer.dropped + lost }\n : settled({ forwarded, pending: forwarded, dropped: lost });\n }\n\n const { sender } = this;\n if (!sender) {\n // During a rotation the old records wait for its rule. Without a sender, they're lost.\n return this.rotating\n ? settled({ pending: held + this.waiting() })\n : flushResult(\"complete\", { dropped: held });\n }\n\n return settled(await sender.flushUntil(expired));\n }\n\n /**\n * Returns the result for a runtime that sends nothing now: before the start, after a failed\n * first configure(), during a pause and after shutdown().\n * @returns The \"inactive\" result with the records that wait in memory, or null.\n */\n private idle(): FlushResult | null {\n if (this.tunablesLocked && this.config.enabled && !this.destroyed) {\n return null;\n }\n\n // A stopped runtime sends nothing more, so no record waits for it.\n return flushResult(\"inactive\", { pending: this.destroyed ? 0 : this.waiting() });\n }\n\n /**\n * Counts the records in the hold buffers and the forward buffer.\n * @returns The record count.\n */\n private heldRecords(): number {\n return this.bootBuffer.length + this.pendingRecords.length + this.forwardBuffer.length;\n }\n\n /**\n * Counts the records in memory: the hold buffers, the forward buffer, and the buffers, the\n * queue and the requests of the sender and of a sender that a rotation retires.\n * @returns The record count.\n */\n private waiting(): number {\n let total = this.heldRecords();\n for (const sender of [this.sender, this.retiring]) {\n const sent = sender?.stats();\n total += sent ? sent.pending + sent.inFlight : 0;\n }\n return total;\n }\n\n /**\n * Copies a call's options. A value that isn't an object reports config.invalid with the text,\n * and so does a getter that throws.\n * @param options The app's options. undefined and null read as no options.\n * @param text The text of the report.\n * @returns The copy, or undefined after a report.\n */\n private readOptions(options: unknown, text: string): Record<string, unknown> | undefined {\n // A JavaScript caller can pass a string, or an object with a getter that throws.\n if (typeof options !== \"object\" && options !== undefined) {\n this.diagnostics.report(\"config.invalid\", text);\n return undefined;\n }\n\n return this.diagnostics.guard(\"config.invalid\", text, () => ({ ...options }));\n }\n\n /**\n * Reads flush()'s time limit. A value it can't use reports config.invalid, and the default\n * applies. null options and a null timeoutMs give the default, as in shutdown() and\n * rotateSecurityContext().\n * @param options The app's options.\n * @returns The time limit in milliseconds.\n */\n private flushTimeout(options: unknown): number {\n const read = this.readOptions(options, FLUSH_INVALID);\n if (!read) {\n return FLUSH_TIMEOUT_MS;\n }\n\n const ms = read.timeoutMs ?? FLUSH_TIMEOUT_MS;\n if (typeof ms === \"number\" && ms >= 0 && ms <= FLUSH_TIMEOUT_MAX_MS) {\n return ms;\n }\n\n this.diagnostics.report(\"config.invalid\", FLUSH_INVALID);\n return FLUSH_TIMEOUT_MS;\n }\n}\n\n/**\n * Compares resolved settings without JSON conversion. Functions are compared by identity.\n * The seen map keeps a cycle from causing repeated comparisons.\n * @param a First value.\n * @param b Second value.\n * @param seen Object pairs already compared.\n * @returns True if the values are equal.\n */\nfunction sameConfig(a: unknown, b: unknown, seen = new WeakMap<object, object>()): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (a instanceof RegExp && b instanceof RegExp) {\n return String(a) === String(b);\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (seen.has(a)) {\n return seen.get(a) === b;\n }\n seen.set(a, b);\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return (\n ak.length === bk.length &&\n ak.every((key) => hasOwn(b, key) && sameConfig(Reflect.get(a, key), Reflect.get(b, key), seen))\n );\n}\n","import {\n TELEMETRY_SDK_VERSION,\n TRANSPORT_WORKER_PROTOCOL,\n TRANSPORT_WORKER_REFUSAL,\n TRANSPORT_WORKER_TYPE,\n} from \"../constants\";\nimport { Diagnostics, type DiagnosticHandler } from \"../core/diagnostics\";\nimport { isObject } from \"../utils/guards\";\n\nlet active: (() => void) | undefined;\n\n/** Installs the worker service synchronously before its delivery module loads. */\nexport function serveTransportWorker(\n options: { onDiagnostic?: DiagnosticHandler } = {},\n): () => void {\n if (active) {\n return active;\n }\n const diagnostics = new Diagnostics(options.onDiagnostic);\n if (typeof document !== \"undefined\" || typeof addEventListener !== \"function\") {\n diagnostics.report(\"config.invalid\", \"Call serveTransportWorker() in a dedicated worker.\");\n return () => undefined;\n }\n\n let stopped = false;\n let port: MessagePort | undefined;\n let detach: (() => void) | undefined;\n const onMessage = (event: MessageEvent<unknown>): void => {\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport worker could not read its connection.\",\n () => {\n const message = event.data;\n if (\n !isObject(message) ||\n message.p !== TRANSPORT_WORKER_PROTOCOL ||\n message.t !== TRANSPORT_WORKER_TYPE.connect\n ) {\n return;\n }\n if (event.ports.length === 0) {\n return;\n }\n const incoming = event.ports[0];\n if (port || message.v !== TELEMETRY_SDK_VERSION) {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n return;\n }\n\n port = incoming;\n void import(\"./worker-server\")\n .then((module) => {\n if (!stopped) {\n detach = module.serveWorkerPort(incoming, diagnostics);\n }\n })\n .catch((error: unknown) => {\n diagnostics.report(\n \"transport.http_error\",\n \"The transport worker delivery module could not load.\",\n undefined,\n error,\n );\n diagnostics.guard(\n \"transport.http_error\",\n \"The failed transport port could not be closed.\",\n () => {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n },\n );\n });\n },\n );\n };\n\n const stop = (): void => {\n if (stopped) {\n return;\n }\n stopped = true;\n active = undefined;\n removeEventListener(\"message\", onMessage);\n detach?.();\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport service could not close its port.\",\n () => {\n port?.postMessage(TRANSPORT_WORKER_REFUSAL);\n },\n );\n diagnostics.guard(\"transport.http_error\", \"The transport port could not close.\", () => {\n port?.close();\n });\n };\n addEventListener(\"message\", onMessage);\n active = stop;\n return stop;\n}\n","// src/transport/memory-transport.ts\n//\n// A transport for tests that keeps every batch in memory, so a test can check the records the\n// library sends without a network or a fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport for tests that keeps every batch in memory. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of every accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns every request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets every batch. The answer set with respondWith stays. */\n clear(): void;\n /**\n * Sets the answer for all later batches. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps every batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\n };\n}\n","// src/index.ts\n//\n// The library's public entry point. Exports the facade API, the logging primitives and\n// the types.\n\nimport type { WorkerLike } from \"./bus/links\";\nimport type { Journey } from \"./core/journey\";\nimport { INSTRUMENT_OPTIONS_FAULT } from \"./constants\";\nimport { OneLogger, type OneLogger as Logger, type OneLoggerOptions } from \"./core/logger\";\nimport { measureCall } from \"./core/measure\";\nimport { makeCounter, makeGauge, makeHistogram } from \"./core/meter\";\nimport { profilerCore } from \"./core/profiler\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport { isObject } from \"./utils/guards\";\nimport type { ObservabilityConfig } from \"./models/config\";\nexport type {\n ReplayLoader,\n ReplayPluginLoader,\n ReplayPluginTools,\n ReplaySegment,\n} from \"./models/replay\";\nimport type {\n FlushOptions,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n ShutdownOptions,\n} from \"./models/config\";\nimport type { DebugBundle, FlushResult, ObservabilityHealth } from \"./models/health\";\nimport type { FrameOptions, SourceOptions } from \"./models/bus\";\nexport type { FrameOptions, SourceOptions, BusPermission } from \"./models/bus\";\nimport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Profiler,\n} from \"./models/metric\";\n\nexport { serveTransportWorker } from \"./transport/worker-entry\";\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, Logger, ObservabilityConfig, OneLoggerOptions };\nexport type {\n BatchingOptions,\n BufferingOptions,\n BusOptions,\n CaptureLimitsOptions,\n CaptureOptions,\n ConsoleCaptureOptions,\n ConsoleOutputOptions,\n ConsoleStyles,\n CorrelationOptions,\n DebugBufferOptions,\n DeliveryOptions,\n DiagnosticsOptions,\n FlushOptions,\n InteractionOptions,\n JourneyOptions,\n LimitsOptions,\n LoggerCacheOptions,\n LongFramesOptions,\n MetadataOptions,\n MetricsOptions,\n ProfilerOptions,\n RemoteCaptureFlag,\n ReplayOptions,\n ResourceTimingOptions,\n RetentionOptions,\n RoutingOptions,\n SamplingOptions,\n SecurityContextOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n ShutdownOptions,\n StorageOptions,\n StorageScope,\n UserTimingOptions,\n WebVitalsOptions,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type {\n DebugBundle,\n DeliveryHealth,\n FlushResult,\n FlushStatus,\n ObservabilityHealth,\n} from \"./models/health\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Probe,\n ProbeOptions,\n Profiler,\n} from \"./models/metric\";\nexport type { CapturePlugin, PluginContext } from \"./models/plugin\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { StorageAdapter } from \"./models/storage\";\n\n/**\n * Cached loggers, keyed by namespace. A scoped logger never goes in this map.\n * A logger looks up the runtime on every write, so the cache stays valid across\n * configure() and shutdown().\n */\nconst loggers = new Map<string, Logger>();\n\n/**\n * Returns the active runtime. After shutdown() that is the stopped runtime, which does\n * nothing. Before the first configure(), it makes an unconfigured runtime, which holds records\n * in memory and starts nothing until a configure() call works.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\n if (runtime) {\n return runtime;\n }\n\n // Make the unconfigured runtime, so a log call before configure() doesn't throw.\n return ObservabilityRuntime.configure({}, true);\n}\n\n/**\n * Initializes or reconfigures the observability runtime. The first call that works starts the\n * runtime. Before it, the library patches, stores and sends nothing, and the records logged\n * before it go out with its hooks and identity. With `enabled: false`, the start waits for the\n * first `enabled: true`.\n * With `payloadMode: \"defer\"`, logger records are built in idle time. With the debug buffer on,\n * they are still built at the call.\n * @param config Consumer configuration options.\n */\nexport function configure(config: Partial<ObservabilityConfig>): void {\n ObservabilityRuntime.configure(config);\n trimLoggerCache();\n}\n\n/**\n * Locks or unlocks the configuration. The lock isn't access control against other code on\n * this origin. Call it after configure(), because a lock before the first configure() refuses\n * that call too, and the runtime then never starts.\n * @param locked True to refuse changes through configure().\n */\nexport function setConfigurationLocked(locked: boolean): void {\n requireRuntime().setConfigurationLocked(locked);\n}\n\n/**\n * Stops delivery for the old context and starts it for the new one. A call during another\n * rotation runs after it.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with old records, and the flush deadline.\n * @returns Promise that resolves once the change is complete. It rejects before the first\n * configure() call that works, while a failed first call still refuses records, and after\n * shutdown().\n */\nexport function rotateSecurityContext(\n update: SecurityContextUpdate,\n options?: SecurityContextRotationOptions,\n): Promise<void> {\n return requireRuntime().rotateSecurityContext(update, options);\n}\n\n/**\n * Reads this SDK copy's runtime state, policies and delivery state. The `delivery` block holds\n * the record and batch counts, the send and failure times, the throttle end and the losses. It\n * doesn't wait for startup or for the delivery stack to load.\n * @returns Promise that resolves to the current state.\n */\nexport async function getHealth(): Promise<ObservabilityHealth> {\n const runtime = requireRuntime();\n trimLoggerCache();\n return {\n ...(await runtime.health()),\n loggerCache: { ...runtime.config.loggerCache, size: loggers.size },\n };\n}\n\n/**\n * Collects the library's state for a support ticket. The bundle holds the health, the\n * diagnostic counters, the resource, the breadcrumbs, the debug buffer and a config summary.\n * The summary has no headers and no URL query, and a plugin or custom serializer shows up by\n * name only. The breadcrumbs go through the privacy hooks. A debug buffer record keeps its\n * context attributes. Where the bundle gets sent is up to the app.\n * @returns Promise that resolves to a JSON-safe bundle.\n */\nexport async function collectDebugBundle(): Promise<DebugBundle> {\n const health = await getHealth();\n return requireRuntime().debugBundle(health);\n}\n\n/**\n * Removes the least recently used loggers until the cache is within its limit.\n * @returns Cache limit, or null for no limit.\n */\nfunction trimLoggerCache(): number | null {\n const limit = (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.config\n .loggerCache.maxEntries;\n const max = limit === undefined ? 256 : limit;\n if (max !== null) {\n // A Map keeps insertion order, so the first keys are the least recently used loggers.\n for (const key of loggers.keys()) {\n if (loggers.size <= max) {\n break;\n }\n loggers.delete(key);\n }\n }\n return max;\n}\n\n/**\n * Returns the cached logger for a namespace, or a new scoped logger.\n * @param namespace Application subsystem or module namespace.\n * @param options Context attributes for this logger only.\n * @returns Logger for the namespace. You get a new logger if you pass options or the cache\n * is disabled.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): Logger {\n const max = trimLoggerCache();\n if (options || max === 0) {\n return new OneLogger(requireRuntime, namespace, options);\n }\n\n let logger = loggers.get(namespace);\n\n logger ??= new OneLogger(requireRuntime, namespace);\n\n // Move a cached logger to the end, so the first entry is always the least recently used.\n loggers.delete(namespace);\n loggers.set(namespace, logger);\n trimLoggerCache();\n\n return logger;\n}\n\n/**\n * Returns the default root logger.\n * @returns The logger for the \"app\" namespace.\n */\nfunction root(): Logger {\n return getLogger(\"app\");\n}\n\n/**\n * Logs a trace-level debug record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function trace(message: string, payload?: Record<string, unknown>): void {\n root().trace(message, payload);\n}\n\n/**\n * Logs a debug-level record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function debug(message: string, payload?: Record<string, unknown>): void {\n root().debug(message, payload);\n}\n\n/**\n * Logs an informational record.\n * @param message Informational message.\n * @param payload Optional context attributes.\n */\nexport function info(message: string, payload?: Record<string, unknown>): void {\n root().info(message, payload);\n}\n\n/**\n * Logs a warning record.\n * @param message Warning message.\n * @param payload Optional context attributes.\n */\nexport function warn(message: string, payload?: Record<string, unknown>): void {\n root().warn(message, payload);\n}\n\n/**\n * Logs an error record, with the error that caused it and the breadcrumbs.\n * @param message Error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function error(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().error(message, err, payload);\n}\n\n/**\n * Logs a fatal record, with the error that caused it and the breadcrumbs.\n * @param message Fatal error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(message, err, payload);\n}\n\n/**\n * Logs a single user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\nexport function logAction(name: string, payload?: Record<string, unknown>): void {\n root().logAction(name, payload);\n}\n\n/**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\nexport function logEvent(name: string, payload?: Record<string, unknown>): void {\n root().logEvent(name, payload);\n}\n\n/**\n * Reports instrument options the library couldn't read. Without a runtime there is nowhere to\n * report to, so it does nothing.\n * @param error What reading the options threw.\n */\nfunction optionsFault(error: unknown): void {\n ObservabilityRuntime.current()?.diagnostics.report(\n \"config.invalid\",\n INSTRUMENT_OPTIONS_FAULT,\n undefined,\n error,\n );\n}\n\n/**\n * Returns a counter. Values are summed in memory, and every interval the library sends one\n * point per attribute set. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The counter.\n */\nexport function counter(name: string, options: InstrumentOptions = {}): Counter {\n return makeCounter(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Returns a gauge. It keeps the last value for each attribute set in memory, and every interval\n * the library sends that value as one point. With `metricsEndpoint`, the point is an OTLP gauge.\n * A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The gauge.\n */\nexport function gauge(name: string, options: InstrumentOptions = {}): Gauge {\n return makeGauge(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Returns a histogram. Values are counted into buckets in memory, and every interval the\n * library sends one point per attribute set. A handle stays valid across configure() and\n * shutdown().\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @returns The histogram.\n */\nexport function histogram(name: string, options: HistogramOptions = {}): Histogram {\n return makeHistogram(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Times an operation with named phases. Every phase and the total go into duration histograms.\n * With `tracesEndpoint` set, the operation is also a span with one child span per phase.\n * @param name Operation name. Every name creates one series.\n * @param attributes Attribute set for every histogram point. Keep it small.\n * @returns The operation's handle.\n */\nexport function startMeasure(name: string, attributes?: MetricAttributes): Measure {\n return requireRuntime().startMeasure(name, attributes);\n}\n\n/**\n * Times a function call with a measure, as `startMeasure()` does. If the result has a `then`\n * function, the measure ends when it settles. A throw or a rejection ends it with the outcome\n * \"error\", and the error goes to the caller unchanged.\n * @param name Operation name. Every name creates one series.\n * @param fn The function to call.\n * @param attributes Attribute set for every histogram point. Keep it small.\n * @returns Whatever `fn` returned, or the result of its `then` call.\n */\nexport function measure<T>(name: string, fn: () => T, attributes?: MetricAttributes): T {\n const runtime = requireRuntime();\n return measureCall(runtime.startMeasure(name, attributes), fn, runtime.diagnostics);\n}\n\n/**\n * Starts the session replay recorder. With `replay.requireConsent` set, nothing is recorded\n * until you call this, so call it once the user agrees. Does nothing while `replay.enabled`\n * is false.\n */\nexport function startReplay(): void {\n requireRuntime().setReplay(true);\n}\n\n/**\n * Stops the session replay recorder and drops any replay events that haven't been sent. With\n * `replay.requireConsent` set, the recorder stays off until the next `startReplay()`.\n */\nexport function stopReplay(): void {\n requireRuntime().setReplay(false);\n}\n\n/**\n * Times spans of app code with probes. A probe is a named handle with `begin()`, `end()`,\n * `endAfterPaint()` and `record()`, and `time()` times a single function call. Once per\n * interval the library sends one `ui.profile.duration` histogram for every probe that has data.\n *\n * The profiler is off by default. Set `profiler.enabled` to true to turn it on. While it is\n * off, probes don't read the clock. After `shutdown()` a probe does nothing until a later\n * `configure()` turns the profiler back on. Probes stay valid across `configure()` and\n * `shutdown()`, and you can create them before `configure()`. No call ever throws.\n * @example\n * const render = profiler.probe(\"grid.render\");\n * const token = render.begin();\n * drawGrid();\n * render.end(token);\n */\nexport const profiler: Profiler = {\n // Probe calls report to whichever runtime is current. Once shutdown() resolves, the stopped\n // runtime gets nothing.\n probe: (name, options) =>\n profilerCore().probe(name, options, ObservabilityRuntime.current()?.diagnostics),\n time: (name, fn) => profilerCore().time(name, fn, ObservabilityRuntime.current()?.diagnostics),\n};\n\n/**\n * Adds a breadcrumb to the trail. The next error record carries the trail.\n * @param message Description of the event.\n * @param data Optional metadata. It is copied right away.\n */\nexport function addBreadcrumb(message: string, data?: Record<string, unknown>): void {\n requireRuntime().addBreadcrumb(message, data);\n}\n\n/**\n * Merges attributes into the ambient context. Every later record includes them. A null value\n * removes its key, and an undefined value keeps the current value. A value that isn't an object\n * reports `config.invalid` and changes nothing.\n * @param values Attributes to merge.\n */\nexport function setContext(values: Record<string, unknown>): void {\n const runtime = requireRuntime();\n // A string would give one attribute for each character.\n if (!isObject(values)) {\n runtime.diagnostics.report(\n \"config.invalid\",\n \"setContext() takes an object. The library keeps the current context.\",\n );\n return;\n }\n\n // A getter or a Proxy trap on the app's object can throw, and the call must not.\n runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the values of setContext().\",\n () => {\n runtime.context.merge(values);\n },\n );\n}\n\n/**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to delete.\n */\nexport function removeContext(key: string): void {\n requireRuntime().context.remove(key);\n}\n\n/**\n * Starts a new journey correlation context.\n * @param name Journey workflow identifier.\n * @param options `parent` links the active journey as the parent. `id` sets the journey id, a\n * string of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". Without it, the library generates one.\n * @returns The started Journey.\n */\nexport function startJourney(name: string, options?: { parent?: boolean; id?: string }): Journey {\n return requireRuntime().journey.start(name, options);\n}\n\n/** Ends the active journey correlation context. */\nexport function endJourney(): void {\n requireRuntime().journey.end();\n}\n\n/**\n * Returns the active journey, or null if none is in progress.\n * @returns The active Journey, or null.\n */\nexport function currentJourney(): Journey | null {\n return requireRuntime().journey.current();\n}\n\n/**\n * Serializes the active journey's metadata into a URL token that another context can adopt.\n * @returns The token, or null if no journey is active or the token is above the size limit.\n */\nexport function getJourneyToken(): string | null {\n return requireRuntime().journey.getToken();\n}\n\n/**\n * Adopts a serialized journey token in this application realm.\n * @param token Serialized journey token.\n * @returns True if the token is valid and the runtime adopted it.\n */\nexport function adoptJourney(token: string): boolean {\n return requireRuntime().journey.adopt(token, \"manual\", true);\n}\n\n/**\n * Connects a Web Worker or MessagePort to the document bus, so its records get routed.\n * @param worker The Worker or MessagePort to connect.\n * @param options The worker's permissions. Defaults to \"records\".\n * @returns Function that removes this registration.\n */\nexport function registerWorker(worker: WorkerLike, options?: SourceOptions): () => void {\n return requireRuntime().registerWorker(worker, options);\n}\n\n/**\n * Registers one frame or window at an exact origin.\n * @param frame Child frame or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\nexport function registerFrame(\n frame: HTMLIFrameElement | Window,\n options: FrameOptions,\n): () => void {\n return requireRuntime().registerFrame(frame, options);\n}\n\n/** Starts a new distributed trace. Later records and requests carry the new trace id. */\nexport function newTrace(): void {\n requireRuntime().tracing.rotate(\"explicit\");\n}\n\n/**\n * Returns the W3C traceparent headers to put on an outgoing HTTP request.\n * @returns Map of trace header names to values.\n */\nexport function getTraceHeaders(): Record<string, string> {\n return requireRuntime().tracing.headers();\n}\n\n/**\n * Builds any deferred calls and the open metric interval, sends the records in memory, and\n * waits until each one has a final state or the time limit passes. The snapshot is the records\n * in memory at the call. A record logged later isn't in it. Before startup ends, the call waits\n * for startup and the delivery stack first, and the snapshot then also holds the records logged\n * during that wait. A forwarder hands its records to its sender and asks the sender to flush.\n * At the limit the call returns, and the work goes on in the background. The stored batches\n * from earlier failures and the replay segments are outside the snapshot. Before the first\n * `configure()` call that works, during a pause and after `shutdown()`, it sends nothing and\n * returns the status \"inactive\" at once.\n * @param options How long to wait. `timeoutMs` is 0 to 600000 ms, and the default is 5000.\n * @returns Promise that resolves to the counts of the snapshot's records. It never rejects.\n */\nexport function flush(options?: FlushOptions): Promise<FlushResult> {\n return requireRuntime().flush(options);\n}\n\n/**\n * Starts a new correlation in this tab. Ends the active journey and starts a new trace. Other\n * tabs pick up the new id at their next startup. For a logout or a tenant change, use\n * rotateSecurityContext().\n */\nexport function newSession(): void {\n requireRuntime().newSession();\n}\n\n/**\n * Returns a snapshot of the cumulative diagnostic event counts.\n * @returns Map of diagnostic codes to how often each one occurred.\n */\nexport function getDiagnosticCounters(): Record<string, number> {\n return requireRuntime().diagnostics.snapshot();\n}\n\n/**\n * Stops every runtime subsystem. By default it flushes the records first, then runs the exit\n * flush, and a request still open after that is cancelled with its stored batch kept. With\n * `pending: \"discard\"` it sends nothing and reports each record in memory to `onDrop` with the\n * reason \"discarded\". `clearStorage` also removes the stored batches and the stored ids, for a\n * logout on a shared device. A call before any log call or `configure()` does nothing. A call\n * after `shutdown()` stops nothing more, but its `clearStorage` still removes the stored data,\n * once the first call ends. The next `configure()` starts a new runtime.\n * @param options What to do with the records that wait, and which storage to remove.\n * @returns Promise that resolves once shutdown is complete.\n */\nexport async function shutdown(options?: ShutdownOptions): Promise<void> {\n await (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.destroy(options);\n}\n"],"mappings":"A,uqBAaA,IAAMmJ,EAAS,IAAI,QAGnB,SAASC,EAAO,EAA4B,CAC1C,IAAMC,EAAOC,EAAM,KACfD,IAAS,IAAA,KACXC,EAAM,YAAY,MAAM,mBAAoB,gDAAmD,CAC7F,mBAAmBD,CAAI,CACzB,CAAC,EACD,EAAM,KAAO,IAAA,IAGf,aAAaC,EAAM,KAAK,EACxB,EAAM,MAAQ,IAAA,EAChB,CAGA,SAASC,EAAS,EAAe,EAA4B,CACvD,OAAO,qBAAwB,YAAc,OAAO,oBAAuB,aAC7E,EAAM,KAAOD,EAAM,YAAY,MAC7B,mBACA,gDAEE,oBACG,GAAa,CACZE,EAAMC,EAAOH,EAAOI,CAAQ,CAC9B,EACA,CAAE,QAAS1J,EAAAA,CAAsB,CACnC,CACJ,EACIsJ,EAAM,OAAS,IAAA,MAKrB,EAAM,MAAQ,eAAiB,CAC7BE,EAAMC,EAAOH,CAAK,CACpB,EAAG,CAAC,EACJf,EAAA,EAAWe,EAAM,KAAK,EACxB,CAGA,SAASE,EAAM,EAAe,EAAsB,EAA+B,CACjF,GAAIL,EAAO,IAAIM,CAAK,IAAMH,GAASA,EAAM,SACvC,OAGFF,EAAOE,CAAK,EACZ,EAAM,SAAW,GACjB,IAAMK,EAAOL,EAAM,KACnB,EAAM,KAAO,CAAC,EACd,IAAIM,EAAQ,EAEZ,KACEA,EAAQD,EAAK,SACZ,CAACD,GAAaA,EAAS,YAAcE,IAAU,GAAMF,EAAS,cAAc,EAAI,IAQjF,GANAJ,EAAM,YAAY,MAChB,mBACA,iDACAK,EAAKC,EACP,EACA,IACIT,EAAO,IAAIM,CAAK,IAAMH,EACxB,OAIJ,EAAM,KAAO,CAAC,GAAGK,EAAK,MAAMC,CAAK,EAAG,GAAGN,EAAM,IAAI,EACjD,EAAM,SAAW,GACb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R_ERROR_DATA","ATTR_BREADCRUMBS","DEFAULT_METRIC_UNIT","METRIC_KEYS","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","METRIC_DEFAULT_BOUNDARIES","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","METRIC_KEYS","METRIC_DEFAULT_BOUNDARIES","ATTR_METRIC_OVERFLOW","RECORD_LIMITS","hasOwn","LEVEL_ORDER","isLibraryConsole","sanitize","ATTR_DEBUG_BUFFER","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","attributeOf","ATTR_JOURNEY_ID","isActionRecord","isActionRecord","BUS_MAX_BOOT_BUFFER_ACTIONS","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","METRIC_KEYS","SPAN_KEYS","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","LEVEL_BYPASS_TYPES","levelFor","LEVEL_ORDER","shouldSampleInput","currentUrl","recordedUrl","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_SEQ","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","shouldSample","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","REFUSE_RECORDS","isLogRecord","isLogLevel","isObject","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","SPAN_KEYS","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","isObject","recordedUrl","TELEMETRY_SDK_VERSION","DIAGNOSTICS_NAMESPACE","BUS_PROTOCOL","memoryStores","STORAGE_NAMESPACE","detectPlatform","resolveConfig","newId","resolveIdentity","SessionTouch","sampleKey","JOURNEY_OPTIONS","JourneyEngine","truncate","sanitize","TRACE_NAMESPACE","METRIC_NAMESPACE","profilerCore","REFUSE_RECORDS","LIBRARY_LOG_PREFIX","ROUTING_KEYS","BROWSER_STORES","REMOTE_CAPTURE_FLAGS","CAPTURE_NAMESPACE","INSTRUMENT_OPTIONS_FAULT","runAsLibraryRequest","isLogRecord","shouldSample","ATTR_BREADCRUMBS","ATTR_PAGE_URL","FLUSH_REQUEST_SHARE","FLUSH_TIMEOUT_MS","hasOwn","isObject","TRANSPORT_WORKER_TYPE","TRANSPORT_WORKER_REFUSAL","INSTRUMENT_OPTIONS_FAULT","profilerCore","isObject","require_constants","require_log_record","require_error_like","require_guards","require_unref","require_platform","require_defineProperty","require_identity","require_profiler","require_library_console","require_sanitize","require_library_request","require_config","require_batch","require_journey","require_sampling","require_observed_windows","queues","cancel","idle","queue","schedule","drain","owner","deadline","work","index","deferWrite","capacity","limit","diagnostics","drainDeferred","cancelDeferred","_work","LIBRARY_NAMESPACES","toError","known","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","message","error","name","bind","options","runtime","level","type","body","snapshot","journey","input","copied","hooks","keepsCrumb","protectedCrumb","dropped","safe","record","crumb","ships","asPayload","attributes","asError","shown","clean","LibraryLogger","_args","recordOnly","unit","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","traceparent","traceId","spanId","traceFlags","toTraceContext","ambient","TraceEngine","maxAgeMs","load","spans","otel","span","spanContext","old","next","carrier","\"traceparent\"","fromOtel","ctx","kept","flags","client","TOTAL_DURATION","PHASE_DURATION","createMeasure","label","startMs","startedAt","open","ended","epoch","at","closePhase","sinks","now","outcome","fields","measureCall","result","fn","then","chained","handle","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","copyBounds","bounds","i","isAscending","bound","fieldsOf","point","def","start","series","readOptions","fault","scalarDef","makeCounter","makeGauge","makeHistogram","boundaries","Meter","intervalMs","emit","policy","instrument","instruments","one","found","maxInstruments","valid","set","maxSeries","size","buckets","METHOD","ConsoleSink","settings","limits","prefix","method","details","styles","Sequence","BreadcrumbBuffer","recent","keep","ContextStore","values","DebugBuffer","enabled","maxRecords","oldest","entry","Diagnostics","handler","throttleMs","consoleFallback","total","code","by","event","addCapped","list","DropReporter","config","records","batchIds","summary","id","summaries","onDrop","HoldBuffer","actions","others","action","kind","cap","held","first","second","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","HOOK_STAGES","isFiniteNumber","isNumberList","isNanos","isTraceId","isSpanId","isParentId","isCounter","isHistogram","isSpanKind","isSpanStatus","COUNTER_FIELDS","HISTOGRAM_FIELDS","SPAN_FIELDS","LINK_FIELDS","groupsOf","fixedOf","fixed","group","keys","asAttributes","RecordBuilder","deps","minLevel","debug","forConsole","traceCtx","tracing","activeJourney","sampled","remote","seq","sequence","url","pageUrl","bytes","fromContext","fromProvider","fromScope","fromPayload","stages","redact","leveled","stamped","hooked","keptBytes","breadcrumbs","crumbBytes","processors","hook","current","stage","remeasured","changed","refused","candidate","provider","given","platform","identity","US_PER_MS","ROOT_NAMES","unixNano","ms","rootSpan","spanFields","CAPTURE_LOADERS","pluginIds","lastPluginId","pluginId","plugin","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","LOGGED_CRUMBS","FAILED_START","SHUTDOWN_INVALID","FLUSH_INVALID","NOTICE_CODES","captureKey","capture","recordDetail","detail","consoleOnly","sends","flushResult","counts","settled","ownVersion","ObservabilityRuntime","locked","resolve","origin","bus","reply","batch","mismatch","keeps","points","core","sink","consent","local","pinned","stopped","implicit","live","foundText","sameConfig","accepted","probe","maxProbes","section","sections","adds","removes","built","sessionIdleMs","sessionId","tabId","traceMaxAgeMs","captures","journeyReady","Bus","rotating","shared","timeoutMs","sender","Sender","storage","state","carried","stored","wire","framePhases","framePacing","replay","generation","replayKey","names","profiler","classes","WebSocketCapture","CaptureModule","plugins","metric","cancelled","detach","worker","frame","discard","scope","closing","parked","read","unset","clearStorage","knownScope","flushes","pending","buffered","ids","clearStored","paused","fresh","redacted","run","update","settle","rotate","plan","crumbs","configSummary","sent","issues","collect","ends","stop","expired","timer","loading","forwarder","forwarded","lost","share","answer","a","b","seen","ak","bk","active","serveTransportWorker","port","onMessage","incoming","module","createMemoryTransport","request","retryAfterMs","loggers","requireRuntime","configure","trimLoggerCache","setConfigurationLocked","rotateSecurityContext","getHealth","collectDebugBundle","health","max","getLogger","logger","root","trace","info","warn","err","fatal","logAction","logEvent","optionsFault","counter","gauge","histogram","startMeasure","measure","startReplay","stopReplay","addBreadcrumb","setContext","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","registerWorker","registerFrame","newTrace","getTraceHeaders","flush","newSession","getDiagnosticCounters","shutdown"],"sources":["../src/core/deferred.ts","../src/core/logger.ts","../src/utils/tracing.ts","../src/core/measure.ts","../src/core/meter.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/core/breadcrumbs.ts","../src/core/context.ts","../src/core/debug-buffer.ts","../src/core/diagnostics.ts","../src/core/drops.ts","../src/core/hold-buffer.ts","../src/core/record.ts","../src/core/spans.ts","../src/core/runtime.ts","../src/transport/worker-entry.ts","../src/transport/memory-transport.ts","../src/index.ts"],"sourcesContent":["import { DEFER_IDLE_TIMEOUT_MS, DEFER_QUEUE_LIMIT } from \"../constants\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One runtime's pending logger calls. A stopped runtime releases every payload reference. */\ninterface DeferredQueue {\n work: (() => void)[];\n diagnostics: Diagnostics;\n draining: boolean;\n idle?: number;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nconst queues = new WeakMap<object, DeferredQueue>();\n\n/** Cancels the scheduled callback before a synchronous drain or a shutdown. */\nfunction cancel(queue: DeferredQueue): void {\n const idle = queue.idle;\n if (idle !== undefined) {\n queue.diagnostics.guard(\"pipeline.crashed\", \"The idle callback could not be cancelled.\", () => {\n cancelIdleCallback(idle);\n });\n queue.idle = undefined;\n }\n\n clearTimeout(queue.timer);\n queue.timer = undefined;\n}\n\n/** Schedules one idle callback, or a timer in browsers without the idle API. */\nfunction schedule(owner: object, queue: DeferredQueue): void {\n if (typeof requestIdleCallback === \"function\" && typeof cancelIdleCallback === \"function\") {\n queue.idle = queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The idle callback could not be scheduled.\",\n () =>\n requestIdleCallback(\n (deadline) => {\n drain(owner, queue, deadline);\n },\n { timeout: DEFER_IDLE_TIMEOUT_MS },\n ),\n );\n if (queue.idle !== undefined) {\n return;\n }\n }\n\n queue.timer = setTimeout(() => {\n drain(owner, queue);\n }, 0);\n unrefTimer(queue.timer);\n}\n\n/** Builds a bounded group of calls. Reentrant calls wait for the next callback. */\nfunction drain(owner: object, queue: DeferredQueue, deadline?: IdleDeadline): void {\n if (queues.get(owner) !== queue || queue.draining) {\n return;\n }\n\n cancel(queue);\n queue.draining = true;\n const work = queue.work;\n queue.work = [];\n let index = 0;\n\n while (\n index < work.length &&\n (!deadline || (deadline.didTimeout && index === 0) || deadline.timeRemaining() > 0)\n ) {\n queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The library could not build a deferred record.\",\n work[index],\n );\n index++;\n if (queues.get(owner) !== queue) {\n return;\n }\n }\n\n queue.work = [...work.slice(index), ...queue.work];\n queue.draining = false;\n if (queue.work.length > 0) {\n schedule(owner, queue);\n } else {\n queues.delete(owner);\n }\n}\n\n/** Queues a call without reading its payload. A full queue builds its pending calls first. */\nexport function deferWrite(\n owner: object,\n work: () => void,\n diagnostics: Diagnostics,\n limit: number | null,\n): void {\n let queue = queues.get(owner);\n const capacity = limit === null ? DEFER_QUEUE_LIMIT : Math.min(limit, DEFER_QUEUE_LIMIT);\n if (queue && queue.work.length >= capacity && !queue.draining) {\n drain(owner, queue);\n queue = queues.get(owner);\n }\n\n if (queue) {\n if (queue.work.length >= capacity) {\n diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n queue.work.push(work);\n return;\n }\n\n queue = { work: [work], diagnostics, draining: false };\n queues.set(owner, queue);\n schedule(owner, queue);\n}\n\n/** Builds pending calls before a flush, a session change or a delivery identity change. */\nexport function drainDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n drain(owner, queue);\n }\n}\n\n/** Releases calls that a hook queues during shutdown. No records were built for them. */\nexport function cancelDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n cancel(queue);\n queues.delete(owner);\n for (const _work of queue.work) {\n queue.diagnostics.count(\"record.dropped_by_ceiling\");\n }\n queue.work = [];\n }\n}\n","// src/core/logger.ts\n//\n// Namespaced logger facade with scoped log methods. The capture modules' logger can also write\n// one metric record per call.\n\nimport {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n DIAGNOSTICS_NAMESPACE,\n METRIC_KEYS,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport {\n type LogLevel,\n type LogRecord,\n type LogType,\n type MetricType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason, RecordSnapshot } from \"./record\";\nimport { deferWrite } from \"./deferred\";\nimport { currentUrl } from \"../utils/platform\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** The library's own namespaces. Their records get log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [\n CAPTURE_NAMESPACE,\n STORAGE_NAMESPACE,\n DIAGNOSTICS_NAMESPACE,\n];\n\n/** Configuration options for a scoped OneLogger instance. */\nexport interface OneLoggerOptions {\n /** Contextual attributes merged into all records emitted by this logger. */\n scopedContext?: Record<string, unknown>;\n}\n\n/**\n * Turns any thrown value into an Error. A real error is copied with its name, message and stack.\n * @param value Caught error instance or primitive value.\n * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof and from any property read, and a Proxy around\n // an Error passes instanceof, so read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a throwing toString. log.error() runs\n // inside the consumer's catch block, so it must not throw out of it.\n const text = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not convert the error reason to text.\",\n () => String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Returns the error the console prints. The console shows a real Error's cause and own\n * fields, while the record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, otherwise the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads an error reason's data for the error.data attribute. Keeps only own fields whose\n * value is a string, number or boolean.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns An object reason's fields, a primitive reason, or undefined. A string reason\n * returns undefined because error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, such as an AxiosError's config, can hold credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\n}\n\n/**\n * Checks whether a value is an attribute bag rather than an error reason. Works across\n * realms, because an object literal from an iframe has that realm's Object.prototype, whose\n * own prototype is also null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!isObject(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/**\n * Picks the log.type the level methods use for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for one of the library's namespaces, \"log\" for any other.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload, so a Proxy with a throwing trap can't throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the payload can't be read.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type the level methods use. \"system\" only for the library's own namespaces. */\n private readonly levelType: LogType;\n\n /**\n * @param bind Returns the runtime for each write, so a logger created before configure()\n * still writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n protected readonly bind: () => ObservabilityRuntime,\n readonly namespace: string,\n private readonly options: OneLoggerOptions = {},\n ) {\n this.levelType = levelTypeFor(namespace);\n }\n\n /**\n * Creates a child logger with a nested namespace and merged scoped context.\n * @param namespace Sub-namespace appended with dot notation.\n * @param options Additional scoped context attributes.\n * @returns Nested child OneLogger instance.\n */\n child(namespace: string, options: OneLoggerOptions = {}): OneLogger {\n return new OneLogger(this.bind, `${this.namespace}.${namespace}`, {\n scopedContext: {\n ...this.options.scopedContext,\n ...options.scopedContext,\n },\n });\n }\n\n /**\n * Logs a trace-level debug record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n trace = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"TRACE\", this.levelType, message, payload);\n };\n\n /**\n * Logs a debug-level record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n debug = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"DEBUG\", this.levelType, message, payload);\n };\n\n /**\n * Logs an informational record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n info = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", this.levelType, message, payload);\n };\n\n /**\n * Logs a warning record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n warn = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"WARN\", this.levelType, message, payload);\n };\n\n /**\n * Logs an error record with the breadcrumb history. When payload is omitted, a plain\n * object in the error slot is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n error = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"ERROR\", message, error, payload);\n };\n\n /**\n * Logs a fatal error record. When payload is omitted, a plain object in the error slot\n * is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n fatal = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"FATAL\", message, error, payload);\n };\n\n /**\n * Logs a user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\n logAction = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"action\", name, payload);\n };\n\n /**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\n logEvent = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"event\", name, payload);\n };\n\n /**\n * Builds and emits a standard log record, and prints it to the console.\n * @param level Severity level.\n * @param type Record classification.\n * @param body Primary message.\n * @param payload Optional contextual attributes.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, type, (snapshot) => {\n this.writeNow(runtime, level, type, body, payload, false, snapshot);\n });\n }\n\n /** Runs a call right away, or queues it without reading its payload. */\n protected submit(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n work: (snapshot?: RecordSnapshot) => void,\n ): void {\n if (runtime.isDestroyed()) {\n return;\n }\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\n return;\n }\n\n if (\n runtime.config.payloadMode === \"defer\" &&\n runtime.config.enabled &&\n !runtime.config.debugBuffer.enabled &&\n // A deferred diagnostic record is built outside its loop guard, so a hook failure would loop.\n this.namespace !== DIAGNOSTICS_NAMESPACE\n ) {\n if (\n !runtime.builder.isEnabled(level, this.namespace, type) &&\n !this.mirrors(runtime, level)\n ) {\n return;\n }\n\n const journey = runtime.journey.current();\n const snapshot: RecordSnapshot = {\n timeUnixNano: nowUnixNano(),\n trace: runtime.tracing.resolve(),\n journey: journey ? { ...journey } : null,\n context: runtime.context.getAll(),\n url: currentUrl(runtime.diagnostics),\n };\n deferWrite(\n runtime,\n () => {\n work(snapshot);\n },\n runtime.diagnostics,\n runtime.config.buffering.maxPendingRecords,\n );\n return;\n }\n\n work();\n }\n\n /** Builds a standard record once the call's payload is ready to read. */\n protected writeNow(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n body: string,\n payload: Record<string, unknown> | undefined,\n copied: boolean,\n snapshot?: RecordSnapshot,\n ): void {\n // minLevel limits what we send, and the console level limits what we print. minLevel doesn't\n // apply to an action or a metric, and the debug buffer keeps records below it.\n const keepsDropped = runtime.config.enabled && runtime.config.debugBuffer.enabled;\n if (!keepsDropped && !runtime.builder.isEnabled(level, this.namespace, type)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null, undefined, snapshot);\n }\n\n return;\n }\n\n const input = {\n snapshot,\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: copied ? payload : copyPayload(payload, runtime.diagnostics),\n };\n const { record, dropped } = runtime.builder.build(input);\n const hooks = Boolean(runtime.config.redact) || runtime.config.processors.length > 0;\n // Only run the hooks on a sampled-out record if a breadcrumb keeps its message.\n const keepsCrumb = type !== \"metric\" && runtime.config.captureLimits.breadcrumbs > 0;\n const protectedCrumb =\n dropped === \"sampling\" && hooks && keepsCrumb\n ? runtime.builder.build(input, true)\n : undefined;\n const safe = record ?? protectedCrumb?.record ?? null;\n const crumb = safe ? safe.body : dropped === \"sampling\" && !hooks ? body : undefined;\n if (keepsCrumb && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: snapshot ? Number(snapshot.timeUnixNano.slice(0, -6)) : Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n this.print(\n runtime,\n level,\n body,\n payload,\n undefined,\n safe,\n protectedCrumb?.dropped ?? dropped,\n snapshot,\n );\n runtime.emit(record);\n }\n\n /**\n * Builds and emits an error record with breadcrumbs, and prints it to the console.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n private writeError(\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, this.levelType, (snapshot) => {\n this.writeErrorNow(runtime, level, message, error, payload, snapshot);\n });\n }\n\n /** Builds an error record once the deferred queue releases its payload. */\n private writeErrorNow(\n runtime: ObservabilityRuntime,\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload: Record<string, unknown> | undefined,\n snapshot?: RecordSnapshot,\n ): void {\n const ships = runtime.builder.isEnabled(level, this.namespace);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // Every sibling method takes (name, payload?), so callers expect log.error(\"failed\", { id })\n // to work. Treated as an error reason, that object would put \"[object Object]\" in\n // error.message and drop the caller's fields. A Proxy in the error slot can throw on the check.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null, undefined, snapshot);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped, snapshot);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook or processors, the line shows only what they\n * returned. A host can record console arguments, so the console must not show what the hooks\n * remove.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error The error from an error call.\n * @param record Built record, or null if it was never built or redact dropped it.\n * @param dropped Why the builder dropped the record, if it did.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n dropped?: DropReason,\n snapshot?: RecordSnapshot,\n ): void {\n if (!runtime.config.redact && runtime.config.processors.length === 0) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record's attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n // A record dropped by a hook or the shape check prints nothing. Its text never passed redact.\n if (dropped === \"processor\" || dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n if (!runtime.config.enabled || !runtime.console.accepts(level)) {\n return;\n }\n // Use the record builder without the delivery level and sampling checks. Don't process\n // a record again if a hook refused it, and don't send this one or add it as a breadcrumb.\n const clean = runtime.builder.build(\n {\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(payload, runtime.diagnostics),\n ...(error\n ? {\n \"error.type\": error.name,\n \"error.message\": error.message,\n \"error.stack_trace\": error.stack,\n }\n : {}),\n },\n },\n true,\n ).record;\n if (clean) {\n runtime.console.write(this.namespace, level, clean.body, clean.attributes);\n }\n }\n\n /**\n * Checks whether the console prints a level that we don't send.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\n }\n}\n\n/**\n * Logger for the capture modules. It also writes one metric record per call, which the public\n * Logger can't, because an app's metric goes through an instrument and its interval.\n */\nexport class LibraryLogger extends OneLogger {\n /**\n * Logs one metric measurement as its own record.\n * @param name Metric identifier.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes. With metricsEndpoint they're point attributes.\n * @param recordOnly Optional attributes for the record only. They stay off the OTLP point,\n * because a value that changes on each page load would start a new series each time.\n */\n logMetric = (\n name: string,\n value: number,\n unit = DEFAULT_METRIC_UNIT,\n type: MetricType = \"gauge\",\n attributes?: Record<string, unknown>,\n recordOnly?: Record<string, unknown>,\n ): void => {\n // NaN and Infinity become null in JSON, which a backend then reads as a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n const runtime = this.bind();\n this.submit(runtime, \"INFO\", \"metric\", (snapshot) => {\n // Copy the caller's attributes first so the metric fields win. The record-only ones aren't\n // in the key list, so the metrics format leaves them off the point.\n const copied = copyPayload(attributes, runtime.diagnostics);\n const payload = {\n ...copyPayload(recordOnly, runtime.diagnostics),\n ...copied,\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n [METRIC_KEYS.attributeKeys]: Object.keys(copied),\n };\n this.writeNow(runtime, \"INFO\", \"metric\", name, payload, true, snapshot);\n });\n };\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed trace contexts, OpenTelemetry span integration, and W3C\n// traceparent headers. Consecutive records share one trace id, because a new trace id for\n// every record would give each trace only one span.\n\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** The W3C format fixes these hex widths. A span context with any other width is unusable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Matches a digit that isn't zero. A span that hasn't started reports an all-zero id. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Checks whether a span context can carry correlation. Replaces isSpanContextValid from the\n * peer package, which isn't available when the peer isn't installed.\n * @param context The span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\n\n/** W3C trace context fields attached to log records and network headers. */\nexport interface TraceContext {\n /** Hexadecimal 32-character W3C trace identifier. */\n traceId: string;\n /** Hexadecimal 16-character W3C span identifier. */\n spanId: string;\n /** Bitfield byte containing W3C trace flags. */\n traceFlags: number;\n}\n\n/** Why the ambient trace context rotated. */\nexport type RotateReason = \"start\" | \"interaction\" | \"navigation\" | \"explicit\" | \"maxAge\";\n\n/** An ambient trace that ended. Its root span covers it. */\nexport interface EndedTrace {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the root span. */\n spanId: string;\n /** Why the trace started. */\n reason: RotateReason;\n /** Start time in epoch milliseconds. */\n startedAt: number;\n /** End time in epoch milliseconds. */\n endedAt: number;\n}\n\n/** The client span that a traceparent header names. */\nexport interface ClientSpan {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the client span. */\n spanId: string;\n /** Span ID of the trace's root span. */\n parentSpanId: string;\n}\n\n/** One request's headers, and the client span they name. */\nexport interface RequestTrace {\n /** Header map containing traceparent. */\n headers: Record<string, string>;\n /** The request's client span. Undefined when the library records no span for it. */\n span?: ClientSpan;\n}\n\n/** The runtime's span decisions. */\nexport interface SpanHooks {\n /**\n * Checks whether the library records spans.\n * @returns True when there is a traces endpoint.\n */\n enabled(): boolean;\n /**\n * Checks whether sampling keeps a trace's spans.\n * @param traceId Trace ID.\n * @returns True if the library sends the trace's spans.\n */\n keeps(traceId: string): boolean;\n /**\n * Receives an ambient trace that ended.\n * @param ended The trace.\n */\n onEnd(ended: EndedTrace): void;\n}\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n /** Why the trace started. */\n reason: RotateReason;\n /** True once the root span has ended. It ends only once. */\n ended: boolean;\n}\n\n/**\n * Generates a random 32-character hex string in the W3C trace ID format. Use it to start\n * your own trace. The backend drops an id with the wrong width without reporting an error.\n * @returns 32-character hexadecimal trace ID.\n */\nexport function newTraceId(): string {\n return randomHex(TRACE_ID_BYTES);\n}\n\n/**\n * Generates a random 16-character hex string conforming to W3C span ID format.\n * @returns 16-character hexadecimal span ID.\n */\nexport function newSpanId(): string {\n return randomHex(SPAN_ID_BYTES);\n}\n\n/**\n * Creates a new AmbientTrace with the sampled trace flag set. The flag is always set, because\n * sampling runs before the library builds the record.\n * @param reason Why the trace starts.\n * @returns The initialized AmbientTrace.\n */\nfunction mintAmbient(reason: RotateReason): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n reason,\n ended: false,\n };\n}\n\n/**\n * Formats a W3C traceparent value.\n * @param traceId Trace ID.\n * @param spanId The caller's span ID.\n * @param traceFlags Trace flags.\n * @returns The traceparent value.\n */\nfunction traceparent(traceId: string, spanId: string, traceFlags: number): string {\n // Mask the trace flags to a 2-digit hex byte, as the W3C specification requires.\n // trace-flags is a bitfield, not a boolean, and a fixed 00 or 01 would discard upstream flags.\n const flags = (traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n return `${TRACEPARENT_VERSION}-${traceId}-${spanId}-${flags}`;\n}\n\n/**\n * Creates a defensive copy of a TraceContext from an AmbientTrace.\n * @param ambient Source ambient trace object.\n * @returns Defensive copy of TraceContext.\n */\nfunction toTraceContext(ambient: AmbientTrace): TraceContext {\n return {\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n traceFlags: ambient.traceFlags,\n };\n}\n\n/** Manages ambient distributed trace contexts and resolves active OpenTelemetry spans. */\nexport class TraceEngine {\n /**\n * The active ambient trace context. This state lives on the instance, not the module,\n * because two runtimes in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient(\"start\");\n\n /** The optional peer, once loaded. Undefined while it loads or when it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it isn't set, OTel is off.\n * Do not import the peer by name, because the Vite dev server fails if the peer isn't\n * installed.\n * @param spans The runtime's span decisions. Without them, the library records no span.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private maxAgeMs = TRACE_MAX_AGE_MS,\n private load?: OtelLoader,\n private readonly spans?: SpanHooks,\n ) {}\n\n /**\n * Sets the trace age and the OpenTelemetry loader from the app's startup call. A log call\n * before configure() builds the engine before those settings exist.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it isn't set, OTel is off.\n */\n setup(maxAgeMs: number, load: OtelLoader | undefined): void {\n this.maxAgeMs = maxAgeMs;\n this.load = load;\n }\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns A promise that resolves when the attempt settles.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"The library could not load @opentelemetry/api. Records use the trace ids of the library.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.\n * @returns Active TraceContext.\n */\n resolve(): TraceContext {\n return this.activeSpanContext() ?? this.ambientContext();\n }\n\n /**\n * Reads the ambient trace, rotating it first if it is too old.\n * @returns The ambient TraceContext.\n */\n private ambientContext(): TraceContext {\n // Rotate the ambient trace once it is older than maxAgeMs. This is checked on read, not on\n // a timer, because a timer would keep this instance alive for the life of the document.\n if (Date.now() - this.ambient.startedAt > this.maxAgeMs) {\n this.rotate(\"maxAge\");\n }\n return toTraceContext(this.ambient);\n }\n\n /**\n * Reads the host's active span, if the peer module loaded and a span is running.\n * @returns The active span's trace context, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not read the active OpenTelemetry span.\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\n }\n\n /**\n * Rotates the ambient trace context to mark the start of a new logical operation, and ends\n * the old trace's root span.\n * @param reason The event that triggers the rotation.\n * @returns The newly created TraceContext.\n */\n rotate(reason: RotateReason): TraceContext {\n // Set the new trace first, so a record that a hook makes inside onEnd joins the new trace.\n // Otherwise that record would rotate again, and its trace would get no root span.\n const old = this.ambient;\n this.ambient = mintAmbient(reason);\n const next = toTraceContext(this.ambient);\n this.finish(old);\n return next;\n }\n\n /**\n * Ends the ambient trace's root span, once. Later records can still use the trace. The exit\n * flush calls this, because a closing document has no later rotation.\n */\n end(): void {\n this.finish(this.ambient);\n }\n\n /**\n * Ends a trace's root span, once.\n * @param ambient The trace to end.\n */\n private finish(ambient: AmbientTrace): void {\n if (ambient.ended) {\n return;\n }\n\n ambient.ended = true;\n this.spans?.onEnd({\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n reason: ambient.reason,\n startedAt: ambient.startedAt,\n endedAt: Date.now(),\n });\n }\n\n /**\n * Generates W3C traceparent headers with the registered OpenTelemetry propagators. Falls\n * back to the ambient trace when OpenTelemetry provides no traceparent.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n return this.trace(false).headers;\n }\n\n /**\n * Generates the headers for one request from the network capture. With spans on, the\n * traceparent names a new client span of the ambient trace.\n * @returns The headers, and the client span that the library records.\n */\n request(): RequestTrace {\n return this.trace(true);\n }\n\n /**\n * Generates the trace headers.\n * @param client True to name a new client span in the traceparent.\n * @returns The headers, and the client span that the library records.\n */\n private trace(client: boolean): RequestTrace {\n const carrier: Record<string, string> = {};\n const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not add the OpenTelemetry headers.\",\n () => {\n otel.propagation.inject(otel.context.active(), carrier);\n },\n );\n }\n if (carrier[TRACEPARENT_HEADER]) {\n return { headers: carrier };\n }\n\n // The peer keeps its own spans, so the library records no span for one of the peer's traces.\n const fromOtel = this.activeSpanContext();\n const ctx = fromOtel ?? this.ambientContext();\n const spans = fromOtel ? undefined : this.spans;\n\n if (!spans?.enabled()) {\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, ctx.spanId, ctx.traceFlags);\n return { headers: carrier };\n }\n\n // Clear the sampled flag on a trace that sampling drops, so a downstream service drops its\n // spans too. The whole trace stays or goes.\n const kept = spans.keeps(ctx.traceId);\n const flags = kept ? ctx.traceFlags : ctx.traceFlags & ~TRACE_FLAGS_SAMPLED;\n const spanId = client ? newSpanId() : ctx.spanId;\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, spanId, flags);\n\n if (!client || !kept) {\n return { headers: carrier };\n }\n\n return { headers: carrier, span: { traceId: ctx.traceId, spanId, parentSpanId: ctx.spanId } };\n }\n}\n","// src/core/measure.ts\n//\n// Times one operation with named phases. Every phase and the total go into duration histograms.\n// With a span, the operation is that span, with one child span per phase. measure() times a\n// single function call with one.\n\nimport { METRIC_DEFAULT_BOUNDARIES } from \"../constants\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport { type ClientSpan, newSpanId } from \"../utils/tracing\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { SpanData } from \"./spans\";\n\n/** Total duration of each measure, in milliseconds. */\nconst TOTAL_DURATION: InstrumentDef = {\n name: \"ui.measure.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Duration of each phase, in milliseconds. */\nconst PHASE_DURATION: InstrumentDef = {\n name: \"ui.measure.phase.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Where the values of one measure go. */\nexport interface MeasureSinks {\n /** Adds a value to a histogram. */\n metric(def: InstrumentDef, value: number, attributes: MetricAttributes): void;\n /** Records one span. */\n span(span: SpanData): void;\n}\n\n/**\n * Starts the clock for one operation.\n * @param name Operation name. A JavaScript caller can pass any type.\n * @param attributes Copy of the app's attribute set.\n * @param span The operation's span, or undefined when spans are off or the trace was dropped.\n * @param sinks Where the values go.\n * @returns The operation's handle.\n */\nexport function createMeasure(\n name: unknown,\n attributes: MetricAttributes,\n span: ClientSpan | undefined,\n sinks: MeasureSinks,\n): Measure {\n // The record builder needs text.\n const label = String(name);\n const startMs = Date.now();\n const startedAt = performance.now();\n let open: { name: string; at: number } | undefined;\n let ended = false;\n\n // The histograms use the monotonic clock, but a span needs epoch times.\n const epoch = (at: number): number => startMs + at - startedAt;\n\n const closePhase = (now: number, error: boolean): void => {\n if (!open) {\n return;\n }\n\n sinks.metric(PHASE_DURATION, now - open.at, {\n ...attributes,\n \"measure.name\": label,\n \"measure.phase\": open.name,\n });\n if (span) {\n sinks.span({\n name: open.name,\n kind: \"internal\",\n traceId: span.traceId,\n spanId: newSpanId(),\n parentSpanId: span.spanId,\n startMs: epoch(open.at),\n endMs: epoch(now),\n error,\n attributes: { \"measure.name\": label },\n });\n }\n open = undefined;\n };\n\n return {\n phase: (next: unknown) => {\n if (ended) {\n return;\n }\n\n const now = performance.now();\n closePhase(now, false);\n open = { name: String(next), at: now };\n },\n end: (outcome = \"ok\") => {\n if (ended) {\n return;\n }\n\n ended = true;\n const now = performance.now();\n const error = outcome === \"error\";\n closePhase(now, error);\n const fields = { ...attributes, \"measure.outcome\": outcome };\n sinks.metric(TOTAL_DURATION, now - startedAt, { ...fields, \"measure.name\": label });\n if (span) {\n sinks.span({\n ...span,\n name: label,\n kind: \"internal\",\n startMs,\n endMs: epoch(now),\n error,\n attributes: fields,\n });\n }\n },\n };\n}\n\n/**\n * Calls a function and ends the measure when the call returns. If the result has a `then`\n * function, the measure ends when it settles. A throw or a rejection ends it with the outcome\n * \"error\" and goes to the caller.\n * @param handle The measure of the call.\n * @param fn The app's function.\n * @param diagnostics Reports a result whose `then` can't be read.\n * @returns Whatever fn returned, or the result of its then() call.\n */\nexport function measureCall<T>(handle: Measure, fn: () => T, diagnostics: Diagnostics): T {\n // finally sees a throw from fn or from the result's then(), so the error goes to the caller\n // unchanged and the measure still ends.\n let outcome: string | undefined = \"error\";\n try {\n const result = fn();\n // A hostile result can throw from its then getter. The measure then ends now.\n const then = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read what the function of the measure returned. The measure ends now.\",\n (): unknown => (result as { then?: unknown } | null | undefined)?.then,\n );\n\n if (typeof then !== \"function\") {\n outcome = \"ok\";\n return result;\n }\n\n // Hand back the chained result, so a rejection has exactly one owner: the caller.\n const chained = (then as PromiseLike<unknown>[\"then\"]).call(\n result,\n (value) => {\n handle.end();\n return value;\n },\n (error: unknown) => {\n handle.end(\"error\");\n throw error;\n },\n ) as T;\n // The settle ends the measure from here.\n outcome = undefined;\n return chained;\n } finally {\n if (outcome !== undefined) {\n handle.end(outcome);\n }\n }\n}\n","// src/core/meter.ts\n//\n// Sums counter and histogram values and keeps the last gauge value in memory. At every interval\n// it emits one point per instrument and attribute set, so a thousand adds produce one record.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_METRIC_OVERFLOW,\n ATTR_PAGE_URL,\n DEFAULT_METRIC_UNIT,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n} from \"../constants\";\nimport type { MetricsOptions } from \"../models/config\";\nimport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n MetricAttributes,\n} from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One attribute set's sums in the current interval. */\ninterface Series {\n /** The series' attribute set. */\n attributes: MetricAttributes;\n /** Number of values. */\n count: number;\n /** Sum of the values. */\n sum: number;\n /** Smallest value. */\n min: number;\n /** Largest value. */\n max: number;\n /** Last value. A gauge sends it. */\n last: number;\n /** Count per histogram bucket. A counter and a gauge have none. */\n buckets: number[];\n}\n\n/** One instrument's series in the current interval. */\ninterface Instrument {\n /** Definition taken from the interval's first value. */\n def: InstrumentDef;\n /** Series by attribute set key. */\n series: Map<string, Series>;\n}\n\n/** Key of the overflow series. An attribute set's key is JSON text, which starts with \"{\". */\nconst OVERFLOW_KEY = \"overflow\";\n\n/** Keys the record builder sets. It overwrites a call attribute with the same name. */\nconst RECORD_KEYS = new Set<string>([\n ATTR_LOG_TYPE,\n ATTR_LOG_SEQ,\n ATTR_APP_NAMESPACE,\n ATTR_PAGE_URL,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n]);\n\n/**\n * Keeps the string, finite number and boolean attributes, in key order. Two calls with the same\n * set in a different key order then share one series.\n * @param attributes The call's attribute set.\n * @returns The clean attribute set.\n */\nfunction cleanAttributes(attributes: MetricAttributes = {}): MetricAttributes {\n const clean: MetricAttributes = {};\n\n for (const key of Object.keys(attributes).sort()) {\n // The builder replaces the metric fields, so keeping one would give every value its own\n // series with the same output. An app's other metric. keys stay reserved for the library.\n if (key.startsWith(\"metric.\") || RECORD_KEYS.has(key)) {\n continue;\n }\n\n const value: unknown = attributes[key];\n const finite = typeof value === \"number\" && Number.isFinite(value);\n if (typeof value === \"string\" || typeof value === \"boolean\" || finite) {\n clean[key] = value;\n }\n }\n\n return clean;\n}\n\n/**\n * Copies a list of boundaries by index, so a custom iterator on the app's array has no effect.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. null means no limit.\n * @returns A plain array with at most one value more than the limit, or null if the value\n * isn't an array.\n */\nfunction copyBounds(bounds: unknown, limit: number | null): unknown[] | null {\n if (!Array.isArray(bounds)) {\n return null;\n }\n\n // One more than the limit, so isAscending rejects a list that is too long.\n const count = limit === null ? bounds.length : Math.min(bounds.length, limit + 1);\n return Array.from({ length: count }, (_unused, i): unknown => bounds[i]);\n}\n\n/**\n * Checks a list of histogram boundaries.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. null means no limit.\n * @returns True for finite numbers in ascending order, no more of them than the limit.\n */\nfunction isAscending(bounds: unknown, limit: number | null): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n (limit === null || bounds.length <= limit) &&\n bounds.every(\n (bound: unknown, i) =>\n typeof bound === \"number\" &&\n Number.isFinite(bound) &&\n (i === 0 || bound > (bounds[i - 1] as number)),\n )\n );\n}\n\n/**\n * Builds the metric fields for one point. The call's attributes stay out.\n * @param def The instrument's definition.\n * @param series The attribute set's sums.\n * @param start Start of the interval, in Unix nanoseconds.\n * @returns The point's metric fields.\n */\nfunction fieldsOf(def: InstrumentDef, series: Series, start: string): Record<string, unknown> {\n const point: Record<string, unknown> = {\n \"metric.name\": def.name,\n \"metric.unit\": def.unit,\n \"metric.type\": def.kind,\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: Object.keys(series.attributes),\n };\n\n if (def.kind !== \"histogram\") {\n point[\"metric.value\"] = def.kind === \"gauge\" ? series.last : series.sum;\n return point;\n }\n\n return {\n ...point,\n [METRIC_KEYS.count]: series.count,\n [METRIC_KEYS.sum]: series.sum,\n [METRIC_KEYS.min]: series.min,\n [METRIC_KEYS.max]: series.max,\n [METRIC_KEYS.bounds]: def.boundaries,\n [METRIC_KEYS.buckets]: series.buckets,\n };\n}\n\n/** Adds a value to one of the runtime's instruments. */\nexport type RecordMetric = (\n def: InstrumentDef,\n value: number,\n attributes?: MetricAttributes,\n) => void;\n\n/** Called with whatever reading an options object threw. */\nexport type OptionsFault = (error: unknown) => void;\n\n/**\n * Reads an instrument's options. A getter or a Proxy trap on them can throw, and a JavaScript\n * caller can pass null.\n * @param options Options from the app.\n * @param fault Reports options that couldn't be read.\n * @returns The unit and the boundaries. Anything the app didn't set is undefined.\n */\nfunction readOptions(\n options: HistogramOptions,\n fault: OptionsFault,\n): { unit: string | undefined; boundaries: readonly number[] | undefined } {\n try {\n return { unit: options.unit, boundaries: options.boundaries };\n } catch (error) {\n fault(error);\n return { unit: undefined, boundaries: undefined };\n }\n}\n\n/**\n * Builds the definition of an instrument with one value per point.\n * @param name Metric name.\n * @param kind \"counter\" or \"gauge\".\n * @param options Unit for the values.\n * @param fault Reports options that couldn't be read.\n * @returns The definition.\n */\nfunction scalarDef(\n name: string,\n kind: \"counter\" | \"gauge\",\n options: InstrumentOptions,\n fault: OptionsFault,\n): InstrumentDef {\n return {\n name,\n kind,\n unit: readOptions(options, fault).unit ?? DEFAULT_METRIC_UNIT,\n boundaries: [],\n };\n}\n\n/**\n * Creates a counter handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The counter.\n */\nexport function makeCounter(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Counter {\n const def = scalarDef(name, \"counter\", options, fault);\n\n return {\n add: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Creates a gauge handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values.\n * @param record Sets the instrument's value.\n * @param fault Reports options that couldn't be read.\n * @returns The gauge.\n */\nexport function makeGauge(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Gauge {\n const def = scalarDef(name, \"gauge\", options, fault);\n\n return {\n set: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Creates a histogram handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values, and the bucket boundaries.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The histogram.\n */\nexport function makeHistogram(\n name: string,\n options: HistogramOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Histogram {\n const { unit, boundaries } = readOptions(options, fault);\n const def: InstrumentDef = {\n name,\n kind: \"histogram\",\n unit: unit ?? DEFAULT_METRIC_UNIT,\n boundaries: boundaries ?? METRIC_DEFAULT_BOUNDARIES,\n fromApp: boundaries !== undefined,\n };\n\n return {\n record: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/** Sums the counter and histogram values and keeps the gauge values of one interval. */\nexport class Meter {\n /** Instruments with a value in the current interval. */\n private readonly instruments = new Map<string, Instrument>();\n\n /** Timer for the current interval. Runs only while a value is waiting. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Time of the interval's first value, in epoch milliseconds. */\n private startedAt = 0;\n\n /**\n * @param intervalMs Returns the interval length, in milliseconds.\n * @param emit Builds and sends the record for one point from the call attributes and the\n * metric fields.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly intervalMs: () => number,\n private readonly emit: (\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ) => void,\n private readonly diagnostics: Diagnostics,\n private readonly policy: Omit<MetricsOptions, \"intervalMs\"> = {\n maxSeries: 100,\n maxInstruments: 1000,\n maxHistogramBoundaries: 50,\n },\n ) {}\n\n /**\n * Adds a value to the series for its attribute set. Never throws into the app.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // NaN and Infinity become null in JSON, and a negative add breaks a counter's sum.\n if (!Number.isFinite(value) || (def.kind === \"counter\" && value < 0)) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The value of the metric ${def.name} is not valid. The library dropped it.`,\n { \"metric.name\": def.name },\n );\n return;\n }\n\n // A getter or a Proxy trap on the attributes can throw.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n `The library could not read the attributes of the metric ${def.name}.`,\n () => {\n const instrument = this.instrumentOf(def);\n if (instrument) {\n this.add(instrument, value, cleanAttributes(attributes));\n this.arm();\n }\n },\n );\n }\n\n /** Sends one point per series in the interval, then starts a new interval. */\n collect(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n const start = `${String(this.startedAt)}000000`;\n const instruments = [...this.instruments.values()];\n this.instruments.clear();\n\n for (const { def, series } of instruments) {\n for (const one of series.values()) {\n this.emit(def.name, one.attributes, fieldsOf(def, one, start));\n }\n }\n }\n\n /**\n * Finds the interval's instrument. The first value of the interval sets its definition.\n * @param def The call's definition.\n * @returns The instrument, or null when the name has another kind.\n */\n private instrumentOf(def: InstrumentDef): Instrument | null {\n const found = this.instruments.get(def.name);\n\n if (found) {\n if (found.def.kind === def.kind) {\n return found;\n }\n\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The metric ${def.name} is a ${found.def.kind} and a ${def.kind}. The library dropped the value.`,\n { \"metric.name\": def.name },\n );\n return null;\n }\n\n const { maxInstruments } = this.policy;\n if (maxInstruments !== null && this.instruments.size >= maxInstruments) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return null;\n }\n // Copy before the check, so a later change to the app's array can't change the buckets. The\n // limit is for the app's lists. The library's own lists always fit, or a low limit would\n // report every histogram without custom boundaries.\n const limit = def.fromApp === true ? this.policy.maxHistogramBoundaries : null;\n const copy = copyBounds(def.boundaries, limit);\n const valid = isAscending(copy, limit);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`,\n );\n }\n\n const instrument: Instrument = {\n def: { ...def, boundaries: valid ? copy : [...METRIC_DEFAULT_BOUNDARIES] },\n series: new Map(),\n };\n this.instruments.set(def.name, instrument);\n return instrument;\n }\n\n /**\n * Adds a value to an attribute set's series.\n * @param instrument The value's instrument.\n * @param value Value to add.\n * @param attributes Clean attribute set.\n */\n private add(instrument: Instrument, value: number, attributes: MetricAttributes): void {\n let key = JSON.stringify(attributes);\n let series = instrument.series.get(key);\n let set = attributes;\n\n // Cap the series, or a storm of attribute sets grows memory and the payload without limit.\n const { maxSeries } = this.policy;\n if (!series && maxSeries !== null && instrument.series.size >= maxSeries) {\n key = OVERFLOW_KEY;\n series = instrument.series.get(key);\n set = { [ATTR_METRIC_OVERFLOW]: true };\n }\n\n if (!series) {\n // A histogram has one more bucket than it has boundaries. The last has no upper bound.\n const size = instrument.def.kind === \"histogram\" ? instrument.def.boundaries.length + 1 : 0;\n const buckets = new Array<number>(size).fill(0);\n series = { attributes: set, count: 0, sum: 0, min: value, max: value, last: value, buckets };\n instrument.series.set(key, series);\n }\n\n series.count += 1;\n series.sum += value;\n series.min = Math.min(series.min, value);\n series.max = Math.max(series.max, value);\n series.last = value;\n\n if (series.buckets.length > 0) {\n const index = instrument.def.boundaries.findIndex((bound) => value <= bound);\n series.buckets[index === -1 ? series.buckets.length - 1 : index] += 1;\n }\n }\n\n /** Starts the interval's timer on its first value. An idle meter has no timer. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n this.startedAt = Date.now();\n this.timer = setTimeout(() => {\n this.collect();\n }, this.intervalMs());\n unrefTimer(this.timer);\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { LEVEL_ORDER, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConsole } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { hasOwn } from \"./guards\";\nimport { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, sanitize } from \"./sanitize\";\n\n/** Maps each log level to its console method. */\nconst METHOD: Record<LogLevel, \"debug\" | \"info\" | \"warn\" | \"error\"> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warn\",\n ERROR: \"error\",\n FATAL: \"error\",\n};\n\n/** Mirrors log records directly to browser or Node console methods based on severity. */\nexport class ConsoleSink {\n /**\n * @param settings Console level and styles. A null level prints nothing.\n * @param diagnostics Diagnostics reporter.\n * @param limits Size limits for the printed payload. Same as the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\n ) {}\n\n /**\n * Replaces the console level and styles.\n * @param settings Console level and styles. A null level prints nothing.\n */\n update(settings: ResolvedConsole): void {\n this.settings = settings;\n }\n\n /**\n * Checks whether a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.settings.level];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\n return;\n }\n // Guard against a missing console. Some worker realms don't define it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n // Guard against a loop: a host console wrapper can call the logger, which would print again.\n // The console capture also records inside this scope, and its line is already in devtools.\n if (isLibraryConsole()) {\n return;\n }\n\n // Pass the namespace as a %s argument, so a %o or %c in the namespace prints as text.\n // The last %c resets the style, so the message prints in the default style.\n const prefix = `%c[%s]%c[${level}]%c`;\n const { styles } = this.settings;\n const method = METHOD[level];\n\n // A host can replace console methods with ones that throw. The guard keeps that error\n // from breaking the caller's log call.\n this.diagnostics.guard(\n \"handler.threw\",\n `The library could not print to console.${method}.`,\n () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to every logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, this.limits, this.diagnostics));\n }\n\n // The console capture skips calls in this scope, so it doesn't record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\n });\n },\n );\n }\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers that order each context's records. Timestamps can't\n// order records, because a clock can step and two records can share a millisecond. Each\n// context has its own counter, because a shared counter shows gaps and a gap looks like a\n// lost record. The counter never resets, because a reset would repeat numbers in one context.\n\n/** Monotonic sequence counter establishing total record ordering within an execution context. */\nexport class Sequence {\n /** Last emitted sequence counter value. */\n private value = 0;\n\n /**\n * Increments and returns the next monotonic sequence number starting at 1.\n * @returns Next sequence number.\n */\n next(): number {\n return ++this.value;\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// A ring buffer that keeps a bounded, time-ordered trail of recent user and system events.\n// Breadcrumbs are never sent as records of their own. They reach the backend inside the\n// payload of an error record. Nothing in this file throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category of a breadcrumb event. */\nexport type BreadcrumbCategory =\n | \"log\"\n | \"action\"\n | \"event\"\n | \"click\"\n | \"navigation\"\n | \"http\"\n | \"console\"\n | \"frame\"\n | \"profile\"\n | \"custom\";\n\n/** Short summary of one event, kept so an error record can carry it. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Category of the event. */\n category: BreadcrumbCategory;\n /** Human-readable description of the event. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Fixed-size ring buffer that keeps recent breadcrumbs in time order. */\nexport class BreadcrumbBuffer {\n /** The ring's backing array. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * True once the pointer has wrapped past the capacity. The pointer alone can't tell an\n * empty ring from one that wrapped back to index 0.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs the buffer keeps. */\n private capacity: number;\n\n /**\n * @param capacity Maximum number of breadcrumbs. 0 turns the buffer off. Any other value\n * below the minimum size is raised to it.\n */\n constructor(capacity: number) {\n this.capacity = capacity === 0 ? 0 : Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Changes the capacity, keeping the most recent breadcrumbs that fit.\n * @param capacity New capacity. Pass 0 to drop the stored breadcrumbs and turn the buffer off.\n */\n resize(capacity: number): void {\n const recent = this.snapshot().slice(-capacity);\n this.capacity = capacity;\n this.buffer = new Array<Breadcrumb | undefined>(capacity);\n this.pointer = 0;\n this.filled = false;\n if (capacity) {\n for (const crumb of recent) {\n this.push(crumb);\n }\n }\n }\n\n /**\n * Adds a breadcrumb. When the buffer is full, it overwrites the oldest one.\n * @param crumb Breadcrumb to add.\n */\n push(crumb: Breadcrumb): void {\n if (this.capacity === 0) {\n return;\n }\n this.buffer[this.pointer] = crumb;\n this.pointer = (this.pointer + 1) % this.capacity;\n if (this.pointer === 0) {\n this.filled = true;\n }\n }\n\n /**\n * Keeps only the breadcrumbs that pass the test, in their order.\n * @param keep Returns true for a breadcrumb to keep.\n */\n retain(keep: (crumb: Breadcrumb) => boolean): void {\n const kept = this.snapshot().filter(keep);\n this.clear();\n for (const crumb of kept) {\n this.push(crumb);\n }\n }\n\n /** Removes all breadcrumbs, so a new session never carries the previous user's trail. */\n clear(): void {\n this.buffer.fill(undefined);\n this.pointer = 0;\n this.filled = false;\n }\n\n /**\n * Returns all stored breadcrumbs, oldest to newest.\n * @returns The breadcrumbs in time order.\n */\n snapshot(): Breadcrumb[] {\n const ordered = this.filled\n ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)]\n : this.buffer.slice(0, this.pointer);\n return ordered.filter((crumb): crumb is Breadcrumb => crumb !== undefined);\n }\n}\n","// src/core/context.ts\n//\n// Stores the ambient context attributes that the logger merges into every later record.\n// Keep the store per instance, not at module level: all runtimes in a realm share a module Map.\n\n/** Key-value store for ambient context attributes attached to log records. */\nexport class ContextStore {\n /** Backing store mapping attribute keys to raw values. */\n private readonly map = new Map<string, unknown>();\n\n /**\n * Merges attributes into the ambient context. null removes a key, and undefined keeps the\n * current value, as in configure().\n * @param values Attributes to merge.\n */\n merge(values: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(values)) {\n if (value === null) {\n this.map.delete(key);\n } else if (value !== undefined) {\n this.map.set(key, value);\n }\n }\n }\n\n /**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to remove.\n */\n remove(key: string): void {\n this.map.delete(key);\n }\n\n /** Removes all ambient context attributes. */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Returns a copy of all ambient context attributes, so a merge target or a sanitizer\n * can't change the store.\n * @returns Plain object with the stored key-value pairs.\n */\n getAll(): Record<string, unknown> {\n return Object.fromEntries(this.map);\n }\n}\n","// src/core/debug-buffer.ts\n//\n// Keeps the recent records that minLevel or sampling dropped. An error record from this context\n// sends them out first, so they show what happened before the error.\n\nimport { ATTR_DEBUG_BUFFER } from \"../constants\";\nimport type { DebugBufferOptions } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One kept record, with the time the buffer took it. */\ninterface Kept {\n /** Epoch time in milliseconds when the buffer took the record. */\n at: number;\n /** Built record. The privacy hooks have already run on it. */\n record: LogRecord;\n}\n\n/** Bounded list of the records that were dropped by level or by sampling. */\nexport class DebugBuffer {\n /** Kept records, oldest first. Can grow to twice maxRecords between trims. */\n private kept: Kept[] = [];\n\n /**\n * @param policy Returns the current settings. A later configure() can change them.\n */\n constructor(private readonly policy: () => DebugBufferOptions) {}\n\n /**\n * Keeps a record. When the buffer is full, the oldest record goes first.\n * @param record Built record. The privacy hooks have already run on it.\n */\n push(record: LogRecord): void {\n const { enabled, maxRecords } = this.policy();\n if (!enabled) {\n return;\n }\n\n this.kept.push({ at: Date.now(), record });\n // Trim in steps. Trimming on every push would copy the whole list each time.\n if (this.kept.length >= maxRecords * 2) {\n this.kept = this.kept.slice(-maxRecords);\n }\n }\n\n /**\n * Takes the kept records that aren't too old and empties the buffer.\n * @returns The records, oldest first, each with `uiobs.debug_buffer: true`.\n */\n drain(): LogRecord[] {\n const kept = this.live();\n this.kept = [];\n\n return kept.map(({ record }) => ({\n ...record,\n attributes: { ...record.attributes, [ATTR_DEBUG_BUFFER]: true },\n }));\n }\n\n /**\n * Returns the kept records without taking them.\n * @returns The records, oldest first.\n */\n snapshot(): LogRecord[] {\n return this.live().map(({ record }) => record);\n }\n\n /**\n * Returns the kept records that the current settings allow. A disabled buffer empties itself.\n * @returns The records, oldest first.\n */\n private live(): Kept[] {\n const { enabled, maxRecords, maxAgeMs } = this.policy();\n if (!enabled) {\n this.kept = [];\n return [];\n }\n\n const oldest = maxAgeMs === null ? -Infinity : Date.now() - maxAgeMs;\n\n return this.kept.slice(-maxRecords).filter((entry) => entry.at >= oldest);\n }\n\n /** Removes every kept record, so nothing from an old session or identity goes out. */\n clear(): void {\n this.kept = [];\n }\n}\n","// src/core/diagnostics.ts\n//\n// Reports the library's internal errors. Emits are rate limited, but every event is counted.\n\nimport { DIAGNOSTIC_THROTTLE_MS, LIBRARY_LOG_PREFIX } from \"../constants\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\n\n/** Closed set of diagnostic event codes emitted by library subsystems. */\nexport type DiagnosticCode =\n | \"config.locked\"\n | \"security.rotated\"\n | \"security.rotation_failed\"\n | \"security.context_mismatch\"\n | \"record.dropped_during_rotation\"\n | \"bus.rejected_message\"\n | \"bus.journey_denied\"\n | \"config.invalid\"\n | \"config.reconfigured\"\n | \"record.sanitize_failed\"\n | \"record.truncated\"\n | \"record.dropped_by_level\"\n | \"record.dropped_by_sampling\"\n | \"record.dropped_by_ceiling\"\n | \"record.dropped_by_processor\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_full\"\n | \"record.dropped_malformed\"\n | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\n | \"journey.expired\"\n | \"journey.adopted\"\n | \"journey.token_too_large\"\n | \"trace.otel_failed\"\n | \"bus.role_resolved\"\n | \"bus.no_owner\"\n | \"bus.handshake_timeout\"\n | \"bus.untrusted_origin\"\n | \"bus.send_failed\"\n | \"bus.protocol_mismatch\"\n | \"transport.http_error\"\n | \"transport.timeout\"\n | \"transport.batch_split\"\n | \"transport.partial_success\"\n | \"transport.throttled\"\n | \"transport.dropped_permanent\"\n | \"transport.rejected_credentials\"\n | \"transport.serialize_failed\"\n | \"storage.unavailable\"\n | \"storage.degraded\"\n | \"storage.quota_exceeded\"\n | \"storage.evicted\"\n | \"storage.dead_lettered\"\n | \"pipeline.crashed\"\n | \"capture.install_failed\"\n | \"capture.rate_limited\"\n | \"capture.header_failed\"\n | \"capture.trace_header_kept\"\n | \"capture.record_failed\"\n | \"capture.transport_request\"\n | \"openfin.unavailable\"\n | \"platform.api_blocked\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Human-readable description. */\n message: string;\n /** Structured context metadata. */\n detail?: Record<string, unknown>;\n /** Caught error instance or reason. */\n cause?: unknown;\n /** Event timestamp in epoch milliseconds. */\n at: number;\n /** Total count of this code since startup, including rate-limited occurrences. */\n count: number;\n}\n\n/** Consumer callback for receiving rate-limited diagnostic events. */\nexport type DiagnosticHandler = (event: DiagnosticEvent) => void;\n\n/** Reports internal errors. Dispatch is rate limited, but every event is counted. */\nexport class Diagnostics {\n /** Running occurrence counts per diagnostic code. */\n private readonly counters = new Map<DiagnosticCode, number>();\n\n /** Timestamp of the last emitted event per code, in epoch milliseconds. */\n private readonly lastEmitted = new Map<DiagnosticCode, number>();\n\n /**\n * @param handler Optional listener for diagnostic events.\n * @param throttleMs Minimum time in milliseconds between emitted events for one code.\n * @param consoleFallback True to print a fixed warning if the diagnostic handler throws.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private throttleMs = DIAGNOSTIC_THROTTLE_MS,\n private consoleFallback = false,\n ) {}\n\n /**\n * Changes the report interval and the console fallback rule.\n * @param throttleMs Minimum wait between reports of one code, in milliseconds.\n * @param consoleFallback True to print a fixed warning if the handler throws.\n */\n setPolicy(throttleMs: number, consoleFallback: boolean): void {\n this.throttleMs = throttleMs;\n this.consoleFallback = consoleFallback;\n }\n\n /**\n * Replaces or removes the active diagnostic event handler.\n * @param handler New diagnostic event handler.\n */\n setHandler(handler?: DiagnosticHandler): void {\n this.handler = handler;\n }\n\n /**\n * Increments the count for a code without calling the handler.\n * @param code Diagnostic code to increment.\n * @param by Amount to add.\n * @returns New total for the code.\n */\n count(code: DiagnosticCode, by = 1): number {\n const total = (this.counters.get(code) ?? 0) + by;\n this.counters.set(code, total);\n return total;\n }\n\n /**\n * Bumps the counter for the code and, once the throttle window has passed, sends the event\n * to the handler. Never throws.\n * @param code Diagnostic code.\n * @param message Event description.\n * @param detail Optional structured metadata.\n * @param cause Caught error instance or reason.\n * @returns False if the throttle dropped the event.\n */\n report(\n code: DiagnosticCode,\n message: string,\n detail?: Record<string, unknown>,\n cause?: unknown,\n ): boolean {\n const count = this.count(code);\n const now = Date.now();\n const last = this.lastEmitted.get(code) ?? 0;\n if (now - last < this.throttleMs) {\n return false;\n }\n this.lastEmitted.set(code, now);\n\n const event: DiagnosticEvent = {\n code,\n message,\n detail,\n cause,\n at: now,\n count,\n };\n\n const { handler } = this;\n\n if (!handler) {\n return true;\n }\n try {\n // Console capture skips anything the handler logs inside this scope. Without the scope,\n // the line becomes a record, and a failed send of that record raises a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\n } catch (_handlerError) {\n // Bump the counter directly. Calling report() here would recurse when the handler throws.\n this.count(\"handler.threw\");\n if (this.consoleFallback && typeof console !== \"undefined\") {\n // Console capture skips calls made in this scope.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- Fallback sink when diagnostic handler throws.\n console.warn(`${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`);\n });\n }\n }\n\n return true;\n }\n\n /**\n * Runs a synchronous function and reports anything it throws to diagnostics.\n * @param code Diagnostic code to report on throw.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Function to run.\n * @returns The function's return value, or undefined if it threw.\n */\n guard<T>(code: DiagnosticCode, message: string, fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Runs an asynchronous function and reports a rejected promise to diagnostics.\n * @param code Diagnostic code to report on rejection.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Async function to run.\n * @returns Promise that resolves to the return value, or to undefined on rejection.\n */\n async guardAsync<T>(\n code: DiagnosticCode,\n message: string,\n fn: () => Promise<T>,\n ): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Returns a copy of the cumulative diagnostic counts since initialization.\n * @returns Map of diagnostic codes to occurrence counts.\n */\n snapshot(): Record<string, number> {\n return Object.fromEntries(this.counters);\n }\n}\n","// src/core/drops.ts\n//\n// Collects lost records into onDrop summaries and sends one summary per reason after the\n// current task. A storm of losses then makes one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value once, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and hands the onDrop hook one summary per reason. */\nexport class DropReporter {\n /** Summaries waiting for the end of the task, one per reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask is waiting to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss the hook itself causes isn't reported again. */\n private reporting = false;\n\n /** Lost records since the start, per reason. getHealth() reports them. */\n private readonly lost: Partial<Record<LossReason, number>> = {};\n\n /**\n * @param config Active configuration. `onDrop` is read from it on every call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Counts lost records, and adds them to the summary for their reason. The summary needs an\n * onDrop hook.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n * @param count Number of lost records when the caller can't name them, for example after an\n * OTLP partial rejection. Defaults to the length of `records`.\n */\n add(\n reason: LossReason,\n records: readonly LogRecord[],\n batchIds: readonly string[] = [],\n count = records.length,\n ): void {\n // Count first, so getHealth() shows a loss also without an onDrop hook.\n if (count > 0) {\n this.lost[reason] = (this.lost[reason] ?? 0) + count;\n }\n\n // A hook that logs can fill a buffer again, and reporting that loss would start a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing, and a corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += count;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt: null, or missing its attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /**\n * Returns the lost record counts since the start.\n * @returns A copy of the count for each reason. A reason with no loss has no key.\n */\n counts(): Partial<Record<LossReason, number>> {\n return { ...this.lost };\n }\n\n /** Hands every waiting summary to the hook. A hook that throws doesn't stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip any request or console line the hook makes. A captured line\n // would become a record, and that record could evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// Holds records while the runtime can't deliver them. A full buffer keeps its first records,\n// because the first error of a failed startup is usually the cause, and drops the oldest record\n// after them. An action is an audit fact, so actions have their own lists with their own cap,\n// and a storm of other records can't push one out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, HOLD_BUFFER_HEAD_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One held record. The arrival number puts the lists back into one order. */\ninterface Held {\n /** The record. */\n record: LogRecord;\n /** Counts up with every push. */\n arrival: number;\n}\n\n/** The held records of one kind, oldest first in each list. */\ninterface Kind {\n /** The first HOLD_BUFFER_HEAD_RECORDS records. A full buffer never drops one of them. */\n head: Held[];\n /** Every later record. A full buffer drops the oldest of them. */\n tail: Held[];\n}\n\n/** Holds records and returns them in arrival order. Each kind keeps its head when it is full. */\nexport class HoldBuffer {\n /** Held actions. */\n private actions: Kind = { head: [], tail: [] };\n\n /** Held records of every other kind. */\n private others: Kind = { head: [], tail: [] };\n\n /** Arrival number of the next record. */\n private arrivals = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.inOrder();\n }\n\n /** Number of held records. */\n get length(): number {\n const { actions, others } = this;\n return actions.head.length + actions.tail.length + others.head.length + others.tail.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind after the head.\n * @param record Record to hold.\n * @param maxRecords Cap on records that aren't actions. The caller reads it from the config\n * on each push, because a record can arrive before the app's configure() sets the cap.\n */\n push(record: LogRecord, maxRecords: number): void {\n const action = isActionRecord(record);\n const kind = action ? this.actions : this.others;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : maxRecords;\n const held = { record, arrival: this.arrivals };\n this.arrivals += 1;\n\n if (kind.head.length < HOLD_BUFFER_HEAD_RECORDS) {\n kind.head.push(held);\n return;\n }\n\n kind.tail.push(held);\n\n if (kind.head.length + kind.tail.length > cap) {\n // The tail holds at least the record just pushed, so it always has a front to drop. It is\n // shift() and not splice(0, 1), because splice moves the whole tail on every drop of a storm.\n const dropped = kind.tail[0];\n kind.tail.shift();\n this.onDrop(dropped.record);\n }\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.inOrder();\n this.actions = { head: [], tail: [] };\n this.others = { head: [], tail: [] };\n this.arrivals = 0;\n return records;\n }\n\n /**\n * Builds one list from the four. Each list is already sorted, so the sort only merges runs.\n * @returns The held records in arrival order.\n */\n private inOrder(): LogRecord[] {\n const { actions, others } = this;\n return [...actions.head, ...actions.tail, ...others.head, ...others.tail]\n .sort((first, second) => first.arrival - second.arrival)\n .map((held) => held.record);\n }\n}\n","// src/core/record.ts\n//\n// Builds structured log records from ambient context, journey data, trace context and\n// resource attributes. Never throws to the caller.\n// The builder caches the resource block, so call invalidateResource after its inputs change.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_ATTRIBUTES_BYTES,\n ATTR_ATTRIBUTES_DROPPED,\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_SANITIZE_FAILED,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_METRIC,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n METRIC_NAMESPACE,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_CONTEXT_ID,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_HOST_PLATFORM,\n RESOURCE_OPENFIN_NAME,\n RESOURCE_OPENFIN_UUID,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n RESOURCE_SESSION_ID,\n RESOURCE_TAB_ID,\n RESOURCE_TELEMETRY_SDK_LANGUAGE,\n RESOURCE_TELEMETRY_SDK_NAME,\n RESOURCE_TELEMETRY_SDK_VERSION,\n SEVERITY_NUMBER,\n SPAN_KEYS,\n TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n TRACE_NAMESPACE,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport {\n isLogLevel,\n isLogRecord,\n type LogLevel,\n type LogRecord,\n type LogType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { type SanitizeLimits, sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceContext, TraceEngine } from \"../utils/tracing\";\nimport { REFUSE_RECORDS } from \"./config\";\nimport type { ContextStore } from \"./context\";\nimport type { DebugBuffer } from \"./debug-buffer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { Journey, JourneyEngine } from \"./journey\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { levelFor, shouldSample, shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields, which an oversized error record keeps. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps as redact left them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Ambient context store. */\n context: ContextStore;\n /** Active journey engine. */\n journey: JourneyEngine;\n /** Distributed tracing engine. */\n tracing: TraceEngine;\n /** Monotonic sequence counter. */\n sequence: Sequence;\n /** Context, session and tab identity. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n /** Slot for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Keeps the records that minLevel or sampling drops, for the next error. */\n debug?: DebugBuffer;\n}\n\n/** Per-record size limits. The builder applies them after sanitize and after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/**\n * Reason a record was not built. \"malformed\" means a processor or the redact hook broke the\n * record shape or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"processor\" | \"redact\" | \"malformed\";\n\n/** Consumer hook that changes or drops a record. */\ntype RecordHook = (record: LogRecord) => LogRecord | null;\n\n/** Stage of a consumer hook. */\ntype HookStage = \"processor\" | \"redact\";\n\n/** Message subject, drop code and refusal text for each hook stage. */\nconst HOOK_STAGES = {\n processor: {\n label: \"A processor\",\n code: \"record.dropped_by_processor\",\n refused:\n \"processors is not a list of functions. The library drops each record until processors is a list of functions or [].\",\n },\n redact: {\n label: \"The redact hook\",\n code: \"record.dropped_by_redact\",\n refused:\n \"redact is not a function. The library drops each record until redact is a function or null.\",\n },\n} as const;\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\n record: LogRecord | null;\n /** Reason for the drop. Absent when a record was built. */\n dropped?: DropReason;\n}\n\n/** Metadata captured before a deferred logger call reads its payload. */\nexport interface RecordSnapshot {\n timeUnixNano: string;\n trace: TraceContext;\n journey: Journey | null;\n context: Record<string, unknown>;\n url: string;\n}\n\n/** Input parameters for constructing a single log record. */\nexport interface BuildInput {\n /** Severity level of the log entry. */\n level: LogLevel;\n /** Telemetry type classification. */\n type: LogType;\n /** Primary log message body. */\n body: string;\n /** Originating application namespace. */\n namespace: string;\n /** Pre-merged scoped context from logger instance. */\n scoped?: Record<string, unknown>;\n /** Call-site payload attributes. */\n payload?: Record<string, unknown>;\n /**\n * Fields the library builds with a fixed size bound, for example a point's buckets.\n * The record limits don't trim them, and they override a payload key of the same name.\n */\n fixed?: Record<string, unknown>;\n /** True for a counter or histogram point. Sampling keeps it. */\n aggregated?: boolean;\n /** A span's trace IDs. Without them the builder reads the active trace. */\n trace?: TraceContext;\n /** The call's metadata, captured before the deferred build. */\n snapshot?: RecordSnapshot;\n}\n\n/** Checks whether a forwarded value has the shape the library writes for one field. */\ntype FieldCheck = (value: unknown) => boolean;\n\n/** Fields the library writes together on one kind of record, each with its check. */\ntype FieldGroup = Readonly<Record<string, FieldCheck>>;\n\nconst isFiniteNumber: FieldCheck = (value) => typeof value === \"number\" && Number.isFinite(value);\nconst isNumberList: FieldCheck = (value) => Array.isArray(value) && value.every(isFiniteNumber);\n// An int64 time travels as a digit string because a JavaScript number can't hold it.\nconst isNanos: FieldCheck = (value) => typeof value === \"string\" && /^\\d{1,20}$/.test(value);\nconst isTraceId: FieldCheck = (value) => typeof value === \"string\" && /^[0-9a-f]{32}$/.test(value);\nconst isSpanId: FieldCheck = (value) => typeof value === \"string\" && /^[0-9a-f]{16}$/.test(value);\n// A root span's parent id is empty.\nconst isParentId: FieldCheck = (value) => value === \"\" || isSpanId(value);\nconst isCounter: FieldCheck = (value) => value === \"counter\";\nconst isHistogram: FieldCheck = (value) => value === \"histogram\";\nconst isSpanKind: FieldCheck = (value) => value === \"client\" || value === \"internal\";\nconst isSpanStatus: FieldCheck = (value) => value === \"error\" || value === \"unset\";\n\n// metric.name, metric.unit and metric.attribute_keys are app text, so they aren't in a group\n// and the sender's redact has the last word on them.\nconst COUNTER_FIELDS: FieldGroup = {\n \"metric.type\": isCounter,\n \"metric.value\": isFiniteNumber,\n [METRIC_KEYS.start]: isNanos,\n};\n\nconst HISTOGRAM_FIELDS: FieldGroup = {\n \"metric.type\": isHistogram,\n [METRIC_KEYS.start]: isNanos,\n [METRIC_KEYS.count]: isFiniteNumber,\n [METRIC_KEYS.sum]: isFiniteNumber,\n [METRIC_KEYS.min]: isFiniteNumber,\n [METRIC_KEYS.max]: isFiniteNumber,\n [METRIC_KEYS.bounds]: isNumberList,\n [METRIC_KEYS.buckets]: isNumberList,\n};\n\nconst SPAN_FIELDS: FieldGroup = {\n [SPAN_KEYS.kind]: isSpanKind,\n [SPAN_KEYS.parentId]: isParentId,\n [SPAN_KEYS.start]: isNanos,\n [SPAN_KEYS.end]: isNanos,\n [SPAN_KEYS.status]: isSpanStatus,\n};\n\n// A span only has a link when both ids are there, so a lone id is the app's own attribute.\nconst LINK_FIELDS: FieldGroup = {\n [SPAN_KEYS.linkTraceId]: isTraceId,\n [SPAN_KEYS.linkSpanId]: isSpanId,\n};\n\n/**\n * Picks the field groups the library wrote on a forwarded record. The builder sets log.type and\n * app.namespace after it merges the app's attributes, so an attribute can't fake them, but an app\n * logger named uiobs.metrics can. A capture's single metric record writes its fields as payload,\n * so it gets none, as on the local path.\n * @param attributes A forwarded record's attributes, before the sender's hooks.\n * @returns The groups to check.\n */\nfunction groupsOf(attributes: Record<string, unknown>): FieldGroup[] {\n const type = attributes[ATTR_LOG_TYPE];\n const namespace = attributes[ATTR_APP_NAMESPACE];\n\n if (type === LOG_TYPE_SPAN && namespace === TRACE_NAMESPACE) {\n return [SPAN_FIELDS, LINK_FIELDS];\n }\n\n if (type !== LOG_TYPE_METRIC || namespace !== METRIC_NAMESPACE) {\n return [];\n }\n\n if (attributes[\"metric.type\"] === \"histogram\") {\n return [HISTOGRAM_FIELDS];\n }\n\n return [COUNTER_FIELDS];\n}\n\n/**\n * Reads the encoding fields of a metric point or a span from another context, so the sender's\n * redact can't break the point and the limits can't trim its buckets. A group comes back whole\n * or not at all, and only when each value has the library's shape. Otherwise a caller attribute\n * named like a library field would undo the sender's redact.\n * @param attributes A forwarded record's attributes, before the sender's hooks.\n * @returns The fields to put back after the hooks.\n */\nfunction fixedOf(attributes: Record<string, unknown>): Record<string, unknown> {\n const fixed: Record<string, unknown> = {};\n\n for (const group of groupsOf(attributes)) {\n const keys = Object.keys(group);\n if (keys.every((key) => group[key](attributes[key]))) {\n for (const key of keys) {\n fixed[key] = attributes[key];\n }\n }\n }\n\n return fixed;\n}\n\n/**\n * Casts a sanitized plain object value to an attribute record.\n * @param value Sanitized object value.\n * @returns Attribute record.\n */\nfunction asAttributes(value: unknown): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\n/** Builds validated and sanitized LogRecord instances from logger inputs. */\nexport class RecordBuilder {\n /** Cached resource attributes block. */\n private resourceCache: Record<string, unknown> | null = null;\n\n /**\n * @param deps Injected builder dependencies.\n */\n constructor(private readonly deps: RecordBuilderDeps) {}\n\n /** Clears the cached resource attributes, so the next build computes them again. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Checks whether logging is on and the level is at or above the namespace's minimum level.\n * The minimum level doesn't apply to an action or a metric.\n * @param level Target log severity level.\n * @param namespace Logger namespace. `minLevels` can set its level.\n * @param type Record type. Without it, the minimum level applies.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, namespace: string, type?: LogType): boolean {\n return this.deps.config.enabled && this.passesLevel(level, namespace, type);\n }\n\n /**\n * Checks the level against the namespace's minimum level, whatever `enabled` says.\n * @param level Target log severity level.\n * @param namespace Logger namespace.\n * @param type Record type. An action, a metric or a span passes.\n * @returns True if the level is high enough.\n */\n private passesLevel(level: LogLevel, namespace: string, type?: LogType): boolean {\n const { config } = this.deps;\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower the level during an incident.\n const minLevel =\n this.deps.remote.sampling?.minLevelFor(namespace) ?? levelFor(namespace, config);\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];\n }\n\n /**\n * Keeps a record that minLevel or sampling dropped, when the debug buffer is on. The privacy\n * hooks run now, and an error record from this context sends the kept record later.\n * @param input The dropped record's input.\n */\n private keepForDebug(input: BuildInput): void {\n const { config, debug } = this.deps;\n if (!debug || !config.enabled || !config.debugBuffer.enabled) {\n return;\n }\n\n const { record } = this.build(input, true);\n if (record) {\n debug.push(record);\n }\n }\n\n /**\n * Builds a structured LogRecord from the input, sanitizing attributes and applying size limits.\n * @param input Logger call input parameters.\n * @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.\n * @returns The record, or null with the reason for the drop.\n */\n build(input: BuildInput, forConsole = false): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!forConsole && !this.isEnabled(input.level, input.namespace, input.type)) {\n diagnostics.count(\"record.dropped_by_level\");\n this.keepForDebug(input);\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = input.trace ?? input.snapshot?.trace ?? tracing.resolve();\n const activeJourney = input.snapshot ? input.snapshot.journey : journey.current();\n\n // Sample delivery records before the attribute walk. A record for the console or a\n // breadcrumb skips this check: the privacy hooks still process it, but it is never sent.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n aggregated: input.aggregated,\n },\n config,\n remote.sampling?.current() ?? null,\n );\n if (!forConsole && !sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n this.keepForDebug(input);\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // The query and fragment can contain tokens and user input. The path is what groups records.\n const url = input.snapshot?.url ?? currentUrl(diagnostics);\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(url, config.capture.fullUrls, config.capture.urlTransform, diagnostics)\n : \"\";\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(\n input.snapshot?.context ?? this.deps.context.getAll(),\n limits,\n diagnostics,\n );\n const fromProvider = sanitizeWithSize(this.provided(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromProvider.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence: the provider overrides the context, scope overrides\n // the provider, and payload overrides scope.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromProvider.value),\n ...asAttributes(fromScope.value),\n ...asAttributes(fromPayload.value),\n };\n } catch (error) {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"The library could not sanitize the attributes.\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // A trimmed bucket list would make the serializer drop the point.\n Object.assign(attributes, input.fixed);\n\n // Set reserved attributes after the payload merge. If they went first, a payload key\n // named journey.id would replace the ID that correlates the records.\n attributes[ATTR_LOG_TYPE] = input.type;\n attributes[ATTR_LOG_SEQ] = seq;\n attributes[ATTR_APP_NAMESPACE] = input.namespace;\n attributes[ATTR_PAGE_URL] = pageUrl;\n if (activeJourney) {\n attributes[ATTR_JOURNEY_ID] = activeJourney.id;\n attributes[ATTR_JOURNEY_NAME] = activeJourney.name;\n if (activeJourney.parentId !== undefined) {\n attributes[ATTR_JOURNEY_PARENT_ID] = activeJourney.parentId;\n }\n }\n\n const body = truncate(input.body, limits.maxBodyChars);\n if (body !== input.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n let record: LogRecord = {\n timeUnixNano: input.snapshot?.timeUnixNano ?? nowUnixNano(),\n traceId: traceCtx.traceId,\n spanId: traceCtx.spanId,\n traceFlags: traceCtx.traceFlags,\n severityNumber: SEVERITY_NUMBER[input.level],\n severityText: input.level,\n body,\n attributes,\n resource: this.resource(),\n };\n\n const stages = this.hookStages();\n if (stages.length > 0) {\n const outcome = this.applyHooks(record, stages, input.fixed);\n if (typeof outcome === \"string\") {\n return { record: null, dropped: outcome };\n }\n\n ({ record, bytes } = outcome);\n }\n\n const index = {\n [ATTR_LOG_TYPE]: input.type,\n [ATTR_LOG_SEQ]: seq,\n [ATTR_APP_NAMESPACE]: input.namespace,\n };\n return { record: this.fit(record, bytes, index, input.fixed) };\n }\n\n /**\n * Runs the redact hook on a record from another context. A child context without redact\n * forwards raw records, so the sender is the last privacy gate.\n * @param record Forwarded record.\n * @returns The record to deliver, or null when the hook drops it.\n */\n redactForwarded(record: LogRecord): LogRecord | null {\n const { redact } = this.deps.config;\n if (!redact) {\n return record;\n }\n\n const stages: [RecordHook, HookStage][] = [[redact, \"redact\"]];\n const outcome = this.applyHooks(record, stages, fixedOf(record.attributes));\n return typeof outcome === \"string\" ? null : outcome.record;\n }\n\n /**\n * Runs the hooks on a record that a log call built before the app's first configure(), and\n * gives it the configured resource. That record never met the app's hooks, so the processors\n * run as well as redact. The resource goes on first, so redact sees the record that leaves.\n * @param record Held record.\n * @returns The record to deliver, or null when a hook drops it.\n */\n rehook(record: LogRecord): LogRecord | null {\n const { config, diagnostics, limits, remote, debug } = this.deps;\n const { attributes } = record;\n const namespace = String(attributes[ATTR_APP_NAMESPACE]);\n // The app's levels and sampling decide now, as they would have at the call.\n const leveled = this.passesLevel(\n record.severityText,\n namespace,\n attributes[ATTR_LOG_TYPE] as LogType,\n );\n const sampled = leveled && shouldSample(record, config, remote.sampling?.current() ?? null);\n\n // The stored page.url already lost its query to the default rule, so it can't come back.\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(\n String(attributes[ATTR_PAGE_URL]),\n config.capture.fullUrls,\n config.capture.urlTransform,\n diagnostics,\n )\n : \"\";\n const body = truncate(record.body, limits.maxBodyChars);\n if (body !== record.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n const fixed = fixedOf(attributes);\n const stamped = {\n ...record,\n body,\n attributes: { ...attributes, [ATTR_PAGE_URL]: pageUrl },\n resource: this.resource(),\n };\n const outcome = this.applyHooks(stamped, this.hookStages(), fixed);\n const hooked =\n typeof outcome === \"string\"\n ? null\n : this.fit(outcome.record, outcome.bytes, attributes, fixed);\n\n // A refused record goes where build() sends one: a count, and the debug buffer if it's on.\n if (!sampled) {\n diagnostics.count(leveled ? \"record.dropped_by_sampling\" : \"record.dropped_by_level\");\n if (hooked && debug && config.enabled && config.debugBuffer.enabled) {\n debug.push(hooked);\n }\n return null;\n }\n\n return hooked;\n }\n\n /**\n * Drops the caller attributes of a record over maxRecordBytes, but keeps the index keys: a\n * search can't find a record without journey.id and trace_id. Keeps the error fields, then\n * the breadcrumbs if they fit, because they say why the record exists.\n * @param record Record after the hooks.\n * @param bytes Size of its attributes.\n * @param index The type, the sequence and the namespace the library set on the record.\n * @param fixed Fields the library builds. A point without its metric fields is lost.\n * @returns The record, cut down when it's over the limit.\n */\n private fit(\n record: LogRecord,\n bytes: number,\n index: Record<string, unknown>,\n fixed: Record<string, unknown> | undefined,\n ): LogRecord {\n const { diagnostics, limits } = this.deps;\n if (bytes <= limits.maxRecordBytes) {\n return record;\n }\n\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\n { bytes, body: record.body },\n );\n\n const kept: Record<string, unknown> = {\n [ATTR_LOG_TYPE]: index[ATTR_LOG_TYPE],\n [ATTR_LOG_SEQ]: index[ATTR_LOG_SEQ],\n [ATTR_APP_NAMESPACE]: index[ATTR_APP_NAMESPACE],\n [ATTR_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact, because the hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large, so drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\n\n Object.assign(kept, fixed);\n record.attributes = kept;\n return record;\n }\n\n /**\n * Lists the app's hooks in the order they see a record.\n * @returns The processors, then redact, which is the last privacy gate.\n */\n private hookStages(): [RecordHook, HookStage][] {\n const { processors, redact } = this.deps.config;\n const stages = processors.map((hook): [RecordHook, HookStage] => [hook, \"processor\"]);\n if (redact) {\n stages.push([redact, \"redact\"]);\n }\n\n return stages;\n }\n\n /**\n * Runs the hooks in order, then sanitizes and measures the attributes again.\n * @param record Built record.\n * @param stages Hooks and their stages.\n * @param fixed Fields the library builds. The hooks can't change them.\n * @returns The record and the size of its attributes, or the reason for the drop.\n */\n private applyHooks(\n record: LogRecord,\n stages: readonly [RecordHook, HookStage][],\n fixed: Record<string, unknown> | undefined,\n ): { record: LogRecord; bytes: number } | DropReason {\n let current = record;\n\n for (const [hook, stage] of stages) {\n const outcome = this.runHook(hook, stage, current);\n if (typeof outcome === \"string\") {\n return outcome;\n }\n current = outcome;\n }\n\n // A hook can change the attributes in place or replace them. A cycle, a hostile getter or\n // a BigInt from a hook would throw at serialization, and the transport would lose the batch.\n const { diagnostics, limits } = this.deps;\n const remeasured = sanitizeWithSize(current.attributes, limits, diagnostics);\n const attributes = asAttributes(remeasured.value);\n // The limits must not trim the fields the library builds.\n Object.assign(attributes, fixed);\n\n return { record: { ...current, attributes }, bytes: remeasured.bytes };\n }\n\n /**\n * Runs one consumer hook on a record. A processor and the redact hook have the same contract.\n * @param hook Processor or redact hook.\n * @param stage Stage of the hook.\n * @param record Record before the hook.\n * @returns The record after the hook, or the reason for the drop.\n */\n private runHook(hook: RecordHook, stage: HookStage, record: LogRecord): LogRecord | DropReason {\n const { diagnostics } = this.deps;\n const { label, code, refused } = HOOK_STAGES[stage];\n\n // A plain JavaScript hook can edit the record in place and return nothing.\n let changed: unknown;\n try {\n changed = hook(record);\n } catch (error) {\n // Drop the record. A record the hook didn't clean must not leave the page.\n diagnostics.report(\n code,\n `${label} threw an error. The library dropped the record.`,\n undefined,\n error,\n );\n return stage;\n }\n\n if (changed === null) {\n // The stand-in for a hook value that isn't valid drops every record, and says why.\n if (hook === REFUSE_RECORDS) {\n diagnostics.report(code, refused);\n } else {\n diagnostics.count(code);\n }\n return stage;\n }\n\n const candidate: unknown = changed ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place, so we have no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} changed the record to a shape that is not a record. The library dropped it.`,\n );\n return \"malformed\";\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record didn't pass the hook.\n diagnostics.report(\n code,\n `${label} returned a value that is not a record. The library dropped the record.`,\n );\n return stage;\n }\n\n if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number, so the serializer can't map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} set a severityText that is not a log level. The library dropped the record.`,\n );\n return \"malformed\";\n }\n\n // The hook can change severityText, so keep the number in step with the text.\n return { ...candidate, severityNumber: SEVERITY_NUMBER[candidate.severityText] };\n }\n\n /**\n * Calls the config's contextProvider. A provider that throws or returns something that isn't\n * an object adds nothing, and the record is still built. undefined means no attributes.\n * @returns The attributes from the provider, or an empty object.\n */\n private provided(): unknown {\n const provider = this.deps.config.contextProvider;\n if (!provider) {\n return {};\n }\n\n const { diagnostics } = this.deps;\n const value = diagnostics.guard(\n \"handler.threw\",\n \"The contextProvider threw an error. The record has no attributes from it.\",\n () => {\n const given: unknown = provider();\n if (given === undefined) {\n return {};\n }\n\n // A promise is an object, but its fields aren't attributes.\n return isObject(given) && typeof given.then !== \"function\" ? given : null;\n },\n );\n\n if (value === null) {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must return an object of attributes. The library ignores the value.\",\n );\n }\n\n return value ?? {};\n }\n\n /**\n * Computes or returns cached resource metadata for this runtime context.\n * @returns Resource attributes record.\n */\n private resource(): Record<string, unknown> {\n if (this.resourceCache) {\n return this.resourceCache;\n }\n const { config, identity, platform } = this.deps;\n\n this.resourceCache = {\n [RESOURCE_SERVICE_NAME]: config.serviceName,\n [RESOURCE_SERVICE_VERSION]: config.serviceVersion,\n [RESOURCE_DEPLOYMENT_ENVIRONMENT]: config.environment,\n [RESOURCE_TELEMETRY_SDK_NAME]: TELEMETRY_SDK_NAME,\n [RESOURCE_TELEMETRY_SDK_VERSION]: TELEMETRY_SDK_VERSION,\n [RESOURCE_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE,\n [RESOURCE_HOST_PLATFORM]: platform.platform,\n [RESOURCE_SESSION_ID]: identity.sessionId,\n [RESOURCE_TAB_ID]: identity.tabId,\n [RESOURCE_CONTEXT_ID]: identity.contextId,\n ...(config.metadata.userAgent ? { [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent } : {}),\n // Omits undefined OpenFin properties from resource attributes.\n ...(!config.metadata.openfin || platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(!config.metadata.openfin || platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/spans.ts\n//\n// Builds the span data for a root span and the span fields for a span record. The runtime\n// builds every span as a record of type \"span\", and the traces serializer reads the span fields.\n\nimport { SPAN_KEYS } from \"../constants\";\nimport type { EndedTrace, RotateReason } from \"../utils/tracing\";\n\n/** Microseconds in one millisecond. */\nconst US_PER_MS = 1000;\n\n/** Root span name for each reason a trace can start. */\nconst ROOT_NAMES: Record<RotateReason, string> = {\n start: \"ui.start\",\n interaction: \"ui.interaction\",\n navigation: \"ui.navigation\",\n explicit: \"ui.trace\",\n maxAge: \"ui.trace\",\n};\n\n/** One span recorded by the runtime. */\nexport interface SpanData {\n /** Span name. */\n name: string;\n /** \"internal\" for a root span, \"client\" for a request. */\n kind: \"internal\" | \"client\";\n /** Trace ID. */\n traceId: string;\n /** Span ID. */\n spanId: string;\n /** The parent's span ID, or \"\" for a root span. */\n parentSpanId: string;\n /** Start time in epoch milliseconds. */\n startMs: number;\n /** End time in epoch milliseconds. */\n endMs: number;\n /** True for a failed operation. */\n error: boolean;\n /** The span's attributes. */\n attributes: Record<string, unknown>;\n /** Server span linked through a response traceparent entry. */\n link?: { traceId: string; spanId: string };\n}\n\n/**\n * Converts epoch milliseconds to nanoseconds as a decimal string, keeping microseconds.\n * @param ms Epoch time in milliseconds. May have a fraction.\n * @returns Epoch time in nanoseconds.\n */\nfunction unixNano(ms: number): string {\n return `${String(Math.round(ms * US_PER_MS))}000`;\n}\n\n/**\n * Builds the root span for an ambient trace that has ended.\n * @param ended The trace.\n * @returns The span data.\n */\nexport function rootSpan(ended: EndedTrace): SpanData {\n return {\n name: ROOT_NAMES[ended.reason],\n kind: \"internal\",\n traceId: ended.traceId,\n spanId: ended.spanId,\n parentSpanId: \"\",\n startMs: ended.startedAt,\n endMs: ended.endedAt,\n error: false,\n attributes: {},\n };\n}\n\n/**\n * Builds the span fields for a span record. The record limits don't trim them.\n * @param span The span data.\n * @returns The fields.\n */\nexport function spanFields(span: SpanData): Record<string, unknown> {\n return {\n [SPAN_KEYS.kind]: span.kind,\n [SPAN_KEYS.parentId]: span.parentSpanId,\n [SPAN_KEYS.start]: unixNano(span.startMs),\n [SPAN_KEYS.end]: unixNano(span.endMs),\n [SPAN_KEYS.status]: span.error ? \"error\" : \"unset\",\n ...(span.link\n ? {\n [SPAN_KEYS.linkTraceId]: span.link.traceId,\n [SPAN_KEYS.linkSpanId]: span.link.spanId,\n }\n : {}),\n };\n}\n","// src/core/runtime.ts\n//\n// Coordinates the subsystems. Manages their lifecycles, the configuration and record routing.\n\nimport type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n ATTR_BREADCRUMBS,\n ATTR_DEBUG_BUFFER,\n ATTR_PAGE_URL,\n BUS_PROTOCOL,\n CAPTURE_NAMESPACE,\n LIBRARY_LOG_PREFIX,\n REMOTE_CAPTURE_FLAGS,\n DIAGNOSTICS_NAMESPACE,\n FLUSH_REQUEST_SHARE,\n FLUSH_TIMEOUT_MAX_MS,\n FLUSH_TIMEOUT_MS,\n GAP_REPORT_THROTTLE_MS,\n METRIC_NAMESPACE,\n ROUTING_KEYS,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n TRACE_FLAGS_SAMPLED,\n TRACE_NAMESPACE,\n INSTRUMENT_OPTIONS_FAULT,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type { FrameOptions, SourceOptions } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n ShutdownOptions,\n StorageScope,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { DebugBundle, FlushResult, FlushStatus, ObservabilityHealth } from \"../models/health\";\nimport type { PruneResult, StorageAdapter, StoragePersistence } from \"../models/storage\";\nimport type { StoreAccess } from \"../storage/stored-context\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { hasOwn, isObject } from \"../utils/guards\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} from \"../utils/identity\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { detectPlatform, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { sanitize, truncate } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { type Breadcrumb, BreadcrumbBuffer } from \"./breadcrumbs\";\nimport { applyResolvedConfig, REFUSE_RECORDS, resolveConfig } from \"./config\";\nimport { ContextStore } from \"./context\";\nimport { DebugBuffer } from \"./debug-buffer\";\nimport { cancelDeferred, drainDeferred } from \"./deferred\";\nimport {\n type DiagnosticCode,\n type DiagnosticEvent,\n type DiagnosticHandler,\n Diagnostics,\n} from \"./diagnostics\";\nimport { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { LibraryLogger, OneLogger } from \"./logger\";\nimport { createMeasure } from \"./measure\";\nimport { makeCounter, makeHistogram, Meter, type RecordMetric } from \"./meter\";\nimport { profilerCore, type ProfilerSink } from \"./profiler\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport type { RotationHost, rotateContext } from \"./rotation\";\nimport { sampleKey, shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\nimport { rootSpan, type SpanData, spanFields } from \"./spans\";\n\n/** Constructor for a capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** The import for each capture module. Each one is its own chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\n uncleanExit: async (): Promise<CaptureClass> =>\n (await import(\"../capture/unclean-exit\")).UncleanExitCapture,\n userTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/user-timing\")).UserTimingCapture,\n reports: async (): Promise<CaptureClass> => (await import(\"../capture/reports\")).ReportCapture,\n resourceTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/resource-timing\")).ResourceTimingCapture,\n lifecycle: async (): Promise<CaptureClass> =>\n (await import(\"../capture/lifecycle\")).LifecycleCapture,\n framePhases: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePhasesCapture,\n framePacing: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePacingCapture,\n replay: async (): Promise<CaptureClass> => (await import(\"../capture/replay\")).ReplayCapture,\n};\n\n/** Name of a capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** The parts of the session replay capture the runtime calls. */\ninterface ReplayControl extends Capture {\n /** Loads the recorder and starts it. */\n start(): Promise<void>;\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void;\n /** Drops the buffer and, if the recorder was running, starts a fresh recording. */\n reset(): void;\n}\n\n/** Constructor for the WebSocket capture plugin. */\ntype WebSocketClass = new (diagnostics: Diagnostics, config: ResolvedConfig) => CapturePlugin;\n\n/** An id per plugin object, so a new plugin object changes the capture key. */\nconst pluginIds = new WeakMap<object, number>();\n\n/** The last id pluginId() handed out. */\nlet lastPluginId = 0;\n\n/**\n * Returns a plugin object's id. The capture key can't hold the plugin itself, because a\n * plugin can contain a cycle and JSON.stringify would throw.\n * @param plugin The app's plugin.\n * @returns The object's id.\n */\nfunction pluginId(plugin: object): number {\n let id = pluginIds.get(plugin);\n\n if (id === undefined) {\n id = ++lastPluginId;\n pluginIds.set(plugin, id);\n }\n\n return id;\n}\n\n/** Global symbol key for the singleton runtime. All federated bundles share it. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key for the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_KEY);\n\n/** Config sections the delivery stack reads once, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections a later configure() can't change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/** Crumbs that log calls add. Before the start, they hold a body that no hook has seen. */\nconst LOGGED_CRUMBS: readonly string[] = [\"log\", \"event\", \"action\"];\n\n/** Text of the warning and the report after a failed first configure() call. */\nconst FAILED_START =\n \"configure() could not read its options. The library drops each record and installs no capture until a configure() call sets redact to a function or null.\";\n\n/** Text of the report for shutdown() options the library can't use. */\nconst SHUTDOWN_INVALID =\n 'shutdown() got invalid options. The library discards the records in memory. An invalid clearStorage removes the \"context\" scope.';\n\n/** Text of the report for flush() options the library can't use. */\nconst FLUSH_INVALID = \"flush() got invalid options. The library waits the default 5000 ms.\";\n\n/** Diagnostic codes for a normal event rather than a fault. Their records are logged at INFO. */\nconst NOTICE_CODES: ReadonlySet<DiagnosticCode> = new Set([\n \"bus.role_resolved\",\n \"config.reconfigured\",\n \"security.rotated\",\n \"journey.adopted\",\n \"journey.expired\",\n]);\n\n/**\n * Builds a text key for the capture section. A later configure() reinstalls the capture\n * modules only when the key changes, because a reinstall unpatches and repatches every host\n * function.\n * @param capture Capture section.\n * @returns The key. A function or a RegExp becomes fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n urlTransform: capture.urlTransform ? pluginId(capture.urlTransform) : undefined,\n // Only a loader's presence counts, so a new inline loader on each call reinstalls nothing.\n webVitals:\n typeof capture.webVitals === \"object\"\n ? { loader: capture.webVitals.loader !== undefined }\n : capture.webVitals,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n // A RegExp has no JSON form.\n userTiming:\n typeof capture.userTiming === \"object\"\n ? { include: capture.userTiming.include?.map(String) }\n : capture.userTiming,\n plugins: capture.plugins.map(pluginId),\n });\n}\n\n/**\n * Trims the URL fields of a diagnostic detail, because their query can hold a key.\n * onDiagnostic stays local and keeps them.\n * @param detail A diagnostic event's detail.\n * @returns The detail to put in a record.\n */\nfunction recordDetail(detail: unknown): unknown {\n if (!isObject(detail)) {\n return detail;\n }\n\n const copy = { ...detail };\n for (const key of [\"url\", \"endpoint\"]) {\n const value = copy[key];\n if (typeof value === \"string\") {\n copy[key] = recordedUrl(value, false);\n }\n }\n\n return copy;\n}\n\n/**\n * Removes the routing settings from a configuration. A console-only runtime must not send\n * or join a bus, because the other version's runtime does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n metricsEndpoint: null,\n tracesEndpoint: null,\n transport: null,\n transportOnExit: null,\n transportWorker: null,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Checks whether a configuration names a destination.\n * @param input Consumer configuration options.\n * @returns True if it has an endpoint, a signal endpoint or a transport.\n */\nfunction sends(input: Partial<ObservabilityConfig>): boolean {\n return (\n Boolean(input.endpoint) ||\n Boolean(input.metricsEndpoint) ||\n Boolean(input.tracesEndpoint) ||\n Boolean(input.transport) ||\n Boolean(input.transportWorker)\n );\n}\n\n/**\n * Builds a flush result. The counts that aren't given are 0.\n * @param status How the call ended.\n * @param counts The counts to set.\n * @returns The result.\n */\nfunction flushResult(\n status: FlushStatus,\n counts: Partial<Omit<FlushResult, \"status\">>,\n): FlushResult {\n return { status, accepted: 0, stored: 0, dropped: 0, forwarded: 0, pending: 0, ...counts };\n}\n\n/**\n * Builds the result of a flush that ran. It's \"timeout\" while a record waits, so \"timeout\"\n * always has pending records.\n * @param counts The counts to set.\n * @returns The result.\n */\nfunction settled(counts: Partial<Omit<FlushResult, \"status\">> & { pending: number }): FlushResult {\n return flushResult(counts.pending > 0 ? \"timeout\" : \"complete\", counts);\n}\n\n/**\n * Checks whether a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime older than 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the runtime's methods.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /** True while the security context is changing. */\n private rotating = false;\n /** Number of the latest rotateSecurityContext() call, so a queued call keeps `rotating` up. */\n private rotationSeq = 0;\n /**\n * True while this runtime has the profiler core attached. Tracking it keeps configure() from\n * restarting the sampling every time, and keeps a runtime with the profiler off from ever\n * creating the core and its global symbol.\n */\n private profilerOn = false;\n /** True while the old context's last records are being collected. */\n private closingContext = false;\n /** Version of another SDK copy that owns the page runtime, or null. */\n private mismatchVersion: string | null = null;\n /** True if the configured context id differs from the owner's context id. */\n private contextMismatch = false;\n /** The context change in progress. Shutdown waits for this promise. */\n private rotation?: Promise<void>;\n /** Memory store kept for later context changes. */\n private memoryStorage?: StorageAdapter;\n /** State of the persistent storage request. getHealth() reports it. */\n private storagePersistence: StoragePersistence = \"off\";\n /** True while a diagnostic record goes out. Diagnostics raised meanwhile produce no record. */\n private recordingDiagnostic = false;\n /** True while a rotation checks the next context's settings, so their records wait for it. */\n private holdingRecords = false;\n /** Diagnostics from that check. Their records go out when the new context opens. */\n private heldDiagnostics: DiagnosticEvent[] = [];\n /** Logger for the records that diagnostics.records produces. */\n private readonly diagnosticLogger = new OneLogger(() => this, DIAGNOSTICS_NAMESPACE);\n /** Records that minLevel or sampling dropped. An error in this context sends them first. */\n private readonly debugBuffer = new DebugBuffer(() => this.config.debugBuffer);\n /** True if the app supplied a context id at startup. */\n private explicitSecurityContext: boolean;\n /** True once this forwarder has taken a context id from its owner. */\n private ownerAdopted = false;\n\n /**\n * Checks whether a security context change is in progress.\n * @returns True until the current change completes.\n */\n isRotating(): boolean {\n return this.rotating;\n }\n\n /**\n * Locks or unlocks configuration when the app asks. Any other code on this origin can call\n * this too, so the lock is not access control.\n * @param locked True to refuse changes through configure().\n */\n setConfigurationLocked(locked: boolean): void {\n if (typeof locked === \"boolean\") {\n this.config.lockConfiguration = locked;\n }\n }\n /**\n * This copy's runtime when another version of the library owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * This runtime's library version. Another copy reads it from the global key, because two\n * versions sharing one runtime would call methods the other version doesn't have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\n /**\n * This runtime's bus protocol tag. A same-origin child frame reads it from the global key\n * before it opens a direct link, because a direct call has no envelope to carry the tag.\n */\n readonly protocol: string = BUS_PROTOCOL;\n\n /** Diagnostics reporter for internal faults. */\n readonly diagnostics: Diagnostics;\n\n /** Active configuration instance. A reconfigure changes it in place. */\n readonly config: ResolvedConfig;\n\n /** Detected host platform metadata. */\n readonly platform: PlatformMetadata;\n\n /** Identity context containing session, tab, and context identifiers. */\n readonly identity: Identity;\n\n /** Where the ids and the journey live. Memory until the start, so nothing touches storage. */\n private backing: IdentityStores = memoryStores();\n\n /** Stores for identity and journey keys. They read the backing on every call. */\n private readonly stores: IdentityStores = {\n local: () => this.backing.local(),\n session: () => this.backing.session(),\n opener: () => this.backing.opener?.() ?? null,\n };\n\n /** The identity strategy that the start uses. The app's startup call fixes it. */\n private identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. The start builds it again. */\n private sessionTouch: SessionTouch;\n\n /** Store for ambient application context attributes. */\n readonly context = new ContextStore();\n\n /** Ring buffer holding contextual user breadcrumbs. */\n readonly breadcrumbs: BreadcrumbBuffer;\n\n /** Distributed tracing context engine. */\n readonly tracing: TraceEngine;\n\n /** Monotonic sequence counter for records emitted in this context. */\n readonly sequence = new Sequence();\n\n /** Journey tracking engine managing workflow correlation. */\n readonly journey: JourneyEngine;\n\n /** Record builder assembling structured log records. */\n readonly builder: RecordBuilder;\n\n /** Slot for the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = {\n sampling: null,\n changed: () => {\n this.refreshCaptures();\n },\n };\n\n /** Number of delivery identity changes. A context's first id doesn't count as a change. */\n private identityEpoch = 0;\n\n /** Session replay's hook. It gets every ERROR and FATAL record. */\n private errorHook: ((record: LogRecord) => void) | undefined;\n\n /**\n * True after startReplay(), false after stopReplay(), undefined until either is called. The\n * app's last choice survives a reinstall of the capture modules.\n */\n private replayConsent: boolean | undefined;\n\n /** The installed session replay capture. */\n private replay: ReplayControl | undefined;\n\n /** Timer that restores the local capture switches once the remote TTL ends. */\n private remoteCaptureTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Settings of the current capture load or install. */\n private installedCaptureKey = \"\";\n\n /** The replay settings the running replay capture was built with. */\n private replayBuiltKey = \"\";\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\n\n /** Sums the values of the counter and histogram instruments. */\n private readonly meter: Meter;\n\n /**\n * Cross-realm communication bus. Null until its chunk loads. In bus.mode \"off\", it loads\n * only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Promise for the bus load and construction. Undefined until first needed. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Promise for the bus load and start. Undefined until first needed. */\n private busLoad?: Promise<Bus | null>;\n\n /**\n * Delivery stack. Set in the sender role with an endpoint or a custom transport, once the\n * chunk has loaded.\n */\n private sender?: Sender;\n\n /** The delivery stack load. Undefined when nothing loads, so records have no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads, or while a pause holds them. */\n private readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Records that dropPaused() reported, so a second pagehide doesn't count them again. */\n private readonly pausedLoss = new WeakSet<LogRecord>();\n\n /** Stored batches that a carry during a pause left for the next sender to adopt. */\n private carried: LogBatch[] = [];\n\n /** True once resetSession() ran. start() then keeps that session over the stored one. */\n private sessionPicked = false;\n\n /**\n * True after a rotation fails. The app asked to leave the context, so the runtime sends no\n * record with its endpoint or headers until a rotation succeeds.\n */\n private deliveryClosed = false;\n\n /**\n * The stopped sender of the context that a failed rotation closed. The next rotation that\n * succeeds retires it with its own rule, so the old records don't stay or move by accident.\n */\n private parkedSender: Sender | undefined;\n\n /** The sender that a rotation retires. Its records wait for the rotation's rule. */\n private retiring: Sender | undefined;\n\n /**\n * True after the first configure() call failed. The runtime stays unconfigured and refuses\n * each record, because it can't know what the app needs to redact.\n */\n private startFailed = false;\n\n /**\n * True once the runtime has started: the first configure() call that works, with enabled true.\n * Before that, nothing is patched, stored or sent.\n */\n private running = false;\n\n /** Opens the start gate below. Its promise sets it, and start() calls it. */\n private openGate!: () => void;\n\n /** Resolves at the start. A frame or worker that registers before it joins the bus then. */\n private readonly startGate = new Promise<void>((resolve) => {\n this.openGate = resolve;\n });\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Number of capture installs. An install replaced by a later one stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that rebuilding the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n uncleanExit: false,\n userTiming: false,\n };\n\n /** Holds records created before the bus role is resolved. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Records staged for forwarding on the next microtask. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True once startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. Set by init(), awaited by flush(). */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if shutdown stopped the runtime. */\n private destroyed = false;\n\n /** The first shutdown. A later shutdown() waits for it before it removes the stored data. */\n private stopping?: Promise<void>;\n\n /** When the server last accepted a batch, in epoch milliseconds. A rotation keeps it. */\n private lastSendAt: number | null = null;\n\n /** When the last storage gap warning was reported, in epoch milliseconds. */\n private lastGapAt = 0;\n\n /** Record limits for the builder and the console. The app's first configure() sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules for the journey engine. The app's first configure() sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /**\n * False until the app's startup call, the first configure() call that works. That call sets\n * every startup-fixed setting, also after an early log call.\n */\n private tunablesLocked = false;\n\n /**\n * True for a console-only runtime, which sends nothing, joins no bus and installs no capture.\n * That happens next to another version of the library on the page, or on a server.\n */\n private readonly degraded: boolean;\n\n /** True once a destination on a server has been reported. It is reported only once. */\n private serverReported = false;\n\n /**\n * Ends a forwarder's root span when its document unloads. The exit flush only ends it in the\n * sender, so without this the client spans of a frame or a view have no parent.\n */\n private readonly onPageHide = (): void => {\n drainDeferred(this);\n this.dropPaused();\n if (this.role() !== \"forwarder\") {\n return;\n }\n\n this.tracing.end();\n this.sendForwarded();\n };\n\n /**\n * @param input Initial consumer configuration options.\n * @param mismatch True for a console-only runtime next to another version.\n */\n private constructor(input: Partial<ObservabilityConfig>, mismatch: boolean) {\n // resolveConfig() checks the hook below. Until then, a value that isn't a function gets no\n // events, otherwise each report would call it and count a false handler.threw.\n this.diagnostics = new Diagnostics(\n typeof input.onDiagnostic === \"function\" ? input.onDiagnostic : undefined,\n );\n\n this.platform = detectPlatform(this.diagnostics);\n // A server has no page to capture and no storage, so it only writes to the console.\n this.degraded = mismatch || this.onServer();\n this.config = resolveConfig(this.allowed(input), this.diagnostics);\n this.explicitSecurityContext = Boolean(input.securityContext?.id);\n this.config.securityContext.id ||= newId(this.diagnostics);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n this.identityBuiltAs = this.config.identity;\n this.identity = resolveIdentity(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.sessionTouch = new SessionTouch(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.breadcrumbs = new BreadcrumbBuffer(this.config.captureLimits.breadcrumbs);\n // Sample a span by its trace, so the whole trace stays or goes.\n const keeps = (traceId: string): boolean =>\n sampleKey(traceId, this.config.sampling.defaultRate);\n this.tracing = new TraceEngine(\n this.diagnostics,\n this.config.correlation.traceMaxAgeMs ?? Infinity,\n this.config.otelLoader,\n {\n enabled: () => this.config.tracesEndpoint !== null,\n keeps,\n onEnd: (ended) => {\n if (keeps(ended.traceId)) {\n this.recordSpan(rootSpan(ended));\n }\n },\n },\n );\n // The startup values stick. A later configure() can't change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.consoleOutput, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n remote: this.remote,\n config: this.config,\n limits: this.limits,\n diagnostics: this.diagnostics,\n context: this.context,\n journey: this.journey,\n tracing: this.tracing,\n sequence: this.sequence,\n identity: this.identity,\n platform: this.platform,\n debug: this.debugBuffer,\n });\n\n this.meter = new Meter(\n () => this.config.metrics.intervalMs,\n (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n this.diagnostics,\n this.config.metrics,\n );\n // The record builder exists now, so a diagnostic can become a record.\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.syncProfiler();\n }\n\n /**\n * Returns the diagnostics handler. With diagnostics.records, it also sends every event as\n * a record.\n * @returns The handler, or undefined with no onDiagnostic and no diagnostic records.\n */\n private diagnosticHandler(): DiagnosticHandler | undefined {\n if (this.config.diagnostics.records === false) {\n return this.config.onDiagnostic;\n }\n\n return (event) => {\n this.recordDiagnostic(event);\n this.config.onDiagnostic?.(event);\n };\n }\n\n /**\n * Sends a diagnostic event as a record when diagnostics.records selects its code.\n * A diagnostic raised during that send produces no record, which stops a loop.\n * @param event Diagnostic event.\n */\n private recordDiagnostic(event: DiagnosticEvent): void {\n const { records } = this.config.diagnostics;\n const selected = records === true || (records !== false && records.includes(event.code));\n if (!selected || this.recordingDiagnostic) {\n return;\n }\n\n // The logger would drop this record with the rotation's other calls, but it's about the\n // next context, so endRotation() writes it there.\n if (this.holdingRecords) {\n this.heldDiagnostics.push(event);\n return;\n }\n\n this.recordingDiagnostic = true;\n try {\n const write = NOTICE_CODES.has(event.code)\n ? this.diagnosticLogger.info\n : this.diagnosticLogger.warn;\n write(event.message, {\n \"diagnostic.code\": event.code,\n \"diagnostic.count\": event.count,\n \"diagnostic.detail\": recordDetail(event.detail),\n });\n } finally {\n this.recordingDiagnostic = false;\n }\n }\n\n /**\n * Drops the held diagnostic records of a rotation that didn't open its context, and counts\n * each one as the logger counts a call during a rotation.\n */\n private dropHeldRecords(): void {\n const dropped = this.heldDiagnostics.length;\n this.heldDiagnostics = [];\n\n // A count of 0 would still add the counter, so a clean rotation would show a drop.\n if (dropped > 0) {\n this.diagnostics.count(\"record.dropped_during_rotation\", dropped);\n }\n }\n\n /**\n * Adds a breadcrumb from app code. The data is copied now, so a later change to the app's\n * object doesn't change the trail.\n * @param message Description of the event. A JavaScript caller can pass a non-string, which\n * is converted.\n * @param data Optional metadata.\n */\n addBreadcrumb(message: unknown, data?: Record<string, unknown>): void {\n if (this.rotating || this.destroyed) {\n return;\n }\n // A message whose toString() throws, or a data getter that throws, must not throw into\n // the app's call.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not add the breadcrumb.\",\n () => {\n const crumb: Breadcrumb = {\n t: Date.now(),\n category: \"custom\",\n message: truncate(String(message), this.limits.maxBodyChars),\n };\n\n if (data !== undefined) {\n const clean = sanitize(data, this.limits, this.diagnostics);\n crumb.data = isObject(clean) ? clean : { value: clean };\n }\n\n this.breadcrumbs.push(crumb);\n },\n );\n }\n\n /**\n * Adds a value to a counter or a histogram. The meter sends one point per interval.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // Guard against a value after shutdown, whose interval timer would outlive the runtime.\n // A pause records nothing, as a log call does nothing.\n if (!this.destroyed && !this.rotating && this.config.enabled) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Starts a timed operation. Its values are dropped if the runtime has shut down or a rotation\n * is running when it ends. With `securityContext.isolation`, a new delivery identity before\n * the end drops them too.\n * @param name Operation name.\n * @param attributes Attribute set for every histogram point.\n * @returns The operation's handle.\n */\n startMeasure(name: string, attributes?: MetricAttributes): Measure {\n const epoch = this.identityEpoch;\n const current = (): boolean =>\n !this.destroyed &&\n !this.rotating &&\n (!this.config.securityContext.isolation || this.identityEpoch === epoch);\n const copied = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the attributes of the measure.\",\n () => ({ ...attributes }),\n );\n\n // The name's toString() can throw. If it does, the measure gets an empty name.\n const label = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the name of the measure.\",\n () => \"\".concat(name),\n );\n\n return createMeasure(label ?? \"\", copied ?? {}, this.tracing.request().span, {\n metric: (def, value, points) => {\n if (current()) {\n this.recordMetric(def, value, points);\n }\n },\n span: (span) => {\n if (current()) {\n this.recordSpan(span);\n }\n },\n });\n }\n\n /**\n * Builds and emits the record for one span. The console doesn't print it and minLevel\n * doesn't drop it. The trace engine already sampled the trace before the span existed.\n * @param span The span data.\n */\n private recordSpan(span: SpanData): void {\n if (this.config.tracesEndpoint === null) {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"span\",\n body: span.name,\n namespace: TRACE_NAMESPACE,\n payload: span.attributes,\n fixed: spanFields(span),\n trace: { traceId: span.traceId, spanId: span.spanId, traceFlags: TRACE_FLAGS_SAMPLED },\n });\n this.emit(record);\n }\n\n /**\n * Builds and emits the record for one aggregated point. The console doesn't print it.\n * @param name Metric name.\n * @param attributes The call's attributes. The record limits apply to them.\n * @param fields The point's metric fields. The record limits don't truncate them.\n */\n private emitPoint(\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ): void {\n // A discard at shutdown drops the open interval, so don't build its points.\n if (this.destroyed) {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"metric\",\n body: name,\n namespace: METRIC_NAMESPACE,\n payload: attributes,\n fixed: fields,\n aggregated: true,\n });\n this.emit(record);\n }\n\n /**\n * Turns the profiler on or off to match profiler.enabled. Before switching off it sends the\n * points that are waiting, because the switch would otherwise drop them.\n */\n private syncProfiler(): void {\n // A pause detaches the probes, so they read no clock until enabled is true again.\n const enabled = this.config.profiler.enabled && this.config.enabled;\n if (enabled === this.profilerOn) {\n return;\n }\n\n this.profilerOn = enabled;\n const core = profilerCore();\n if (!enabled) {\n core.collect(false);\n core.detach();\n return;\n }\n\n // Profiler points take the same path as meter points, so hooks and transports apply.\n const sink: ProfilerSink = {\n capacity: this.config.profiler.maxProbes,\n intervalMs: () => this.config.metrics.intervalMs,\n emit: (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n diagnostics: this.diagnostics,\n // Same rule as emit(): the first collect of a rotation still goes to the old sender.\n ready: () => !this.rotating || this.closingContext,\n outlier: (name, ms) => {\n this.breadcrumbs.push({\n t: Date.now(),\n category: \"profile\",\n message: `${name} ${String(Math.round(ms))} ms`,\n });\n },\n };\n core.attach(sink);\n }\n\n /**\n * Gives or withdraws consent for session replay, and starts or stops the recorder if the\n * capture is installed.\n * @param consent True starts the recorder, false stops it.\n */\n setReplay(consent: boolean): void {\n this.replayConsent = consent;\n\n if (consent) {\n void this.replay?.start();\n } else {\n this.replay?.stop();\n }\n }\n\n /**\n * Sends the open interval of the meter and the profiler. The profiler doesn't calibrate here,\n * which keeps flush and the exit path short and synchronous.\n */\n private collectPoints(): void {\n this.meter.collect();\n if (this.profilerOn) {\n profilerCore().collect(false);\n }\n }\n\n /**\n * Starts a new identity epoch. With isolation on, the profiler also drops its data and open\n * spans, so a span from the old identity can't add to the new one. The old identity's remote\n * rules and capture switches don't apply to the new one.\n */\n private advanceIdentity(): void {\n this.identityEpoch++;\n if (this.profilerOn && this.config.securityContext.isolation) {\n profilerCore().reset();\n }\n this.remote.sampling = null;\n this.refreshCaptures();\n }\n\n /**\n * Checks the source policy before a direct child link opens.\n * @param source Child window.\n * @param origin The child window's origin.\n * @returns True if the bus allows this source.\n */\n readonly busCanAccept = (source: Window, origin: string): boolean =>\n this.bus?.isRegistered(source, origin) ?? false;\n\n /**\n * Receives direct messages from same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n * @param source The child frame's window.\n */\n readonly busAccept = (message: BusMessage, reply: Receive, source?: Window): void => {\n if (this.destroyed) {\n return;\n }\n\n // Messages wait for the bus in arrival order, because a promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The bus could not accept a direct message from a child frame.\",\n () => {\n bus.acceptDirect(message, reply, source);\n },\n );\n });\n };\n\n /**\n * Returns the runtime on this realm's global key. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns this copy's local runtime, or the pinned runtime if there is none. A pinned\n * runtime from another version returns null, and a log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime from another version returns null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Checks whether shutdown() stopped this runtime.\n * @returns True once destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /**\n * Initializes a new runtime instance or updates the existing singleton.\n * @param input Consumer configuration options.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n try {\n return ObservabilityRuntime.startOrUpdate(input, implicit);\n } catch (error) {\n const live = ObservabilityRuntime.current();\n // A getter in a later call threw before anything changed, so the current settings stay.\n if (live?.tunablesLocked) {\n live.diagnostics.report(\n \"config.invalid\",\n \"configure() could not read its options. The library keeps the current settings.\",\n undefined,\n error,\n );\n return live;\n }\n\n // An early log call's runtime takes the refusal too, otherwise its held records and a\n // later call without redact would go out unredacted.\n const runtime = live ?? ObservabilityRuntime.startOrUpdate({}, true);\n runtime.refuse(error);\n return runtime;\n }\n }\n\n /**\n * Fails closed after the app's first configure() call couldn't be read. The library can't\n * tell what the app must redact, so it refuses each record, the held ones too, until a call\n * sets redact itself. The runtime stays unconfigured, so it writes no id to storage.\n * @param error What reading the options threw.\n */\n private refuse(error: unknown): void {\n this.startFailed = true;\n // A quiet reporter, so the stand-in doesn't report the missing endpoint a second time.\n const next = resolveConfig({ redact: REFUSE_RECORDS }, new Diagnostics(), this.config);\n applyResolvedConfig(this.config, next);\n // The app's onDiagnostic may not exist yet, so the console gets the warning too.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- The only sink before an onDiagnostic exists.\n console.warn(`${LIBRARY_LOG_PREFIX} ${FAILED_START}`);\n });\n this.diagnostics.report(\"config.invalid\", FAILED_START, undefined, error);\n // The stand-in drops each held record, as it drops every new one.\n this.rehookHeld();\n }\n\n /**\n * Starts a runtime, or updates the one that runs. A getter in the input can throw here.\n * @param input Consumer configuration options.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns Active runtime instance.\n */\n private static startOrUpdate(\n input: Partial<ObservabilityConfig>,\n implicit: boolean,\n ): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() twice.\n local.reconfigure(input);\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime older than 0.9.0 has no sdkVersion, which also counts as another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion, implicit);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input, false);\n (globalThis as Record<symbol, unknown>)[RUNTIME_KEY] = runtime;\n Reflect.deleteProperty(globalThis, STOPPED_KEY);\n // An early log call's runtime waits for the app's configure().\n if (!implicit) {\n runtime.launch();\n }\n return runtime;\n }\n\n /**\n * Starts a console-only runtime next to another version's runtime. It sends nothing, joins\n * no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found The pinned runtime's sdkVersion. A runtime older than 0.9.0 has none.\n * @param implicit True for the unconfigured runtime that an early log call makes.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n implicit: boolean,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(input, true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.mismatchVersion = foundText;\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\n if (!implicit) {\n runtime.launch();\n }\n return runtime;\n }\n\n /**\n * Updates runtime configuration and refreshes affected subsystems.\n * @param input Partial configuration to merge.\n */\n private reconfigure(input: Partial<ObservabilityConfig>): void {\n if (this.rotating) {\n this.diagnostics.report(\n \"config.locked\",\n \"Configuration cannot change during security-context rotation.\",\n );\n return;\n }\n if (this.config.lockConfiguration) {\n const next = resolveConfig(input, this.diagnostics, this.config);\n if (!sameConfig(this.config, next)) {\n this.diagnostics.report(\n \"config.locked\",\n \"Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.\",\n );\n }\n return;\n }\n drainDeferred(this);\n const accepted = this.keepDestination(this.keepRouting(this.allowed(input)));\n // The app's startup call names its own id, so the id is explicit.\n if (!this.tunablesLocked && accepted.securityContext?.id) {\n this.explicitSecurityContext = true;\n }\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n // Nothing reads these sections before the start, so the app's startup call can set them.\n const fixed = this.tunablesLocked ? ([\"correlation\", \"storage\"] as const) : [];\n for (const key of fixed) {\n // Compare resolved values, so an undefined or invalid key isn't a change. Restore the\n // section in the next config, never in the app's own object.\n if (!sameConfig(next[key], this.config[key])) {\n this.diagnostics.report(\n \"config.invalid\",\n `${key} cannot change after startup. The library keeps the current settings.`,\n );\n Object.assign(next, { [key]: this.config[key] });\n }\n }\n this.keepStartupTunables(next);\n const { redact, processors, enabled } = this.config;\n // A pause sends the open interval first. Built now, those points go out after the pause.\n if (enabled && !next.enabled) {\n this.collectPoints();\n }\n applyResolvedConfig(this.config, next);\n // After a failed first call the library can't know which redact the app meant, so only a\n // call that sets redact itself, to a function or null, ends the refusal.\n if (this.config.redact !== REFUSE_RECORDS) {\n this.startFailed = false;\n }\n // A kept record only saw the hooks from its own log call. New hooks must not miss it.\n if (this.config.redact !== redact || this.config.processors !== processors) {\n this.debugBuffer.clear();\n }\n this.breadcrumbs.resize(this.config.captureLimits.breadcrumbs);\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n\n this.builder.invalidateResource();\n this.console.update(this.config.consoleOutput);\n this.keepBuiltIdentity();\n // The handler and the resource are up to date now, and points and diagnostics use both.\n this.syncProfiler();\n this.launch();\n // A pause keeps the sender's records, so they go out once enabled is true again.\n if (this.running && enabled !== this.config.enabled) {\n this.sender?.hold(!this.config.enabled);\n }\n\n // Reinstall only on a change, because a reinstall unpatches and repatches every host\n // function. A stale capture load stops at its generation check, so a reinstall is safe\n // at any time.\n this.refreshCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\"config.reconfigured\", \"A later configure() call updated the runtime.\");\n }\n\n /**\n * Checks whether the runtime is on a server, for example Node during server-side rendering.\n * @returns True on Node.\n */\n private onServer(): boolean {\n return this.platform.platform === \"node\";\n }\n\n /**\n * Removes the routing settings from a console-only runtime's input. On a server, it\n * reports a destination once.\n * @param input Consumer configuration options.\n * @returns The options the runtime accepts.\n */\n private allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.degraded) {\n return input;\n }\n\n if (this.onServer() && !this.serverReported && sends(input)) {\n this.serverReported = true;\n this.diagnostics.report(\n \"config.invalid\",\n \"The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.\",\n );\n }\n\n return consoleOnly(input);\n }\n\n /**\n * Removes routing and identity changes while isolation is on. The other settings still apply.\n * @param input Consumer configuration options.\n * @returns The options without the refused routing or identity changes.\n */\n private keepRouting(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.tunablesLocked || this.degraded || !this.config.securityContext.isolation) {\n return input;\n }\n\n // Compare resolved values. An unset endpoint keeps the current endpoint, so it isn't a\n // change. A separate reporter keeps the real resolve's diagnostics from being counted twice.\n const probe = resolveConfig(input, new Diagnostics(), this.config);\n const refused: string[] = ROUTING_KEYS.filter(\n (key) => !sameConfig(probe[key], this.config[key]),\n );\n if (probe.securityContext.id !== this.config.securityContext.id) {\n refused.push(\"securityContext.id\");\n }\n if (refused.length === 0) {\n return input;\n }\n\n const kept: Partial<ObservabilityConfig> = { ...input };\n for (const key of ROUTING_KEYS) {\n if (refused.includes(key)) {\n Reflect.deleteProperty(kept, key);\n }\n }\n if (refused.includes(\"securityContext.id\")) {\n const context = { ...input.securityContext };\n Reflect.deleteProperty(context, \"id\");\n kept.securityContext = context;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `Isolation refuses changes to ${refused.join(\", \")}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`,\n );\n return kept;\n }\n\n /**\n * Restores the startup tunables in the next config. Each tunable is read once by some part\n * of the runtime, so a later change would have no effect and is refused.\n * @param next The resolved config from a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The app's startup call sets that\n // runtime's limits, journey age and bus role settings.\n if (!this.tunablesLocked) {\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n // The bus reads its role settings once, when it starts.\n for (const key of [\"mode\", \"openFinRole\"] as const) {\n if (next.bus[key] !== this.config.bus[key]) {\n this.diagnostics.report(\n \"config.invalid\",\n `bus.${key} cannot change after startup. The library keeps \"${this.config.bus[key]}\".`,\n { requested: next.bus[key] },\n );\n Object.assign(next.bus, { [key]: this.config.bus[key] });\n }\n }\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n\n const { maxProbes } = this.config.profiler;\n if (next.profiler.maxProbes !== maxProbes) {\n this.diagnostics.report(\n \"config.invalid\",\n `profiler.maxProbes cannot change after startup. It stays ${String(maxProbes)}.`,\n { requested: next.profiler.maxProbes },\n );\n next.profiler.maxProbes = maxProbes;\n }\n }\n\n /**\n * Refuses a change to config sections by restoring the current values in the next config.\n * @param next The resolved config from a later configure() call.\n * @param sections Sections that can't change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (sameConfig(next[section], this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The current values stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\n }\n\n /**\n * Refuses a change that leaves the built delivery stack with no destination.\n * Without one, the retry engine removes every stored batch as if it were delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n // The stack picks its transport once. A rotation can pick another one. undefined keeps the\n // current transport, so only a value or null can add or remove one.\n for (const key of [\"transport\", \"transportWorker\"] as const) {\n const value = input[key];\n // A value that isn't a function adds nothing, so resolveConfig() reports its type instead.\n const adds = typeof value === \"function\" && this.config[key] === undefined;\n const removes = value === null && this.config[key] !== undefined;\n if (adds || removes) {\n this.diagnostics.report(\n \"config.invalid\",\n `You cannot add or remove ${key} after the delivery stack loads. The current transport stays.`,\n );\n accepted = { ...accepted };\n Reflect.deleteProperty(accepted, key);\n }\n }\n\n // \"\" is the value for \"not set\", so it removes the endpoint too.\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot remove the endpoint after the delivery stack loads. The current endpoint stays.\",\n );\n // An undefined endpoint keeps the current endpoint, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\n }\n\n /**\n * Restores the identity strategy from startup. The ids have existed since startup, and a\n * later change can't move them to another store.\n */\n private keepBuiltIdentity(): void {\n // The stores switch at the start, so the app's startup call can still pick the strategy.\n if (!this.tunablesLocked) {\n this.identityBuiltAs = this.config.identity;\n return;\n }\n\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /**\n * Fixes the startup settings at the first configure() call that works, then starts the\n * runtime once enabled is true. A failed first call leaves the runtime unconfigured.\n */\n private launch(): void {\n if (this.startFailed) {\n return;\n }\n\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n // These records never met the app's hooks, so they reach onDrop only after redact.\n if (!this.config.enabled) {\n this.drops.add(\"disabled\", this.rehookHeld());\n }\n }\n\n if (!this.running && this.config.enabled) {\n this.start();\n }\n }\n\n /**\n * Starts the runtime: reads the configured ids, gives the held records the app's hooks and\n * resource, then installs the captures and starts the bus and the sender. Runs once.\n */\n private start(): void {\n this.running = true;\n // The ids lived in memory until now, so a page that never calls configure() stores nothing.\n if (this.identityBuiltAs === \"storage\" && !this.onServer()) {\n this.backing = BROWSER_STORES;\n }\n\n const { sessionIdleMs, traceMaxAgeMs } = this.config.correlation;\n const { sessionId, tabId } = resolveIdentity(this.diagnostics, this.stores, sessionIdleMs);\n this.sessionTouch = new SessionTouch(this.diagnostics, this.stores, sessionIdleMs);\n // A newSession() before the start chose a new session, so the stored one mustn't replace it.\n if (this.sessionPicked) {\n this.sessionTouch.restart(this.identity.sessionId);\n } else {\n this.identity.sessionId = sessionId;\n }\n this.identity.tabId = tabId;\n this.builder.invalidateResource();\n // A log call's crumb holds its raw body, because no hook existed yet. The app's own crumbs stay.\n this.breadcrumbs.retain((crumb) => !LOGGED_CRUMBS.includes(crumb.category));\n this.tracing.setup(traceMaxAgeMs ?? Infinity, this.config.otelLoader);\n // Don't await. Without OTel, records use the ambient trace and nothing is lost.\n void this.tracing.loadOtel();\n\n for (const record of this.rehookHeld()) {\n this.bootBuffer.push(record, this.config.buffering.maxHeldRecords);\n }\n\n this.openGate();\n void this.init();\n }\n\n /**\n * Takes the records that log calls held before the app's startup call, and runs the app's\n * hooks on them now.\n * @returns The records the hooks kept, with the configured resource.\n */\n private rehookHeld(): LogRecord[] {\n return this.bootBuffer\n .take()\n .map((record) => this.builder.rehook(record))\n .filter((record) => record !== null);\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // A console-only runtime never forwards, and Node has no addEventListener.\n if (!this.degraded) {\n addEventListener(\"pagehide\", this.onPageHide);\n }\n\n // Start the capture imports now so they download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n // Set before the first await, so a flush() right after configure() waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /**\n * Resolves the bus role, loads the delivery stack and releases the boot records.\n * Never rejects.\n */\n private async boot(): Promise<void> {\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"Startup failed. The runtime continues with reduced function.\",\n undefined,\n error,\n );\n } finally {\n // Release the boot records before the captures load, so the exit flush can find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n }\n\n /**\n * Starts the bus load once.\n * @returns Promise that resolves to the started bus, or null if it didn't load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus once. Does not call start().\n * @returns Promise that resolves to the constructed bus, or null if it didn't load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. Never rejects.\n * @returns Promise that resolves to the started bus, or null if it didn't load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. Never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n // A frame or a worker can register before configure(), and the bus waits for the start.\n await this.startGate;\n const { Bus } = await import(\"../bus/bus\");\n\n // A shutdown can happen during the load, and a bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const bus = new Bus(\n this.config,\n this.diagnostics,\n this.platform,\n this.identity.contextId,\n this.identity.tabId,\n {\n onSecurityContext: (id) => {\n if (this.explicitSecurityContext && this.config.securityContext.id !== id) {\n this.contextMismatch = true;\n this.diagnostics.report(\n \"security.context_mismatch\",\n \"The configured security context differs from the upstream owner.\",\n );\n return false;\n }\n this.contextMismatch = false;\n if (this.config.securityContext.id !== id) {\n // The first owner id keeps the startup records and the app's context, because\n // those records had no other identity. A later change retires them, even before\n // ready.\n if (this.ownerAdopted) {\n drainDeferred(this);\n this.drops.add(\"security_context\", [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ]);\n this.forwardBuffer = [];\n this.context.clear();\n this.breadcrumbs.clear();\n // collect() removes the open measurements, and emit() refuses them during this\n // reset.\n const rotating = this.rotating;\n this.rotating = true;\n this.collectPoints();\n // The profiler holds on to its data while emit() refuses records. Don't let the\n // old owner's data reach the new owner.\n if (this.profilerOn) {\n profilerCore().reset();\n }\n // A same-origin owner stores its new session before it sends the new id, so use\n // that session. Otherwise every frame starts a different session.\n const shared = this.sessionTouch.stored();\n this.resetSession(\n shared !== undefined && shared !== this.identity.sessionId\n ? shared\n : newId(this.diagnostics),\n );\n this.rotating = rotating;\n this.advanceIdentity();\n }\n this.config.securityContext.id = id;\n }\n this.ownerAdopted = true;\n return true;\n },\n onRecords: (records) => {\n this.ingestForwarded(records);\n },\n paused: () => !this.config.enabled,\n onJourney: (journey) => {\n this.journey.applyRemote(journey);\n },\n onJourneyRequest: () => this.journey.current(),\n onTabConflict: () => {\n this.regenerateTabId();\n },\n onFlush: (timeoutMs) => this.flushFor(timeoutMs, false),\n remote: this.remote,\n },\n );\n\n this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has a destination, that is an\n * endpoint or a custom transport.\n * @returns Promise that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n // Nothing sends before the start or during a pause. A pause that ends calls this again. A\n // shutdown during startup loads nothing, so the held records reach onDrop and don't wait.\n const sends = this.running && this.config.enabled && !this.deliveryClosed && !this.destroyed;\n if (!sends || !this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Checks whether the config names a destination for the records.\n * @returns True if it has an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the delivery stack load once.\n * @returns Promise that resolves when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /**\n * Imports and builds the delivery stack, then moves the held records into it.\n * Never rejects.\n */\n private async buildSender(): Promise<void> {\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n storage: this.memoryStorage,\n onStorage: (storage) => {\n if (storage.name === \"memory\") {\n this.memoryStorage = storage;\n }\n },\n onPersistence: (state) => {\n this.storagePersistence = state;\n },\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n onLoss: this.reportLoss,\n remote: this.remote,\n beforeExit: () => {\n drainDeferred(this);\n this.collectPoints();\n this.tracing.end();\n },\n onSent: (at) => {\n this.lastSendAt = at;\n },\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime. Its\n // pipeline is empty, because the shutdown took the held records, so it sends nothing.\n if (!sender || this.destroyed) {\n await sender?.discard();\n return;\n }\n\n // A failed rotation closed the context during the load. This sender must not send the\n // old context's batches, so it stops and keeps them for the next rotation's rule.\n if (this.deliveryClosed) {\n await this.parkSender(sender);\n return;\n }\n\n this.sender = sender;\n // A pause that started during the load holds the new sender too.\n if (!this.config.enabled) {\n sender.hold(true);\n }\n } catch (error) {\n // Clear the load so a later configure() can try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The delivery stack did not load. The library does not send records.\",\n { held: this.pendingRecords.length },\n error,\n );\n this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\n this.sender?.push(record);\n }\n\n // A carry during a pause left its stored batches for this sender. After a failed load they\n // stay parked, otherwise a later clearStorage can't find their ids under the old context.\n if (this.sender && this.carried.length > 0) {\n const carried = this.carried;\n this.carried = [];\n await this.adoptStored(this.sender, carried);\n }\n }\n\n /**\n * Stores an earlier context's batches under this context.\n * @param sender The sender that adopts them.\n * @param stored The earlier context's stored batches.\n */\n private async adoptStored(sender: Sender, stored: readonly LogBatch[]): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the carried batches under the new context.\",\n () => sender.adopt(stored, this.config.securityContext.id),\n );\n }\n\n /** Refreshes temporary switches and restores local settings when their TTL ends. */\n private refreshCaptures(): void {\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n if (this.destroyed) {\n return;\n }\n\n const wire = this.remote.sampling?.wire();\n if (wire) {\n this.remoteCaptureTimer = setTimeout(() => {\n this.refreshCaptures();\n }, wire.ttlMs);\n unrefTimer(this.remoteCaptureTimer);\n }\n\n if (this.captureState(this.effectiveCapture()) !== this.installedCaptureKey) {\n void this.installCaptures();\n }\n }\n\n /**\n * Serializes the current capture settings and profiler observers into one string. When the\n * string changes, the captures are reinstalled.\n * @param settings Current capture settings.\n * @returns The string.\n */\n private captureState(settings: CaptureOptions): string {\n const { enabled, framePhases, framePacing } = this.config.profiler;\n\n return `${String(this.config.enabled)}${captureKey(settings)}${String(enabled && framePhases)}${String(enabled && framePacing)}${this.replayState(settings)}`;\n }\n\n /**\n * Serializes what the replay recorder reads when it starts. The replay capture has its own\n * key because a restart drops the buffer, so an unrelated capture change must not cause one.\n * The other replay values are read on use and apply without a restart.\n * @param settings Current capture settings.\n * @returns The string. Empty while replay is off, so a replay change then installs nothing.\n */\n private replayState(settings: CaptureOptions): string {\n const { replay } = this.config;\n\n if (!replay.enabled) {\n return \"\";\n }\n\n // Functions and recordOptions go in by identity: a function doesn't stringify, and the\n // app's recordOptions can have a cycle or a throwing getter. The endpoint and onSegment are\n // in, so a buffer never goes to a destination it wasn't recorded for. fullUrls and\n // ignoreUrls are in because the kept capture reads them from its install-time settings,\n // and a buffer recorded with full URLs must not survive the app turning them off.\n // replay.headers stays out, so a refreshed token doesn't drop the buffer.\n return JSON.stringify([\n replay.loader && pluginId(replay.loader),\n replay.onSegment && pluginId(replay.onSegment),\n pluginId(replay.recordOptions),\n replay.endpoint,\n replay.requireConsent,\n replay.mode,\n replay.maskText,\n replay.maskInputs,\n replay.maskSelectors,\n replay.blockSelectors,\n replay.recordCanvas,\n replay.bufferMs,\n replay.plugins.map(pluginId),\n settings.fullUrls,\n settings.ignoreUrls.map(String),\n ]);\n }\n\n /** Returns local capture settings with the permitted remote switches. */\n private effectiveCapture(): CaptureOptions {\n const settings = { ...this.config.capture };\n const remote = this.remote.sampling?.current()?.capture;\n for (const key of REMOTE_CAPTURE_FLAGS) {\n const value = remote?.[key];\n if (settings.remoteToggles.includes(key) && value !== undefined) {\n if (value && typeof settings[key] === \"object\") {\n continue;\n }\n settings[key] = value;\n }\n }\n\n return settings;\n }\n\n /** Loads, builds and installs the enabled capture modules. Never rejects. */\n private async installCaptures(): Promise<void> {\n // A console-only runtime next to another version patches nothing. The other version does.\n // Nothing is patched before the start.\n if (this.degraded || !this.running) {\n return;\n }\n\n const generation = ++this.captureGeneration;\n const settings = this.effectiveCapture();\n this.installedCaptureKey = this.captureState(settings);\n\n // A pause removes every patch and the recorder, so the page runs as if the library weren't\n // there. The replay buffer goes with the recorder, and enabled true starts a new recording.\n if (!this.config.enabled) {\n this.uninstallCaptures();\n return;\n }\n const replayKey = this.replayState(settings);\n\n // The recorder reads the live config whenever it starts, and newSession() or startReplay()\n // can restart it at any time. So once any install has asked for different settings, the\n // running recorder may no longer match the key it was built with, and it is never kept.\n if (replayKey !== this.replayBuiltKey) {\n this.replayBuiltKey = \"\";\n }\n\n // A running recorder whose start settings didn't change stays as it is. Reinstalling it\n // would drop the buffer, and with it the \"before\" of the next error.\n const kept = replayKey !== \"\" && replayKey === this.replayBuiltKey ? this.replay : undefined;\n const names: CaptureName[] = [];\n const { profiler } = this.config;\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing, so don't load the chunk for it.\n const consoleOn =\n typeof settings.console === \"object\"\n ? settings.console.levels?.length !== 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\n }\n if (settings.uncleanExit) {\n names.push(\"uncleanExit\");\n }\n if (settings.userTiming) {\n names.push(\"userTiming\");\n }\n\n if (settings.reports) {\n names.push(\"reports\");\n }\n if (settings.resourceTiming) {\n names.push(\"resourceTiming\");\n }\n if (settings.lifecycle) {\n names.push(\"lifecycle\");\n }\n // The profiler's observers share one chunk, and it only loads with the profiler on.\n if (profiler.enabled && profiler.framePhases) {\n names.push(\"framePhases\");\n }\n if (profiler.enabled && profiler.framePacing) {\n names.push(\"framePacing\");\n }\n if (this.config.replay.enabled && !kept) {\n names.push(\"replay\");\n }\n\n const [classes, WebSocketCapture] = await Promise.all([\n Promise.all(names.map((name) => this.loadCapture(name))),\n settings.webSocket ? this.loadWebSocket() : undefined,\n ]);\n\n // Guard against a later install or a shutdown during the load. A stale capture would\n // leak its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new one in one synchronous step, leaving no gap without capture.\n this.uninstallCaptures(kept);\n\n const ctx: CaptureContext = {\n isActive: () => !this.destroyed && !this.rotating,\n config: Object.assign(Object.create(this.config) as ResolvedConfig, { capture: settings }),\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new LibraryLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n recordMetric: (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n },\n recordSpan: (span) => {\n this.recordSpan(span);\n },\n sessionId: () => this.identity.sessionId,\n onError: (hook) => {\n this.errorHook = hook;\n },\n setContext: (key, value) => {\n // undefined removes the key, so the replay id goes when the recorder stops.\n this.context.merge({ [key]: value ?? null });\n },\n replayConsent: () => this.replayConsent,\n };\n\n classes.forEach((CaptureModule, index) => {\n if (CaptureModule) {\n const capture = new CaptureModule(ctx);\n this.captures.push(capture);\n\n // Find the replay capture by its loader, not by its name. A plugin could use that name.\n if (names[index] === \"replay\") {\n this.replay = capture as ReplayControl;\n this.replayBuiltKey = replayKey;\n }\n }\n });\n\n const plugins = WebSocketCapture\n ? [...settings.plugins, new WebSocketCapture(this.diagnostics, ctx.config)]\n : settings.plugins;\n\n for (const plugin of plugins) {\n this.captures.push(this.pluginCapture(plugin));\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not install the ${capture.name} capture.`,\n () => {\n capture.install();\n },\n );\n }\n }\n\n /**\n * Uninstalls the active capture modules.\n * @param kept A replay capture that stays installed, if there is one.\n */\n private uninstallCaptures(kept?: ReplayControl): void {\n for (const capture of this.captures) {\n if (capture !== kept) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not uninstall the ${capture.name} capture.`,\n () => {\n capture.uninstall();\n },\n );\n }\n }\n this.captures.length = 0;\n this.replay = kept;\n\n if (kept) {\n this.captures.push(kept);\n }\n }\n\n /**\n * Imports the WebSocket capture plugin. A failed import is reported and skipped.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadWebSocket(): Promise<WebSocketClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the webSocket capture.\",\n async () => (await import(\"../capture/web-socket\")).WebSocketCapture,\n );\n }\n\n /**\n * Wraps a plugin as a capture module. The plugin only gets public tools.\n * @param plugin The app's plugin, or a built-in one.\n * @returns The capture module.\n */\n private pluginCapture(plugin: CapturePlugin): Capture {\n const { name } = plugin;\n const record: RecordMetric = (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n };\n const fault = (error: unknown): void => {\n this.diagnostics.report(\"config.invalid\", INSTRUMENT_OPTIONS_FAULT, undefined, error);\n };\n const ctx: PluginContext = {\n logger: new OneLogger(() => this, `${CAPTURE_NAMESPACE}.${name}`),\n counter: (metric, options = {}) => makeCounter(metric, options, record, fault),\n histogram: (metric, options = {}) => makeHistogram(metric, options, record, fault),\n addBreadcrumb: (message, data) => {\n this.addBreadcrumb(message, data);\n },\n ownRequest: runAsLibraryRequest,\n };\n\n return {\n name,\n install: () => {\n plugin.install(ctx);\n },\n uninstall: () => {\n plugin.uninstall();\n },\n };\n }\n\n /**\n * Imports one capture module. A failed import is reported and skips only that module.\n * @param name Capture module name.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `The library could not load the ${name} capture.`,\n CAPTURE_LOADERS[name],\n );\n }\n\n /**\n * Attaches a Web Worker or MessagePort to the bus for record forwarding.\n * @param worker Target Worker or MessagePort instance.\n */\n registerWorker(worker: WorkerLike, options: SourceOptions = {}): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n if (this.destroyed) {\n return () => undefined;\n }\n\n // Attach on construction, because the worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n detach = bus.attachWorker(worker, options);\n },\n );\n\n // In bus.mode \"off\" startup didn't start the bus, so start it now.\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Registers a frame after the bus loads. Early removal cancels the registration.\n * @param frame Child frame or window.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n detach = this.diagnostics.guard(\"bus.send_failed\", \"The frame could not be registered.\", () =>\n bus.registerFrame(frame, options),\n );\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Stops every subsystem and unpins the runtime. By default it flushes the records first. A\n * discard sends nothing, and a clearStorage scope also removes the stored batches and ids. A\n * later call stops nothing more, but its clearStorage scope still applies.\n * @param options What to do with the records that wait, and which storage to remove.\n */\n async destroy(options?: ShutdownOptions): Promise<void> {\n const { discard, scope } = this.shutdownRule(options);\n // The removal waits for the first call, otherwise a late save of its flush or of its exit\n // flush could land after it.\n this.stopping ??= this.stop(discard);\n await this.stopping;\n if (scope !== undefined) {\n await this.clearStorage(scope);\n }\n }\n\n /**\n * Stops every subsystem once, then unpins the runtime.\n * @param discard True to send nothing and report the records in memory as discarded.\n */\n private async stop(discard: boolean): Promise<void> {\n // A flush sends the open interval's points and the root span. A discard builds neither.\n if (!discard) {\n drainDeferred(this);\n this.collectPoints();\n this.tracing.end();\n }\n // After shutdown() probes stop reading the clock until the next configure(), and their\n // data goes with the detach.\n if (this.profilerOn) {\n this.profilerOn = false;\n profilerCore().detach();\n }\n this.destroyed = true;\n // A journey call on the stopped runtime then writes to memory only, as each call records\n // nothing until the next configure().\n this.backing = memoryStores();\n cancelDeferred(this);\n // emitPoint() builds nothing now, so this only stops the meter's timer after a discard.\n this.collectPoints();\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n\n if (!this.degraded) {\n removeEventListener(\"pagehide\", this.onPageHide);\n }\n\n // The replay capture drops its buffer and its upload queue here.\n this.uninstallCaptures();\n const closing = discard ? this.discardHeld() : this.flushHeld();\n this.journey.destroy();\n this.bus?.destroy();\n await closing;\n // A load in progress stops its own stack, and shutdown() resolves only after that.\n await this.senderLoad;\n await this.rotation?.catch(() => undefined);\n // A parked sender keeps its records stored, and only its store needs to close.\n const parked = this.parkedSender;\n this.parkedSender = undefined;\n await this.diagnostics.guardAsync(\n \"pipeline.crashed\",\n \"The delivery stack of the old context did not stop at shutdown. The library leaves its stored batches in storage.\",\n async () => {\n await (discard\n ? parked?.discard()\n : parked?.retire(\"retain\", 0, this.config.securityContext.id));\n },\n );\n await this.memoryStorage?.close();\n\n // A local runtime must not remove the other version's runtime from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime would drop the app's settings.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\n }\n }\n\n /**\n * Reads the shutdown() options. A value it can't use reports config.invalid and discards,\n * because an app that asks to discard or to remove storage doesn't want a send.\n * @param options The app's options.\n * @returns True to discard, and the storage scope to remove.\n */\n private shutdownRule(options: unknown): { discard: boolean; scope?: StorageScope } {\n const read = this.readOptions(options, SHUTDOWN_INVALID);\n if (read === undefined) {\n return { discard: true };\n }\n\n const { pending, clearStorage } = read;\n // null turns the removal off, as null turns off other options.\n const unset = clearStorage === undefined || clearStorage === null;\n const knownScope = unset || clearStorage === \"context\" || clearStorage === \"namespace\";\n let scope: StorageScope | undefined;\n if (!unset) {\n // A value it can't use still removes the narrower scope, because the app asked for one.\n scope = clearStorage === \"namespace\" ? \"namespace\" : \"context\";\n }\n\n const flushes = pending === undefined || pending === \"flush\";\n // clearStorage always discards, so it can't honour an explicit \"flush\".\n if (!knownScope || !(flushes || pending === \"discard\") || (pending === \"flush\" && scope)) {\n this.diagnostics.report(\"config.invalid\", SHUTDOWN_INVALID);\n }\n\n return { discard: !flushes || scope !== undefined, scope };\n }\n\n /** Flushes the sender's records and runs the exit flush. Reports what can't go out. */\n private async flushHeld(): Promise<void> {\n // The sender can load before startup ends, for example while OpenFin's getOptions() waits,\n // so its last flush takes the startup records. Before dropPaused(), so a pause counts them.\n if (this.sender) {\n this.releaseBootBuffer();\n }\n\n // A paused sender sends nothing at shutdown either.\n this.dropPaused();\n // Sender.destroy awaits a normal flush, then runs the exit flush. The records already hold\n // their journey, so the journey and the bus can stop first.\n const closing = this.sender?.destroy();\n // A record in the forward buffer waits for its microtask, so the bus takes it before it stops.\n this.sendForwarded();\n // A stopped runtime loads no sender, so the records that wait for startup or for the load are\n // lost. Startup releases its records later, where nothing reports them. A pause reported its own.\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take()];\n this.drops.add(\"load_failed\", this.unreported(held));\n await closing;\n }\n\n /**\n * Drops the records in memory without a send and reports each one as \"discarded\". A record\n * in a request that is in flight isn't reported, because the request can still arrive.\n */\n private async discardHeld(): Promise<void> {\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take(), ...this.forwardBuffer];\n this.forwardBuffer = [];\n // The stopped runtime stays reachable until the next configure(), so the next user on a\n // shared device must not find the previous user's trail or attributes in it.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n this.context.clear();\n // The stores are memory now, so this writes no browser store and tells no peer.\n this.journey.applyRemote(null);\n const buffered = (await this.sender?.discard()) ?? [];\n this.drops.add(\"discarded\", this.unreported([...held, ...buffered]));\n }\n\n /**\n * Removes the stored batches, the emergency queue entries and the stored ids. Before the\n * first configure() call that works, no store is known, so it removes nothing.\n * @param scope Whose stored batches to remove.\n */\n private async clearStorage(scope: StorageScope): Promise<void> {\n if (!this.tunablesLocked) {\n return;\n }\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches at shutdown.\",\n async () => {\n const { clearStored } = await import(\"../storage/stored-context\");\n // A carry during a pause left its batches under an older context id. A first-call pause\n // hasn't switched to the browser stores yet, but an earlier page can have written the\n // ids there.\n const ids = this.carried.map((batch) => batch.id);\n this.carried = [];\n await clearStored(\n this.storeAccess(),\n scope,\n ids,\n this.identityBuiltAs === \"storage\" && !this.onServer(),\n );\n },\n );\n }\n\n /**\n * Routes a completed log record to the pipeline or forward buffer.\n * @param record Log record to emit, or null when the build dropped it.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed) {\n return;\n }\n\n // A record built during a rotation belongs to neither context.\n if (this.rotating && !this.closingContext) {\n this.drops.add(\"security_context\", [record]);\n return;\n }\n\n this.sessionTouch.touch(this.identity.sessionId);\n\n // An error first sends the records that minLevel or sampling dropped before it.\n const error = record.severityText === \"ERROR\" || record.severityText === \"FATAL\";\n const records = error ? [...this.debugBuffer.drain(), record] : [record];\n\n // Session replay uploads its buffer on an error. The hook has its own guard.\n if (error) {\n this.errorHook?.(record);\n }\n\n for (const one of records) {\n if (this.ready) {\n this.route(one);\n } else {\n this.bootBuffer.push(one, this.config.buffering.maxHeldRecords);\n }\n }\n }\n\n /**\n * Sends a record to the forward buffer or to the local pipeline, depending on the bus role.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.deliveryClosed) {\n this.drops.add(\"security_context\", [record]);\n return;\n }\n\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n // Console-only mode has no destination. Count the drop, otherwise no counter shows the loss.\n // A pause loads no sender, so it holds the record until enabled: true loads one.\n const paused = !this.config.enabled && this.hasDestination();\n if (!this.senderLoad && !paused) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record, this.config.buffering.maxHeldRecords);\n }\n\n /**\n * Reports the sender's records in memory as lost during a pause. A pause has no exit flush,\n * so a pagehide or a shutdown leaves nothing to send them.\n */\n private dropPaused(): void {\n if (this.config.enabled) {\n return;\n }\n\n // The records stay, and a page back from the back/forward cache sends them, so count once.\n const fresh = this.unreported([\n ...this.pendingRecords.records,\n ...(this.sender?.records() ?? []),\n ]);\n for (const record of fresh) {\n this.pausedLoss.add(record);\n }\n this.drops.add(\"disabled\", fresh);\n }\n\n /**\n * Leaves out the records that a pause already reported, so onDrop counts each loss once.\n * @param records Lost records.\n * @returns The records with no report yet.\n */\n private unreported(records: readonly LogRecord[]): LogRecord[] {\n return records.filter((record) => !this.pausedLoss.has(record));\n }\n\n /**\n * Counts a record dropped by a full hold buffer and passes it to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [record]);\n }\n\n /**\n * Batches records for asynchronous transmission to the upstream sender.\n * @param record Log record to forward.\n */\n private forward(record: LogRecord): void {\n this.forwardBuffer.push(record);\n if (this.forwardScheduled) {\n return;\n }\n this.forwardScheduled = true;\n\n queueMicrotask(() => {\n this.forwardScheduled = false;\n this.sendForwarded();\n });\n }\n\n /**\n * Hands the forward buffer's records to the bus.\n * @returns How many records went upstream.\n */\n private sendForwarded(): number {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n // An empty buffer makes no message. A forwarder always has a bus.\n const { bus } = this;\n if (records.length === 0 || !bus) {\n return 0;\n }\n\n return bus.sendRecords(records);\n }\n\n /**\n * Validates, samples and queues records from child frames or workers. A forwarded record\n * arrives already built, so this is the first point in this context where sampling can run.\n * Local records are sampled by RecordBuilder.\n * @param records Inbound payload from bus.\n */\n private ingestForwarded(records: unknown): void {\n if (this.destroyed) {\n return;\n }\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n const accepted: LogRecord[] = [];\n for (const record of records) {\n if (!isLogRecord(record)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n continue;\n }\n // A debug buffer record explains an error. Sampling by its key would drop it again.\n if (\n record.attributes[ATTR_DEBUG_BUFFER] !== true &&\n !shouldSample(record, this.config, this.remote.sampling?.current() ?? null)\n ) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n\n // A child context without redact forwards raw records, so the sender is the last gate.\n const redacted = this.builder.redactForwarded(record);\n if (redacted) {\n accepted.push(redacted);\n }\n }\n\n // Records that arrive while the context changes belong to neither identity. Report the\n // loss after sampling and redact, so onDrop never gets action names or journey ids that\n // redact masks.\n if (this.rotating) {\n this.drops.add(\"security_context\", accepted);\n return;\n }\n\n // The bus stays connected during a pause, but the sender sends nothing.\n if (!this.config.enabled) {\n this.drops.add(\"disabled\", accepted);\n return;\n }\n\n for (const record of accepted) {\n this.deliver(record);\n }\n }\n\n /** Flushes the startup records, adding the active journey to records that have none. */\n private releaseBootBuffer(): void {\n const buffered = this.bootBuffer.take();\n // The hooks have already seen every record, so a key added now would bypass redact.\n const { processors, redact } = this.config;\n const journey = processors.length === 0 && redact === undefined ? this.journey.current() : null;\n\n for (const record of buffered) {\n if (journey && !record.attributes[\"journey.id\"]) {\n record.attributes[\"journey.id\"] = journey.id;\n record.attributes[\"journey.name\"] = journey.name;\n }\n this.route(record);\n }\n }\n\n /**\n * Passes lost records to the onDrop report.\n * @param reason Why they were lost.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds, count) => {\n this.drops.add(reason, records, batchIds, count);\n };\n\n /**\n * Passes the evicted batches to the onDrop report and emits a warning record. The warning\n * records are throttled.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\n const now = Date.now();\n if (now - this.lastGapAt < GAP_REPORT_THROTTLE_MS) {\n return;\n }\n this.lastGapAt = now;\n\n new OneLogger(() => this, STORAGE_NAMESPACE).warn(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\n );\n };\n\n /** Creates and stores a new tab ID after a tab ID collision. */\n private regenerateTabId(): void {\n const fresh = newId(this.diagnostics);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n persistTabId(fresh, this.diagnostics, this.stores);\n this.builder.invalidateResource();\n // Otherwise the bus's next claim and hello carry the old id, and the clash starts again.\n this.bus?.setTabId(fresh);\n }\n\n /**\n * Starts a new session in this context. Sends the open metric points, starts a new trace,\n * ends the active journey and clears the breadcrumbs. Other tabs pick up the new id at\n * their next startup.\n */\n newSession(): void {\n if (this.destroyed) {\n return;\n }\n\n drainDeferred(this);\n this.resetSession(newId(this.diagnostics));\n }\n\n /**\n * Closes the old session's work and starts the given session.\n * @param sessionId Id of the session to start.\n */\n private resetSession(sessionId: string): void {\n this.sessionPicked = true;\n // Close the old session's work first, so its points and root span keep the old id.\n this.collectPoints();\n this.tracing.rotate(\"explicit\");\n this.journey.end();\n // On a shared machine, the next user must not see the previous user's trail.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n // The replay buffer still shows the previous user's page. Drop it and start a new recording.\n this.replay?.reset();\n\n (this.identity as { sessionId: string }).sessionId = sessionId;\n this.sessionTouch.restart(sessionId);\n this.builder.invalidateResource();\n }\n\n /**\n * Changes the delivery context in one operation. Rotations run in call order, so a logout\n * that starts during a login still runs, after the login.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with the old context's records, and the flush deadline.\n * @returns Promise that resolves when the change completes. Invalid settings reject it.\n */\n rotateSecurityContext(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions = {},\n ): Promise<void> {\n if (this.destroyed) {\n return Promise.reject(new Error(\"The runtime has stopped.\"));\n }\n // Before a configure() call works, there's no context to leave and no routing to replace.\n if (!this.tunablesLocked) {\n return Promise.reject(\n new Error(\n \"The runtime is not configured. Call configure() before rotateSecurityContext().\",\n ),\n );\n }\n\n // A record from this call on belongs to neither context, so it's dropped from here.\n drainDeferred(this);\n this.rotating = true;\n const seq = ++this.rotationSeq;\n // Check the promise, not the flag. \"carry\" clears the flag before it stores old batches again.\n const run = (this.rotation ?? Promise.resolve())\n .catch(() => undefined)\n .then(() => this.runRotation(update, options, seq));\n this.rotation = run;\n const settle = (): void => {\n if (this.rotation === run) {\n this.rotation = undefined;\n this.rotating = false;\n this.retiring = undefined;\n }\n };\n run.then(settle, settle);\n return run;\n }\n\n /**\n * Runs one rotation once the earlier ones are done. The rotation code loads on the first call.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with the old context's records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the change completes.\n */\n private async runRotation(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n ): Promise<void> {\n if (this.destroyed) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // A forwarder sends through its owner, so this is a usage error and its delivery stays open.\n await this.started;\n if (this.role() === \"forwarder\") {\n throw new Error(\n \"Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.\",\n );\n }\n\n let rotate: typeof rotateContext;\n try {\n rotate = (await import(\"./rotation\")).rotateContext;\n } catch (error) {\n // The app asked to leave this context, so a rotation that can't run closes it.\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The library could not load the security-context rotation.\",\n undefined,\n error,\n );\n await this.closeDelivery();\n throw error;\n }\n\n // shutdown() ran during the load, so a rotation now would delete stored batches unreported.\n if (this.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n try {\n await rotate(this.rotationHost(), update, options, seq);\n } finally {\n // endRotation() takes the held records once the new context opens, so only a failed\n // rotation leaves any here. Dropping them keeps them out of a later rotation's context.\n this.dropHeldRecords();\n }\n }\n\n /**\n * Returns the changes the rotation code can make to this runtime's private state.\n * @returns The rotation host.\n */\n private rotationHost(): RotationHost {\n return {\n runtime: this,\n quiet: new Diagnostics(),\n senderLoaded: async () => {\n await this.senderLoad;\n },\n holdRecords: (plan) => {\n this.holdingRecords = true;\n try {\n return plan();\n } finally {\n this.holdingRecords = false;\n }\n },\n allowed: (input) => this.allowed(input),\n closeDelivery: () => this.closeDelivery(),\n closeContext: () => {\n // The old context's last points and root span still go to its own sender.\n this.closingContext = true;\n try {\n this.collectPoints();\n this.tracing.end();\n this.journey.end();\n } finally {\n this.closingContext = false;\n }\n },\n takeOld: () => {\n const held = [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ];\n const sender = this.sender ?? this.parkedSender;\n // A flush during the retire still sees these records, so it doesn't call them lost.\n this.retiring = sender;\n const carried = this.carried;\n this.forwardBuffer = [];\n this.carried = [];\n this.sender = undefined;\n this.senderLoad = undefined;\n this.parkedSender = undefined;\n return { held, sender, closed: this.deliveryClosed, carried };\n },\n drop: (records) => {\n this.drops.add(\"security_context\", this.unreported(records));\n },\n storeAccess: () => this.storeAccess(),\n advanceIdentity: () => {\n this.advanceIdentity();\n },\n openDelivery: async () => {\n this.deliveryClosed = false;\n await this.syncSender();\n this.bus?.rotateContext();\n },\n endRotation: (seq) => {\n // A queued rotation keeps the flag up, because a later record belongs to its context.\n this.rotating = seq !== this.rotationSeq;\n\n // The queued rotation replaces this context, so the held records have nowhere to go.\n if (this.rotating) {\n this.dropHeldRecords();\n return;\n }\n\n const held = this.heldDiagnostics;\n this.heldDiagnostics = [];\n for (const event of held) {\n this.recordDiagnostic(event);\n }\n },\n route: (record) => {\n this.route(record);\n },\n adopt: async (stored) => {\n // A pause loads no sender, so the next sender adopts them. With no destination, they\n // stay parked under the old id, so none is lost. A stopped runtime has no sender, and a\n // clearStorage shutdown removes the parked ids.\n if (!this.config.enabled || this.destroyed) {\n this.carried = [...stored];\n return;\n }\n await this.sender?.adopt(stored, this.config.securityContext.id);\n },\n };\n }\n\n /**\n * Stops delivery after a rotation fails. The app asked to leave this context, so its endpoint\n * and headers send no record until a rotation succeeds. The old records stay stored under\n * the old id, and the next rotation that succeeds applies its rule to them.\n */\n private async closeDelivery(): Promise<void> {\n this.deliveryClosed = true;\n this.diagnostics.report(\n \"security.rotation_failed\",\n \"The security-context rotation failed. The library sends no record until a rotation succeeds.\",\n );\n\n // A load in progress sees the closed flag and parks its own sender.\n await this.senderLoad;\n const old = this.sender;\n this.sender = undefined;\n this.senderLoad = undefined;\n if (old) {\n await this.parkSender(old);\n }\n\n // These records arrived during the rotation, so they belong to the context the app left.\n this.drops.add(\"security_context\", this.unreported(this.pendingRecords.take()));\n }\n\n /**\n * Stops a sender of a closed context and keeps it, so the next rotation that succeeds can\n * apply its rule to the records of that context.\n * @param sender The sender to stop.\n */\n private async parkSender(sender: Sender): Promise<void> {\n this.parkedSender = sender;\n\n await this.diagnostics.guardAsync(\n \"pipeline.crashed\",\n \"The delivery stack of the old context did not stop. The next rotation that succeeds retires it.\",\n () => sender.pause(this.config.securityContext.id),\n );\n }\n\n /**\n * Collects this runtime's state for a support ticket. The app decides where to send it.\n * @param health Health snapshot from the facade, with the logger cache counts.\n * @returns Promise that resolves to the JSON-safe bundle.\n */\n async debugBundle(health: ObservabilityHealth): Promise<DebugBundle> {\n const { configSummary } = await import(\"./debug-bundle\");\n // Build the breadcrumbs as a record so the privacy hooks run, as they do for an error record.\n const { record } = this.builder.build(\n {\n level: \"INFO\",\n type: \"system\",\n body: \"debug bundle\",\n namespace: DIAGNOSTICS_NAMESPACE,\n payload: { [ATTR_BREADCRUMBS]: this.breadcrumbs.snapshot() },\n },\n true,\n );\n const attributes = record?.attributes ?? {};\n const crumbs = attributes[ATTR_BREADCRUMBS];\n const pageUrl = attributes[ATTR_PAGE_URL];\n\n return {\n createdAt: new Date().toISOString(),\n sdkVersion: this.sdkVersion,\n health,\n diagnostics: this.diagnostics.snapshot(),\n resource: record?.resource ?? {},\n pageUrl: typeof pageUrl === \"string\" ? pageUrl : \"\",\n breadcrumbs: Array.isArray(crumbs) ? crumbs : [],\n debugBuffer: this.debugBuffer.snapshot(),\n config: configSummary(this.config, this.limits, this.diagnostics),\n };\n }\n\n /**\n * Reads this runtime's state. Doesn't wait for startup or for the sender to load.\n * @returns State, delivery counts and policies. The facade adds the logger cache counts.\n */\n async health(): Promise<Omit<ObservabilityHealth, \"loggerCache\">> {\n const sent = this.sender?.stats();\n const issues: ObservabilityHealth[\"issues\"] = [];\n if (this.mismatchVersion) {\n issues.push(\"runtime.version_mismatch\");\n }\n if (this.contextMismatch) {\n issues.push(\"security.context_mismatch\");\n }\n const { redact, processors } = this.config;\n if (redact === REFUSE_RECORDS || processors.includes(REFUSE_RECORDS)) {\n issues.push(\"records.refused\");\n }\n if (this.deliveryClosed) {\n issues.push(\"security.rotation_failed\");\n } else if (\n // A pause loads no sender, and that isn't a fault.\n this.ready &&\n this.config.enabled &&\n this.hasDestination() &&\n this.role() === \"sender\" &&\n !this.sender\n ) {\n issues.push(\"sender.unavailable\");\n }\n const { sourcePolicy, maxMessageBytes, maxRecordsPerMessage, maxMessagesPerSecond } =\n this.config.bus;\n return {\n delivery: {\n pending: (sent?.pending ?? 0) + this.heldRecords(),\n inFlight: sent?.inFlight ?? 0,\n stored: await this.storedBatches(),\n lastSendAt: this.lastSendAt,\n // A rotation builds a new sender, so these start again with it.\n lastFailureAt: sent?.lastFailureAt ?? null,\n consecutiveFailures: sent?.consecutiveFailures ?? 0,\n throttledUntil: sent?.throttledUntil ?? null,\n dropped: this.drops.counts(),\n },\n sdkVersion: this.sdkVersion,\n owningSdkVersion: this.mismatchVersion,\n status: this.destroyed\n ? \"stopped\"\n : !this.tunablesLocked\n ? \"unconfigured\"\n : !this.config.enabled\n ? \"disabled\"\n : this.rotating\n ? \"rotating\"\n : issues.length\n ? \"degraded\"\n : !this.ready\n ? \"starting\"\n : \"ready\",\n mode:\n this.role() === \"forwarder\"\n ? \"forwarder\"\n : this.hasDestination()\n ? \"sender\"\n : \"console-only\",\n senderReady:\n this.sender !== undefined &&\n this.config.enabled &&\n !this.destroyed &&\n !this.rotating &&\n !this.deliveryClosed,\n configurationLocked: this.config.lockConfiguration,\n issues,\n securityContext: { ...this.config.securityContext },\n storagePersistence: this.storagePersistence,\n bus: { sourcePolicy, maxMessageBytes, maxRecordsPerMessage, maxMessagesPerSecond },\n };\n }\n\n /**\n * Returns what opening the store needs when no sender runs.\n * @returns The config, the reporter and the kept memory store.\n */\n private storeAccess(): StoreAccess {\n return { config: this.config, diagnostics: this.diagnostics, memory: this.memoryStorage };\n }\n\n /**\n * Counts the stored batches. After a failed rotation, the parked sender's store still holds\n * the closed context's batches, and they count until a rotation retires them.\n * @returns Promise that resolves to the number of stored batches.\n */\n private async storedBatches(): Promise<number> {\n return (await (this.sender ?? this.parkedSender)?.queueDepth()) ?? 0;\n }\n\n /**\n * Sends the records in memory and waits until each one has a final state or the time limit\n * passes. A forwarder hands its records to its sender, then asks the sender to flush.\n * @param options How long to wait. A value it can't use reports config.invalid.\n * @returns Promise that resolves to what became of the records in memory at the call. It\n * never rejects.\n */\n flush(options?: unknown): Promise<FlushResult> {\n return this.flushFor(this.flushTimeout(options), true);\n }\n\n /**\n * Runs a flush with a time limit that is already in range.\n * @param timeoutMs How long to wait, in milliseconds.\n * @param collect True to send the open interval of the meter and the profiler first. A flush\n * that a child asks for doesn't, otherwise each request would make this context build points.\n * @returns Promise that resolves to the flush result.\n */\n private async flushFor(timeoutMs: number, collect: boolean): Promise<FlushResult> {\n drainDeferred(this);\n if (collect) {\n this.collectPoints();\n }\n\n const idle = this.idle();\n if (idle) {\n return idle;\n }\n\n const ends = Date.now() + timeoutMs;\n let stop!: () => void;\n const expired = new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n unrefTimer(timer);\n stop = () => {\n clearTimeout(timer);\n };\n });\n\n try {\n return await this.flushBefore(ends, expired);\n } finally {\n stop();\n }\n }\n\n /**\n * Waits for startup and the delivery stack, then flushes the sender or asks the upstream one.\n * @param ends Epoch time in milliseconds of the deadline.\n * @param expired Resolves at the deadline.\n * @returns The flush result.\n */\n private async flushBefore(ends: number, expired: Promise<void>): Promise<FlushResult> {\n // These records wait for startup or for the sender, and they're lost if no sender loads.\n const held = this.heldRecords();\n\n // A record waits in a hold buffer during startup, which loads the first sender, and while a\n // later configure() loads one. The flush would miss it without this wait. Otherwise don't\n // wait, so the snapshot and the forward buffer handover happen in the call itself.\n const loading = this.ready ? this.senderLoad : this.started;\n if (loading && (!this.ready || !this.sender)) {\n const loaded = await Promise.race([loading.then(() => true), expired.then(() => false)]);\n if (!loaded) {\n return settled({ pending: this.waiting() });\n }\n }\n\n const { bus } = this;\n const forwarder = bus?.getRole() === \"forwarder\";\n\n // A pause or a shutdown during the wait leaves nothing to send.\n const idle = this.idle();\n if (idle) {\n return idle;\n }\n\n if (forwarder) {\n // The records go before the request on the same link, so they're in the sender's snapshot.\n // A record that the bus doesn't send, for its size or for no owner, is lost here.\n const total = this.forwardBuffer.length;\n const forwarded = this.sendForwarded();\n const lost = total - forwarded;\n // The sender gets a share of the time left, so its answer arrives before this call ends.\n const share = Math.floor(Math.max(0, ends - Date.now()) * FLUSH_REQUEST_SHARE);\n const answer = await bus.requestFlush(share, expired);\n return answer\n ? { ...answer, forwarded, dropped: answer.dropped + lost }\n : settled({ forwarded, pending: forwarded, dropped: lost });\n }\n\n const { sender } = this;\n if (!sender) {\n // During a rotation the old records wait for its rule. Without a sender, they're lost.\n return this.rotating\n ? settled({ pending: held + this.waiting() })\n : flushResult(\"complete\", { dropped: held });\n }\n\n return settled(await sender.flushUntil(expired));\n }\n\n /**\n * Returns the result for a runtime that sends nothing now: before the start, after a failed\n * first configure(), during a pause and after shutdown().\n * @returns The \"inactive\" result with the records that wait in memory, or null.\n */\n private idle(): FlushResult | null {\n if (this.tunablesLocked && this.config.enabled && !this.destroyed) {\n return null;\n }\n\n // A stopped runtime sends nothing more, so no record waits for it.\n return flushResult(\"inactive\", { pending: this.destroyed ? 0 : this.waiting() });\n }\n\n /**\n * Counts the records in the hold buffers and the forward buffer.\n * @returns The record count.\n */\n private heldRecords(): number {\n return this.bootBuffer.length + this.pendingRecords.length + this.forwardBuffer.length;\n }\n\n /**\n * Counts the records in memory: the hold buffers, the forward buffer, and the buffers, the\n * queue and the requests of the sender and of a sender that a rotation retires.\n * @returns The record count.\n */\n private waiting(): number {\n let total = this.heldRecords();\n for (const sender of [this.sender, this.retiring]) {\n const sent = sender?.stats();\n total += sent ? sent.pending + sent.inFlight : 0;\n }\n return total;\n }\n\n /**\n * Copies a call's options. A value that isn't an object reports config.invalid with the text,\n * and so does a getter that throws.\n * @param options The app's options. undefined and null read as no options.\n * @param text The text of the report.\n * @returns The copy, or undefined after a report.\n */\n private readOptions(options: unknown, text: string): Record<string, unknown> | undefined {\n // A JavaScript caller can pass a string, or an object with a getter that throws.\n if (typeof options !== \"object\" && options !== undefined) {\n this.diagnostics.report(\"config.invalid\", text);\n return undefined;\n }\n\n return this.diagnostics.guard(\"config.invalid\", text, () => ({ ...options }));\n }\n\n /**\n * Reads flush()'s time limit. A value it can't use reports config.invalid, and the default\n * applies. null options and a null timeoutMs give the default, as in shutdown() and\n * rotateSecurityContext().\n * @param options The app's options.\n * @returns The time limit in milliseconds.\n */\n private flushTimeout(options: unknown): number {\n const read = this.readOptions(options, FLUSH_INVALID);\n if (!read) {\n return FLUSH_TIMEOUT_MS;\n }\n\n const ms = read.timeoutMs ?? FLUSH_TIMEOUT_MS;\n if (typeof ms === \"number\" && ms >= 0 && ms <= FLUSH_TIMEOUT_MAX_MS) {\n return ms;\n }\n\n this.diagnostics.report(\"config.invalid\", FLUSH_INVALID);\n return FLUSH_TIMEOUT_MS;\n }\n}\n\n/**\n * Compares resolved settings without JSON conversion. Functions are compared by identity.\n * The seen map keeps a cycle from causing repeated comparisons.\n * @param a First value.\n * @param b Second value.\n * @param seen Object pairs already compared.\n * @returns True if the values are equal.\n */\nfunction sameConfig(a: unknown, b: unknown, seen = new WeakMap<object, object>()): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (a instanceof RegExp && b instanceof RegExp) {\n return String(a) === String(b);\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (seen.has(a)) {\n return seen.get(a) === b;\n }\n seen.set(a, b);\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return (\n ak.length === bk.length &&\n ak.every((key) => hasOwn(b, key) && sameConfig(Reflect.get(a, key), Reflect.get(b, key), seen))\n );\n}\n","import {\n TELEMETRY_SDK_VERSION,\n TRANSPORT_WORKER_PROTOCOL,\n TRANSPORT_WORKER_REFUSAL,\n TRANSPORT_WORKER_TYPE,\n} from \"../constants\";\nimport { Diagnostics, type DiagnosticHandler } from \"../core/diagnostics\";\nimport { isObject } from \"../utils/guards\";\n\nlet active: (() => void) | undefined;\n\n/** Installs the worker service synchronously before its delivery module loads. */\nexport function serveTransportWorker(\n options: { onDiagnostic?: DiagnosticHandler } = {},\n): () => void {\n if (active) {\n return active;\n }\n const diagnostics = new Diagnostics(options.onDiagnostic);\n if (typeof document !== \"undefined\" || typeof addEventListener !== \"function\") {\n diagnostics.report(\"config.invalid\", \"Call serveTransportWorker() in a dedicated worker.\");\n return () => undefined;\n }\n\n let stopped = false;\n let port: MessagePort | undefined;\n let detach: (() => void) | undefined;\n const onMessage = (event: MessageEvent<unknown>): void => {\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport worker could not read its connection.\",\n () => {\n const message = event.data;\n if (\n !isObject(message) ||\n message.p !== TRANSPORT_WORKER_PROTOCOL ||\n message.t !== TRANSPORT_WORKER_TYPE.connect\n ) {\n return;\n }\n if (event.ports.length === 0) {\n return;\n }\n const incoming = event.ports[0];\n if (port || message.v !== TELEMETRY_SDK_VERSION) {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n return;\n }\n\n port = incoming;\n void import(\"./worker-server\")\n .then((module) => {\n if (!stopped) {\n detach = module.serveWorkerPort(incoming, diagnostics);\n }\n })\n .catch((error: unknown) => {\n diagnostics.report(\n \"transport.http_error\",\n \"The transport worker delivery module could not load.\",\n undefined,\n error,\n );\n diagnostics.guard(\n \"transport.http_error\",\n \"The failed transport port could not be closed.\",\n () => {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n },\n );\n });\n },\n );\n };\n\n const stop = (): void => {\n if (stopped) {\n return;\n }\n stopped = true;\n active = undefined;\n removeEventListener(\"message\", onMessage);\n detach?.();\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport service could not close its port.\",\n () => {\n port?.postMessage(TRANSPORT_WORKER_REFUSAL);\n },\n );\n diagnostics.guard(\"transport.http_error\", \"The transport port could not close.\", () => {\n port?.close();\n });\n };\n addEventListener(\"message\", onMessage);\n active = stop;\n return stop;\n}\n","// src/transport/memory-transport.ts\n//\n// A transport for tests that keeps every batch in memory, so a test can check the records the\n// library sends without a network or a fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport for tests that keeps every batch in memory. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of every accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns every request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets every batch. The answer set with respondWith stays. */\n clear(): void;\n /**\n * Sets the answer for all later batches. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps every batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\n };\n}\n","// src/index.ts\n//\n// The library's public entry point. Exports the facade API, the logging primitives and\n// the types.\n\nimport type { WorkerLike } from \"./bus/links\";\nimport type { Journey } from \"./core/journey\";\nimport { INSTRUMENT_OPTIONS_FAULT } from \"./constants\";\nimport { OneLogger, type OneLogger as Logger, type OneLoggerOptions } from \"./core/logger\";\nimport { measureCall } from \"./core/measure\";\nimport { makeCounter, makeGauge, makeHistogram } from \"./core/meter\";\nimport { profilerCore } from \"./core/profiler\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport { isObject } from \"./utils/guards\";\nimport type { ObservabilityConfig } from \"./models/config\";\nexport type {\n ReplayLoader,\n ReplayPluginLoader,\n ReplayPluginTools,\n ReplaySegment,\n} from \"./models/replay\";\nimport type {\n FlushOptions,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n ShutdownOptions,\n} from \"./models/config\";\nimport type { DebugBundle, FlushResult, ObservabilityHealth } from \"./models/health\";\nimport type { FrameOptions, SourceOptions } from \"./models/bus\";\nexport type { FrameOptions, SourceOptions, BusPermission } from \"./models/bus\";\nimport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Profiler,\n} from \"./models/metric\";\n\nexport { serveTransportWorker } from \"./transport/worker-entry\";\nexport { observeWindow } from \"./capture/observed-windows\";\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, Logger, ObservabilityConfig, OneLoggerOptions };\nexport type {\n BatchingOptions,\n BufferingOptions,\n BusOptions,\n CaptureLimitsOptions,\n CaptureOptions,\n ConsoleCaptureOptions,\n ConsoleOutputOptions,\n ConsoleStyles,\n CorrelationOptions,\n DebugBufferOptions,\n DeliveryOptions,\n DiagnosticsOptions,\n FlushOptions,\n InteractionOptions,\n JourneyOptions,\n LimitsOptions,\n LoggerCacheOptions,\n LongFramesOptions,\n MetadataOptions,\n MetricsOptions,\n ProfilerOptions,\n RemoteCaptureFlag,\n ReplayOptions,\n ResourceTimingOptions,\n RetentionOptions,\n RoutingOptions,\n SamplingOptions,\n SecurityContextOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n ShutdownOptions,\n StorageOptions,\n StorageScope,\n UserTimingOptions,\n WebVitalsOptions,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type {\n DebugBundle,\n DeliveryHealth,\n FlushResult,\n FlushStatus,\n ObservabilityHealth,\n} from \"./models/health\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type {\n Counter,\n Gauge,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Probe,\n ProbeOptions,\n Profiler,\n} from \"./models/metric\";\nexport type { CapturePlugin, PluginContext } from \"./models/plugin\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { StorageAdapter } from \"./models/storage\";\n\n/**\n * Cached loggers, keyed by namespace. A scoped logger never goes in this map.\n * A logger looks up the runtime on every write, so the cache stays valid across\n * configure() and shutdown().\n */\nconst loggers = new Map<string, Logger>();\n\n/**\n * Returns the active runtime. After shutdown() that is the stopped runtime, which does\n * nothing. Before the first configure(), it makes an unconfigured runtime, which holds records\n * in memory and starts nothing until a configure() call works.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\n if (runtime) {\n return runtime;\n }\n\n // Make the unconfigured runtime, so a log call before configure() doesn't throw.\n return ObservabilityRuntime.configure({}, true);\n}\n\n/**\n * Initializes or reconfigures the observability runtime. The first call that works starts the\n * runtime. Before it, the library patches, stores and sends nothing, and the records logged\n * before it go out with its hooks and identity. With `enabled: false`, the start waits for the\n * first `enabled: true`.\n * With `payloadMode: \"defer\"`, logger records are built in idle time. With the debug buffer on,\n * they are still built at the call.\n * @param config Consumer configuration options.\n */\nexport function configure(config: Partial<ObservabilityConfig>): void {\n ObservabilityRuntime.configure(config);\n trimLoggerCache();\n}\n\n/**\n * Locks or unlocks the configuration. The lock isn't access control against other code on\n * this origin. Call it after configure(), because a lock before the first configure() refuses\n * that call too, and the runtime then never starts.\n * @param locked True to refuse changes through configure().\n */\nexport function setConfigurationLocked(locked: boolean): void {\n requireRuntime().setConfigurationLocked(locked);\n}\n\n/**\n * Stops delivery for the old context and starts it for the new one. A call during another\n * rotation runs after it.\n * @param update New identity, routing settings and context attributes.\n * @param options What to do with old records, and the flush deadline.\n * @returns Promise that resolves once the change is complete. It rejects before the first\n * configure() call that works, while a failed first call still refuses records, and after\n * shutdown().\n */\nexport function rotateSecurityContext(\n update: SecurityContextUpdate,\n options?: SecurityContextRotationOptions,\n): Promise<void> {\n return requireRuntime().rotateSecurityContext(update, options);\n}\n\n/**\n * Reads this SDK copy's runtime state, policies and delivery state. The `delivery` block holds\n * the record and batch counts, the send and failure times, the throttle end and the losses. It\n * doesn't wait for startup or for the delivery stack to load.\n * @returns Promise that resolves to the current state.\n */\nexport async function getHealth(): Promise<ObservabilityHealth> {\n const runtime = requireRuntime();\n trimLoggerCache();\n return {\n ...(await runtime.health()),\n loggerCache: { ...runtime.config.loggerCache, size: loggers.size },\n };\n}\n\n/**\n * Collects the library's state for a support ticket. The bundle holds the health, the\n * diagnostic counters, the resource, the breadcrumbs, the debug buffer and a config summary.\n * The summary has no headers and no URL query, and a plugin or custom serializer shows up by\n * name only. The breadcrumbs go through the privacy hooks. A debug buffer record keeps its\n * context attributes. Where the bundle gets sent is up to the app.\n * @returns Promise that resolves to a JSON-safe bundle.\n */\nexport async function collectDebugBundle(): Promise<DebugBundle> {\n const health = await getHealth();\n return requireRuntime().debugBundle(health);\n}\n\n/**\n * Removes the least recently used loggers until the cache is within its limit.\n * @returns Cache limit, or null for no limit.\n */\nfunction trimLoggerCache(): number | null {\n const limit = (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.config\n .loggerCache.maxEntries;\n const max = limit === undefined ? 256 : limit;\n if (max !== null) {\n // A Map keeps insertion order, so the first keys are the least recently used loggers.\n for (const key of loggers.keys()) {\n if (loggers.size <= max) {\n break;\n }\n loggers.delete(key);\n }\n }\n return max;\n}\n\n/**\n * Returns the cached logger for a namespace, or a new scoped logger.\n * @param namespace Application subsystem or module namespace.\n * @param options Context attributes for this logger only.\n * @returns Logger for the namespace. You get a new logger if you pass options or the cache\n * is disabled.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): Logger {\n const max = trimLoggerCache();\n if (options || max === 0) {\n return new OneLogger(requireRuntime, namespace, options);\n }\n\n let logger = loggers.get(namespace);\n\n logger ??= new OneLogger(requireRuntime, namespace);\n\n // Move a cached logger to the end, so the first entry is always the least recently used.\n loggers.delete(namespace);\n loggers.set(namespace, logger);\n trimLoggerCache();\n\n return logger;\n}\n\n/**\n * Returns the default root logger.\n * @returns The logger for the \"app\" namespace.\n */\nfunction root(): Logger {\n return getLogger(\"app\");\n}\n\n/**\n * Logs a trace-level debug record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function trace(message: string, payload?: Record<string, unknown>): void {\n root().trace(message, payload);\n}\n\n/**\n * Logs a debug-level record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function debug(message: string, payload?: Record<string, unknown>): void {\n root().debug(message, payload);\n}\n\n/**\n * Logs an informational record.\n * @param message Informational message.\n * @param payload Optional context attributes.\n */\nexport function info(message: string, payload?: Record<string, unknown>): void {\n root().info(message, payload);\n}\n\n/**\n * Logs a warning record.\n * @param message Warning message.\n * @param payload Optional context attributes.\n */\nexport function warn(message: string, payload?: Record<string, unknown>): void {\n root().warn(message, payload);\n}\n\n/**\n * Logs an error record, with the error that caused it and the breadcrumbs.\n * @param message Error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function error(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().error(message, err, payload);\n}\n\n/**\n * Logs a fatal record, with the error that caused it and the breadcrumbs.\n * @param message Fatal error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(message, err, payload);\n}\n\n/**\n * Logs a single user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\nexport function logAction(name: string, payload?: Record<string, unknown>): void {\n root().logAction(name, payload);\n}\n\n/**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\nexport function logEvent(name: string, payload?: Record<string, unknown>): void {\n root().logEvent(name, payload);\n}\n\n/**\n * Reports instrument options the library couldn't read. Without a runtime there is nowhere to\n * report to, so it does nothing.\n * @param error What reading the options threw.\n */\nfunction optionsFault(error: unknown): void {\n ObservabilityRuntime.current()?.diagnostics.report(\n \"config.invalid\",\n INSTRUMENT_OPTIONS_FAULT,\n undefined,\n error,\n );\n}\n\n/**\n * Returns a counter. Values are summed in memory, and every interval the library sends one\n * point per attribute set. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The counter.\n */\nexport function counter(name: string, options: InstrumentOptions = {}): Counter {\n return makeCounter(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Returns a gauge. It keeps the last value for each attribute set in memory, and every interval\n * the library sends that value as one point. With `metricsEndpoint`, the point is an OTLP gauge.\n * A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The gauge.\n */\nexport function gauge(name: string, options: InstrumentOptions = {}): Gauge {\n return makeGauge(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Returns a histogram. Values are counted into buckets in memory, and every interval the\n * library sends one point per attribute set. A handle stays valid across configure() and\n * shutdown().\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @returns The histogram.\n */\nexport function histogram(name: string, options: HistogramOptions = {}): Histogram {\n return makeHistogram(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Times an operation with named phases. Every phase and the total go into duration histograms.\n * With `tracesEndpoint` set, the operation is also a span with one child span per phase.\n * @param name Operation name. Every name creates one series.\n * @param attributes Attribute set for every histogram point. Keep it small.\n * @returns The operation's handle.\n */\nexport function startMeasure(name: string, attributes?: MetricAttributes): Measure {\n return requireRuntime().startMeasure(name, attributes);\n}\n\n/**\n * Times a function call with a measure, as `startMeasure()` does. If the result has a `then`\n * function, the measure ends when it settles. A throw or a rejection ends it with the outcome\n * \"error\", and the error goes to the caller unchanged.\n * @param name Operation name. Every name creates one series.\n * @param fn The function to call.\n * @param attributes Attribute set for every histogram point. Keep it small.\n * @returns Whatever `fn` returned, or the result of its `then` call.\n */\nexport function measure<T>(name: string, fn: () => T, attributes?: MetricAttributes): T {\n const runtime = requireRuntime();\n return measureCall(runtime.startMeasure(name, attributes), fn, runtime.diagnostics);\n}\n\n/**\n * Starts the session replay recorder. With `replay.requireConsent` set, nothing is recorded\n * until you call this, so call it once the user agrees. Does nothing while `replay.enabled`\n * is false.\n */\nexport function startReplay(): void {\n requireRuntime().setReplay(true);\n}\n\n/**\n * Stops the session replay recorder and drops any replay events that haven't been sent. With\n * `replay.requireConsent` set, the recorder stays off until the next `startReplay()`.\n */\nexport function stopReplay(): void {\n requireRuntime().setReplay(false);\n}\n\n/**\n * Times spans of app code with probes. A probe is a named handle with `begin()`, `end()`,\n * `endAfterPaint()` and `record()`, and `time()` times a single function call. Once per\n * interval the library sends one `ui.profile.duration` histogram for every probe that has data.\n *\n * The profiler is off by default. Set `profiler.enabled` to true to turn it on. While it is\n * off, probes don't read the clock. After `shutdown()` a probe does nothing until a later\n * `configure()` turns the profiler back on. Probes stay valid across `configure()` and\n * `shutdown()`, and you can create them before `configure()`. No call ever throws.\n * @example\n * const render = profiler.probe(\"grid.render\");\n * const token = render.begin();\n * drawGrid();\n * render.end(token);\n */\nexport const profiler: Profiler = {\n // Probe calls report to whichever runtime is current. Once shutdown() resolves, the stopped\n // runtime gets nothing.\n probe: (name, options) =>\n profilerCore().probe(name, options, ObservabilityRuntime.current()?.diagnostics),\n time: (name, fn) => profilerCore().time(name, fn, ObservabilityRuntime.current()?.diagnostics),\n};\n\n/**\n * Adds a breadcrumb to the trail. The next error record carries the trail.\n * @param message Description of the event.\n * @param data Optional metadata. It is copied right away.\n */\nexport function addBreadcrumb(message: string, data?: Record<string, unknown>): void {\n requireRuntime().addBreadcrumb(message, data);\n}\n\n/**\n * Merges attributes into the ambient context. Every later record includes them. A null value\n * removes its key, and an undefined value keeps the current value. A value that isn't an object\n * reports `config.invalid` and changes nothing.\n * @param values Attributes to merge.\n */\nexport function setContext(values: Record<string, unknown>): void {\n const runtime = requireRuntime();\n // A string would give one attribute for each character.\n if (!isObject(values)) {\n runtime.diagnostics.report(\n \"config.invalid\",\n \"setContext() takes an object. The library keeps the current context.\",\n );\n return;\n }\n\n // A getter or a Proxy trap on the app's object can throw, and the call must not.\n runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the values of setContext().\",\n () => {\n runtime.context.merge(values);\n },\n );\n}\n\n/**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to delete.\n */\nexport function removeContext(key: string): void {\n requireRuntime().context.remove(key);\n}\n\n/**\n * Starts a new journey correlation context.\n * @param name Journey workflow identifier.\n * @param options `parent` links the active journey as the parent. `id` sets the journey id, a\n * string of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". Without it, the library generates one.\n * @returns The started Journey.\n */\nexport function startJourney(name: string, options?: { parent?: boolean; id?: string }): Journey {\n return requireRuntime().journey.start(name, options);\n}\n\n/** Ends the active journey correlation context. */\nexport function endJourney(): void {\n requireRuntime().journey.end();\n}\n\n/**\n * Returns the active journey, or null if none is in progress.\n * @returns The active Journey, or null.\n */\nexport function currentJourney(): Journey | null {\n return requireRuntime().journey.current();\n}\n\n/**\n * Serializes the active journey's metadata into a URL token that another context can adopt.\n * @returns The token, or null if no journey is active or the token is above the size limit.\n */\nexport function getJourneyToken(): string | null {\n return requireRuntime().journey.getToken();\n}\n\n/**\n * Adopts a serialized journey token in this application realm.\n * @param token Serialized journey token.\n * @returns True if the token is valid and the runtime adopted it.\n */\nexport function adoptJourney(token: string): boolean {\n return requireRuntime().journey.adopt(token, \"manual\", true);\n}\n\n/**\n * Connects a Web Worker or MessagePort to the document bus, so its records get routed.\n * @param worker The Worker or MessagePort to connect.\n * @param options The worker's permissions. Defaults to \"records\".\n * @returns Function that removes this registration.\n */\nexport function registerWorker(worker: WorkerLike, options?: SourceOptions): () => void {\n return requireRuntime().registerWorker(worker, options);\n}\n\n/**\n * Registers one frame or window at an exact origin.\n * @param frame Child frame or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\nexport function registerFrame(\n frame: HTMLIFrameElement | Window,\n options: FrameOptions,\n): () => void {\n return requireRuntime().registerFrame(frame, options);\n}\n\n/** Starts a new distributed trace. Later records and requests carry the new trace id. */\nexport function newTrace(): void {\n requireRuntime().tracing.rotate(\"explicit\");\n}\n\n/**\n * Returns the W3C traceparent headers to put on an outgoing HTTP request.\n * @returns Map of trace header names to values.\n */\nexport function getTraceHeaders(): Record<string, string> {\n return requireRuntime().tracing.headers();\n}\n\n/**\n * Builds any deferred calls and the open metric interval, sends the records in memory, and\n * waits until each one has a final state or the time limit passes. The snapshot is the records\n * in memory at the call. A record logged later isn't in it. Before startup ends, the call waits\n * for startup and the delivery stack first, and the snapshot then also holds the records logged\n * during that wait. A forwarder hands its records to its sender and asks the sender to flush.\n * At the limit the call returns, and the work goes on in the background. The stored batches\n * from earlier failures and the replay segments are outside the snapshot. Before the first\n * `configure()` call that works, during a pause and after `shutdown()`, it sends nothing and\n * returns the status \"inactive\" at once.\n * @param options How long to wait. `timeoutMs` is 0 to 600000 ms, and the default is 5000.\n * @returns Promise that resolves to the counts of the snapshot's records. It never rejects.\n */\nexport function flush(options?: FlushOptions): Promise<FlushResult> {\n return requireRuntime().flush(options);\n}\n\n/**\n * Starts a new correlation in this tab. Ends the active journey and starts a new trace. Other\n * tabs pick up the new id at their next startup. For a logout or a tenant change, use\n * rotateSecurityContext().\n */\nexport function newSession(): void {\n requireRuntime().newSession();\n}\n\n/**\n * Returns a snapshot of the cumulative diagnostic event counts.\n * @returns Map of diagnostic codes to how often each one occurred.\n */\nexport function getDiagnosticCounters(): Record<string, number> {\n return requireRuntime().diagnostics.snapshot();\n}\n\n/**\n * Stops every runtime subsystem. By default it flushes the records first, then runs the exit\n * flush, and a request still open after that is cancelled with its stored batch kept. With\n * `pending: \"discard\"` it sends nothing and reports each record in memory to `onDrop` with the\n * reason \"discarded\". `clearStorage` also removes the stored batches and the stored ids, for a\n * logout on a shared device. A call before any log call or `configure()` does nothing. A call\n * after `shutdown()` stops nothing more, but its `clearStorage` still removes the stored data,\n * once the first call ends. The next `configure()` starts a new runtime.\n * @param options What to do with the records that wait, and which storage to remove.\n * @returns Promise that resolves once shutdown is complete.\n */\nexport async function shutdown(options?: ShutdownOptions): Promise<void> {\n await (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.destroy(options);\n}\n"],"mappings":"A,otBAaA,IAAMoJ,EAAS,IAAI,QAGnB,SAASC,EAAO,EAA4B,CAC1C,IAAMC,EAAOC,EAAM,KACfD,IAAS,IAAA,KACXC,EAAM,YAAY,MAAM,mBAAoB,gDAAmD,CAC7F,mBAAmBD,CAAI,CACzB,CAAC,EACD,EAAM,KAAO,IAAA,IAGf,aAAaC,EAAM,KAAK,EACxB,EAAM,MAAQ,IAAA,EAChB,CAGA,SAASC,EAAS,EAAe,EAA4B,CACvD,OAAO,qBAAwB,YAAc,OAAO,oBAAuB,aAC7E,EAAM,KAAOD,EAAM,YAAY,MAC7B,mBACA,gDAEE,oBACG,GAAa,CACZE,EAAMC,EAAOH,EAAOI,CAAQ,CAC9B,EACA,CAAE,QAAS3J,EAAAA,CAAsB,CACnC,CACJ,EACIuJ,EAAM,OAAS,IAAA,MAKrB,EAAM,MAAQ,eAAiB,CAC7BE,EAAMC,EAAOH,CAAK,CACpB,EAAG,CAAC,EACJhB,EAAA,EAAWgB,EAAM,KAAK,EACxB,CAGA,SAASE,EAAM,EAAe,EAAsB,EAA+B,CACjF,GAAIL,EAAO,IAAIM,CAAK,IAAMH,GAASA,EAAM,SACvC,OAGFF,EAAOE,CAAK,EACZ,EAAM,SAAW,GACjB,I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