@utk09/ui-observability 1.1.0 → 1.2.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 +42 -0
- package/dist/{batch-D3NHhF9L.js → batch-120Kc9jr.js} +3 -3
- package/dist/{batch-D3NHhF9L.js.map → batch-120Kc9jr.js.map} +1 -1
- package/dist/{batch-DnYRJqhU.cjs → batch-C3uNp5kU.cjs} +2 -2
- package/dist/{batch-DnYRJqhU.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
- package/dist/bus/bus.d.cts +5 -0
- package/dist/bus/bus.d.ts +5 -0
- package/dist/bus-Dj8IEVcC.cjs +2 -0
- package/dist/bus-Dj8IEVcC.cjs.map +1 -0
- package/dist/{bus-dw7T92sO.js → bus-DyNafxZN.js} +104 -94
- package/dist/bus-DyNafxZN.js.map +1 -0
- package/dist/capture/errors.d.cts +10 -0
- package/dist/capture/errors.d.ts +10 -0
- package/dist/capture/replay.d.cts +1 -1
- package/dist/capture/replay.d.ts +1 -1
- package/dist/capture/types.d.cts +5 -0
- package/dist/capture/types.d.ts +5 -0
- package/dist/capture/web-vitals.d.cts +1 -0
- package/dist/capture/web-vitals.d.ts +1 -0
- package/dist/{compression-SHPAvS4U.js → compression-BWkDWY3v.js} +2 -2
- package/dist/{compression-SHPAvS4U.js.map → compression-BWkDWY3v.js.map} +1 -1
- package/dist/{compression-C0hUHKR-.cjs → compression-CEVe7NPX.cjs} +2 -2
- package/dist/{compression-C0hUHKR-.cjs.map → compression-CEVe7NPX.cjs.map} +1 -1
- package/dist/config-C0PtemvC.cjs +2 -0
- package/dist/config-C0PtemvC.cjs.map +1 -0
- package/dist/{config-CSNcS7OZ.js → config-DK1Zf7jn.js} +83 -85
- package/dist/config-DK1Zf7jn.js.map +1 -0
- package/dist/{console-BsM-fSCQ.js → console-CAyCQOpm.js} +5 -5
- package/dist/{console-BsM-fSCQ.js.map → console-CAyCQOpm.js.map} +1 -1
- package/dist/{console-Dkxs6IVQ.cjs → console-Dk6GH4yj.cjs} +2 -2
- package/dist/{console-Dkxs6IVQ.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
- package/dist/{constants-BwJDXzj6.js → constants-CEHN6KuY.js} +42 -21
- package/dist/constants-CEHN6KuY.js.map +1 -0
- package/dist/constants-NtiQDWL_.cjs +2 -0
- package/dist/constants-NtiQDWL_.cjs.map +1 -0
- package/dist/constants.d.cts +11 -0
- package/dist/constants.d.ts +11 -0
- package/dist/core/config.d.cts +9 -3
- package/dist/core/config.d.ts +9 -3
- package/dist/core/diagnostics.d.cts +1 -1
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/pipeline.d.cts +11 -0
- package/dist/core/pipeline.d.ts +11 -0
- package/dist/core/record.d.cts +2 -2
- package/dist/core/record.d.ts +2 -2
- package/dist/core/sender.d.cts +3 -2
- package/dist/core/sender.d.ts +3 -2
- package/dist/{debug-bundle-B2v6Cym-.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
- package/dist/{debug-bundle-B2v6Cym-.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
- package/dist/{debug-bundle-Cs_YWzTa.js → debug-bundle-w78W46zr.js} +4 -4
- package/dist/{debug-bundle-Cs_YWzTa.js.map → debug-bundle-w78W46zr.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.js +22 -22
- package/dist/doctor.js.map +1 -1
- package/dist/errors-07pmZ7VY.cjs +3 -0
- package/dist/errors-07pmZ7VY.cjs.map +1 -0
- package/dist/{errors-Q3Ng1ciC.js → errors-C-LYbqyB.js} +27 -24
- package/dist/errors-C-LYbqyB.js.map +1 -0
- package/dist/{factory-DV17sm2p.js → factory-BHYrcSaU.js} +42 -31
- package/dist/factory-BHYrcSaU.js.map +1 -0
- package/dist/factory-DsaNdcXp.cjs +2 -0
- package/dist/factory-DsaNdcXp.cjs.map +1 -0
- package/dist/{identity-BgtHyY4u.js → identity-Byh3gCdT.js} +11 -11
- package/dist/{identity-BgtHyY4u.js.map → identity-Byh3gCdT.js.map} +1 -1
- package/dist/{identity-CvuyqZk7.cjs → identity-BzAzdQyv.cjs} +2 -2
- package/dist/{identity-CvuyqZk7.cjs.map → identity-BzAzdQyv.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +539 -534
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-e-13ZLWm.js → indexeddb-storage-BYywz-v6.js} +4 -4
- package/dist/{indexeddb-storage-e-13ZLWm.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
- package/dist/{indexeddb-storage-D4KVcqdD.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
- package/dist/{indexeddb-storage-D4KVcqdD.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
- package/dist/{interactions-OK85T-Dk.cjs → interactions-BXzEel4F.cjs} +2 -2
- package/dist/interactions-BXzEel4F.cjs.map +1 -0
- package/dist/{interactions-Byxf1C82.js → interactions-DdKPMWIN.js} +12 -12
- package/dist/interactions-DdKPMWIN.js.map +1 -0
- package/dist/{journey-nMbob3OB.cjs → journey-BUmsrgaw.cjs} +2 -2
- package/dist/{journey-nMbob3OB.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
- package/dist/{journey-C93FTYcs.js → journey-Nu655gEO.js} +3 -3
- package/dist/{journey-C93FTYcs.js.map → journey-Nu655gEO.js.map} +1 -1
- package/dist/{library-console-DJUQzcgM.cjs → library-console-DdIlzzph.cjs} +2 -2
- package/dist/{library-console-DJUQzcgM.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
- package/dist/{library-console-DklSmucS.js → library-console-amePMnP8.js} +2 -2
- package/dist/{library-console-DklSmucS.js.map → library-console-amePMnP8.js.map} +1 -1
- package/dist/{library-request-UGEwOHpf.js → library-request-Cv7C05jf.js} +2 -2
- package/dist/{library-request-UGEwOHpf.js.map → library-request-Cv7C05jf.js.map} +1 -1
- package/dist/{library-request-kY9iTpIF.cjs → library-request-DO3Ec7KE.cjs} +2 -2
- package/dist/{library-request-kY9iTpIF.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
- package/dist/{lifecycle-DaMdH_X7.cjs → lifecycle-B5yfH5is.cjs} +2 -2
- package/dist/{lifecycle-DaMdH_X7.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
- package/dist/{lifecycle-B2PlIuQu.js → lifecycle-CMHz2Zbs.js} +2 -2
- package/dist/{lifecycle-B2PlIuQu.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
- package/dist/{log-record-DSt2P-Sr.js → log-record-B_nSqxoe.js} +2 -2
- package/dist/{log-record-DSt2P-Sr.js.map → log-record-B_nSqxoe.js.map} +1 -1
- package/dist/{log-record-Bmx6etMh.cjs → log-record-Bdywwg0k.cjs} +2 -2
- package/dist/{log-record-Bmx6etMh.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
- package/dist/{long-frames-Bamjs1WV.js → long-frames-6NGl1-uN.js} +3 -3
- package/dist/{long-frames-Bamjs1WV.js.map → long-frames-6NGl1-uN.js.map} +1 -1
- package/dist/{long-frames-lhtONgGt.cjs → long-frames-D9DfSWqv.cjs} +2 -2
- package/dist/{long-frames-lhtONgGt.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
- package/dist/models/config.d.cts +4 -3
- package/dist/models/config.d.ts +4 -3
- package/dist/{network-BCn8Gn47.cjs → network-BNHBI0Fc.cjs} +2 -2
- package/dist/{network-BCn8Gn47.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
- package/dist/{network-Cg1L2w2r.js → network-Cc3tSB7e.js} +13 -13
- package/dist/{network-Cg1L2w2r.js.map → network-Cc3tSB7e.js.map} +1 -1
- package/dist/{observed-windows-BrwaJNlj.js → observed-windows-8JtCsIr1.js} +3 -3
- package/dist/{observed-windows-BrwaJNlj.js.map → observed-windows-8JtCsIr1.js.map} +1 -1
- package/dist/{observed-windows-B3gJkdql.cjs → observed-windows-BlE25nrn.cjs} +2 -2
- package/dist/{observed-windows-B3gJkdql.cjs.map → observed-windows-BlE25nrn.cjs.map} +1 -1
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{otlp-D6dRZyB8.js → otlp-Btix3EBa.js} +7 -7
- package/dist/{otlp-D6dRZyB8.js.map → otlp-Btix3EBa.js.map} +1 -1
- package/dist/{otlp-CrAWkQdO.cjs → otlp-CFSW-Dno.cjs} +2 -2
- package/dist/{otlp-CrAWkQdO.cjs.map → otlp-CFSW-Dno.cjs.map} +1 -1
- package/dist/patch-DlcKzIi-.cjs +2 -0
- package/dist/patch-DlcKzIi-.cjs.map +1 -0
- package/dist/patch-Sr1wKg7W.js +9 -0
- package/dist/patch-Sr1wKg7W.js.map +1 -0
- package/dist/platform-BZjp9wp1.cjs +2 -0
- package/dist/platform-BZjp9wp1.cjs.map +1 -0
- package/dist/{platform-8DLhjddo.js → platform-Dba6R3Hp.js} +22 -9
- package/dist/platform-Dba6R3Hp.js.map +1 -0
- package/dist/{profiler-BaXSqCfz.js → profiler-DNKcqu09.js} +19 -19
- package/dist/{profiler-BaXSqCfz.js.map → profiler-DNKcqu09.js.map} +1 -1
- package/dist/{profiler-BvWW2kNM.cjs → profiler-DpoPi1hH.cjs} +2 -2
- package/dist/{profiler-BvWW2kNM.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
- package/dist/{profiler-frames-DeaBiB-5.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
- package/dist/{profiler-frames-DeaBiB-5.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
- package/dist/{profiler-frames-C4ySHN0X.js → profiler-frames-CGXZeZ_3.js} +4 -4
- package/dist/{profiler-frames-C4ySHN0X.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
- package/dist/{remote-rules-Dq9xe7Qn.js → remote-rules-DNK96vLa.js} +15 -15
- package/dist/{remote-rules-Dq9xe7Qn.js.map → remote-rules-DNK96vLa.js.map} +1 -1
- package/dist/{remote-rules-D7L6D_D2.cjs → remote-rules-DuMFRlit.cjs} +2 -2
- package/dist/{remote-rules-D7L6D_D2.cjs.map → remote-rules-DuMFRlit.cjs.map} +1 -1
- package/dist/replay-Cab-lSit.cjs +2 -0
- package/dist/replay-Cab-lSit.cjs.map +1 -0
- package/dist/{replay-B0M8kWz_.js → replay-Dy6OiaOZ.js} +89 -62
- package/dist/replay-Dy6OiaOZ.js.map +1 -0
- package/dist/{reports-ojuMKGO7.cjs → reports-CGK9YQch.cjs} +2 -2
- package/dist/{reports-ojuMKGO7.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
- package/dist/{reports--8APRLa-.js → reports-CX57-S9s.js} +3 -3
- package/dist/{reports--8APRLa-.js.map → reports-CX57-S9s.js.map} +1 -1
- package/dist/{resource-timing-BzR05rE-.js → resource-timing-CWVDCbrY.js} +4 -4
- package/dist/{resource-timing-BzR05rE-.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
- package/dist/{resource-timing-pAG3ZhB5.cjs → resource-timing-DalulXiR.cjs} +2 -2
- package/dist/{resource-timing-pAG3ZhB5.cjs.map → resource-timing-DalulXiR.cjs.map} +1 -1
- package/dist/response-body-Cpz5__4g.cjs +3 -0
- package/dist/response-body-Cpz5__4g.cjs.map +1 -0
- package/dist/{response-body-BWvwKQ2p.js → response-body-yi92Rpvo.js} +100 -100
- package/dist/response-body-yi92Rpvo.js.map +1 -0
- package/dist/{rotation-BylN1B9e.js → rotation-ChBbNDE2.js} +24 -24
- package/dist/rotation-ChBbNDE2.js.map +1 -0
- package/dist/rotation-fTnNJcfH.cjs +2 -0
- package/dist/rotation-fTnNJcfH.cjs.map +1 -0
- package/dist/{sampling-zXA6r-Nw.js → sampling-DZTOD28D.js} +6 -6
- package/dist/{sampling-zXA6r-Nw.js.map → sampling-DZTOD28D.js.map} +1 -1
- package/dist/{sampling-B46LW0cy.cjs → sampling-wAVJIZXp.cjs} +2 -2
- package/dist/{sampling-B46LW0cy.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
- package/dist/{sanitize-DjnR6RXR.js → sanitize-B2GKlSFp.js} +2 -2
- package/dist/{sanitize-DjnR6RXR.js.map → sanitize-B2GKlSFp.js.map} +1 -1
- package/dist/{sanitize-Qj6LuZqp.cjs → sanitize-BZdhoghq.cjs} +2 -2
- package/dist/{sanitize-Qj6LuZqp.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
- package/dist/{sender-Bdp-TAS4.js → sender-BRSpc7R8.js} +175 -161
- package/dist/sender-BRSpc7R8.js.map +1 -0
- package/dist/sender-CFu98DAB.cjs +2 -0
- package/dist/sender-CFu98DAB.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.cts +3 -1
- package/dist/storage/emergency-queue.d.ts +3 -1
- package/dist/storage/stored-context.d.cts +3 -2
- package/dist/storage/stored-context.d.ts +3 -2
- package/dist/stored-context-CPLlzgpm.cjs +2 -0
- package/dist/stored-context-CPLlzgpm.cjs.map +1 -0
- package/dist/{stored-context-CSttrAsw.js → stored-context-df1dEnht.js} +10 -8
- package/dist/stored-context-df1dEnht.js.map +1 -0
- package/dist/{storm-DKlpv0FL.js → storm-U3_ek1nA.js} +2 -2
- package/dist/{storm-DKlpv0FL.js.map → storm-U3_ek1nA.js.map} +1 -1
- package/dist/{storm-BHgI12iS.cjs → storm-qiE_AMC7.cjs} +2 -2
- package/dist/{storm-BHgI12iS.cjs.map → storm-qiE_AMC7.cjs.map} +1 -1
- package/dist/transport/exit-flush.d.cts +23 -0
- package/dist/transport/exit-flush.d.ts +23 -0
- package/dist/transport/http-transport.d.cts +3 -2
- package/dist/transport/http-transport.d.ts +3 -2
- package/dist/transport/retry-engine.d.cts +11 -3
- package/dist/transport/retry-engine.d.ts +11 -3
- package/dist/types-BAerHgCq.js.map +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-BcOB8A2e.js → unclean-exit-Bj6gYHeL.js} +2 -2
- package/dist/{unclean-exit-BcOB8A2e.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
- package/dist/{unclean-exit-BYPYYkQ5.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
- package/dist/{unclean-exit-BYPYYkQ5.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
- package/dist/{user-timing-BsU2wQKE.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
- package/dist/{user-timing-BsU2wQKE.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
- package/dist/{user-timing-4KIJ74Vi.js → user-timing-Duz0d-OA.js} +2 -2
- package/dist/{user-timing-4KIJ74Vi.js.map → user-timing-Duz0d-OA.js.map} +1 -1
- package/dist/utils/lock.d.cts +3 -2
- package/dist/utils/lock.d.ts +3 -2
- package/dist/utils/openfin.d.cts +18 -6
- package/dist/utils/openfin.d.ts +18 -6
- package/dist/utils/patch.d.cts +1 -1
- package/dist/utils/patch.d.ts +1 -1
- package/dist/utils/platform.d.cts +6 -0
- package/dist/utils/platform.d.ts +6 -0
- package/dist/{web-socket-Zg0hj1LB.js → web-socket-CE_9Q22z.js} +5 -5
- package/dist/{web-socket-Zg0hj1LB.js.map → web-socket-CE_9Q22z.js.map} +1 -1
- package/dist/{web-socket-Cs1ZbmmN.cjs → web-socket-sm3rD-A_.cjs} +2 -2
- package/dist/{web-socket-Cs1ZbmmN.cjs.map → web-socket-sm3rD-A_.cjs.map} +1 -1
- package/dist/{web-vitals-4pWACwaR.js → web-vitals-CGwXGF-M.js} +4 -4
- package/dist/web-vitals-CGwXGF-M.js.map +1 -0
- package/dist/web-vitals-Df4Wsfx9.cjs +2 -0
- package/dist/web-vitals-Df4Wsfx9.cjs.map +1 -0
- package/dist/{worker-protocol-DFYXIFus.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
- package/dist/{worker-protocol-DFYXIFus.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
- package/dist/{worker-protocol-CYpAbrVl.js → worker-protocol-h4-tRWqy.js} +6 -6
- package/dist/{worker-protocol-CYpAbrVl.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
- package/dist/{worker-server--yGTadTA.cjs → worker-server-CF1yatXq.cjs} +2 -2
- package/dist/{worker-server--yGTadTA.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
- package/dist/worker-server-FYfKHQhJ.js +94 -0
- package/dist/{worker-server-BokySIII.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
- package/dist/{worker-transport-BdEvh_-a.cjs → worker-transport-COgY4RX8.cjs} +2 -2
- package/dist/{worker-transport-BdEvh_-a.cjs.map → worker-transport-COgY4RX8.cjs.map} +1 -1
- package/dist/{worker-transport-JK-Fby9J.js → worker-transport-jzX1IusG.js} +34 -34
- package/dist/{worker-transport-JK-Fby9J.js.map → worker-transport-jzX1IusG.js.map} +1 -1
- package/llms.txt +1 -2
- package/package.json +1 -1
- package/dist/bus-B__467mL.cjs +0 -2
- package/dist/bus-B__467mL.cjs.map +0 -1
- package/dist/bus-dw7T92sO.js.map +0 -1
- package/dist/config-CSNcS7OZ.js.map +0 -1
- package/dist/config-CybPP5VM.cjs +0 -2
- package/dist/config-CybPP5VM.cjs.map +0 -1
- package/dist/constants-BwJDXzj6.js.map +0 -1
- package/dist/constants-CtF52hIV.cjs +0 -2
- package/dist/constants-CtF52hIV.cjs.map +0 -1
- package/dist/errors-DP2RUm4V.cjs +0 -3
- package/dist/errors-DP2RUm4V.cjs.map +0 -1
- package/dist/errors-Q3Ng1ciC.js.map +0 -1
- package/dist/factory-DV17sm2p.js.map +0 -1
- package/dist/factory-K8O6gpux.cjs +0 -2
- package/dist/factory-K8O6gpux.cjs.map +0 -1
- package/dist/interactions-Byxf1C82.js.map +0 -1
- package/dist/interactions-OK85T-Dk.cjs.map +0 -1
- package/dist/patch-BX8KrPCT.cjs +0 -2
- package/dist/patch-BX8KrPCT.cjs.map +0 -1
- package/dist/patch-UdPz1ea8.js +0 -8
- package/dist/patch-UdPz1ea8.js.map +0 -1
- package/dist/platform-8DLhjddo.js.map +0 -1
- package/dist/platform-BqRc-7RO.cjs +0 -2
- package/dist/platform-BqRc-7RO.cjs.map +0 -1
- package/dist/replay-B0M8kWz_.js.map +0 -1
- package/dist/replay-QOFBpAXh.cjs +0 -2
- package/dist/replay-QOFBpAXh.cjs.map +0 -1
- package/dist/response-body-BWvwKQ2p.js.map +0 -1
- package/dist/response-body-CKEJ5itk.cjs +0 -3
- package/dist/response-body-CKEJ5itk.cjs.map +0 -1
- package/dist/rotation-BylN1B9e.js.map +0 -1
- package/dist/rotation-E2eKClIs.cjs +0 -2
- package/dist/rotation-E2eKClIs.cjs.map +0 -1
- package/dist/sender-Bdp-TAS4.js.map +0 -1
- package/dist/sender-DR7ZycZY.cjs +0 -2
- package/dist/sender-DR7ZycZY.cjs.map +0 -1
- package/dist/stored-context-BOu54M8Y.cjs +0 -2
- package/dist/stored-context-BOu54M8Y.cjs.map +0 -1
- package/dist/stored-context-CSttrAsw.js.map +0 -1
- package/dist/web-vitals-4pWACwaR.js.map +0 -1
- package/dist/web-vitals-__X7t4pj.cjs +0 -2
- package/dist/web-vitals-__X7t4pj.cjs.map +0 -1
- package/dist/worker-server-BokySIII.js +0 -94
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity-BgtHyY4u.js","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","_defineProperty","BROWSER_STORES","opener","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","openerTabId","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n /**\n * Returns the live opener's tab store, or null without one. Memory stores leave it out,\n * because they can't hold a copied tab id. A cross-origin opener throws.\n */\n opener?(): KeyValueStore | null;\n}\n\n/** The opener's fields that the copy check reads. A worker's global has no opener. */\ninterface OpenerWindow {\n closed: boolean;\n sessionStorage: KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n opener: () => {\n const { opener } = globalThis as { opener?: OpenerWindow | null };\n return opener && !opener.closed ? opener.sessionStorage : null;\n },\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Reads the tab id in the opener's session store.\n * @param stores Identity stores.\n * @returns The opener's tab id, or null without a live same-origin opener.\n */\nfunction openerTabId(stores: IdentityStores): string | null {\n try {\n return stores.opener?.()?.getItem(TAB_ID_KEY) ?? null;\n } catch {\n // A cross-origin opener blocks the read, and that's the expected answer. The fallback is\n // null, so the popup keeps its stored id.\n return null;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n // window.open copies sessionStorage, so a popup starts with its opener's tab id. After the\n // popup stores its own id the two differ, and a reload keeps it.\n if (!tabId || tabId === openerTabId(stores)) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"identity-Byh3gCdT.js","names":["SESSION_IDLE_MS","SESSION_ID_KEY","TAB_ID_KEY","_defineProperty","BROWSER_STORES","opener","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","openerTabId","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n /**\n * Returns the live opener's tab store, or null without one. Memory stores leave it out,\n * because they can't hold a copied tab id. A cross-origin opener throws.\n */\n opener?(): KeyValueStore | null;\n}\n\n/** The opener's fields that the copy check reads. A worker's global has no opener. */\ninterface OpenerWindow {\n closed: boolean;\n sessionStorage: KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n opener: () => {\n const { opener } = globalThis as { opener?: OpenerWindow | null };\n return opener && !opener.closed ? opener.sessionStorage : null;\n },\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Reads the tab id in the opener's session store.\n * @param stores Identity stores.\n * @returns The opener's tab id, or null without a live same-origin opener.\n */\nfunction openerTabId(stores: IdentityStores): string | null {\n try {\n return stores.opener?.()?.getItem(TAB_ID_KEY) ?? null;\n } catch {\n // A cross-origin opener blocks the read, and that's the expected answer. The fallback is\n // null, so the popup keeps its stored id.\n return null;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n // window.open copies sessionStorage, so a popup starts with its opener's tab id. After the\n // popup stores its own id the two differ, and a reload keeps it.\n if (!tabId || tabId === openerTabId(stores)) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=identity-
|
|
1
|
+
const e=require("./constants-NtiQDWL_.cjs"),t=require("./defineProperty-X1c4tIPD.cjs");var n={local:()=>localStorage,session:()=>sessionStorage,opener:()=>{let{opener:e}=globalThis;return e&&!e.closed?e.sessionStorage:null}};function r(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function i(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function a(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return i(16)}function o(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function s(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function c(t,n,r,i){let a=o(t,`local`,e.Un,n);if(a)try{let e=JSON.parse(a);return e.id&&(i===null||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function l(e){try{return e.opener?.()?.getItem(`ui-observability.tab`)??null}catch{return null}}function u(t,r=n,i=e.Hn){let u=a(t),d=Date.now(),f=a(t),p=c(r,t,d,i)??f,m=JSON.stringify({id:p,lastSeenAt:d});s(r,`local`,e.Un,m,t);let h=o(r,`session`,`ui-observability.tab`,t)??``;return h&&h!==l(r)||(h=a(t),s(r,`session`,e.tr,h,t)),{sessionId:p,tabId:h,contextId:u}}function d(t,n,r){s(r,`session`,e.tr,t,n)}var f=class{constructor(r,i=n,a=e.Hn){t.t(this,`diagnostics`,void 0),t.t(this,`stores`,void 0),t.t(this,`idleMs`,void 0),t.t(this,`lastTouchAt`,0),this.diagnostics=r,this.stores=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<6e4)return;let n=c(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return c(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});s(this.stores,`local`,e.Un,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
+
//# sourceMappingURL=identity-BzAzdQyv.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity-CvuyqZk7.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","require_constants","require_defineProperty","BROWSER_STORES","opener","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","openerTabId","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n /**\n * Returns the live opener's tab store, or null without one. Memory stores leave it out,\n * because they can't hold a copied tab id. A cross-origin opener throws.\n */\n opener?(): KeyValueStore | null;\n}\n\n/** The opener's fields that the copy check reads. A worker's global has no opener. */\ninterface OpenerWindow {\n closed: boolean;\n sessionStorage: KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n opener: () => {\n const { opener } = globalThis as { opener?: OpenerWindow | null };\n return opener && !opener.closed ? opener.sessionStorage : null;\n },\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Reads the tab id in the opener's session store.\n * @param stores Identity stores.\n * @returns The opener's tab id, or null without a live same-origin opener.\n */\nfunction openerTabId(stores: IdentityStores): string | null {\n try {\n return stores.opener?.()?.getItem(TAB_ID_KEY) ?? null;\n } catch {\n // A cross-origin opener blocks the read, and that's the expected answer. The fallback is\n // null, so the popup keeps its stored id.\n return null;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n // window.open copies sessionStorage, so a popup starts with its opener's tab id. After the\n // popup stores its own id the two differ, and a reload keeps it.\n if (!tabId || tabId === openerTabId(stores)) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"A,uFAmEA,IAAaK,EAAiC,CAC5C,UAAa,aACb,YAAe,eACf,WAAc,CACZ,GAAM,CAAE,UAAW,WACnB,OAAOC,GAAU,CAACA,EAAO,OAASA,EAAO,eAAiB,IAC5D,CACF,EAMA,SAAgBC,GAA+B,CAC7C,IAAMC,EAAQ,IAA6C,CACzD,QAAU,GAAQC,EAAI,IAAIC,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvBD,EAAI,IAAIC,EAAKC,CAAK,CACpB,EACA,WAAa,GAAQ,CACnBF,EAAI,OAAOC,CAAG,CAChB,CACF,GAEME,EAAaJ,EAAK,IAAI,GAAK,EAC3BK,EAAeL,EAAK,IAAI,GAAK,EAEnC,MAAO,CAAE,UAAaI,EAAY,YAAeC,CAAa,CAChE,CAQA,SAAgBC,EAAU,EAA4B,CACpD,IAAMC,EAAQ,IAAI,WAAWC,CAAU,EACvC,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,iBAAoB,WACrE,OAAO,gBAAgBD,CAAK,OAE5B,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAY,IAC9B,EAAMC,GAAK,KAAK,MAAM,KAAK,OAAO,EAAA,GAAoB,EAG1D,OAAO,MAAM,KAAKF,EAAQ,GAAMG,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAC1E,CAOA,SAAgBC,EAAM,EAAkC,CACtD,GAAI,CACF,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,CAE7B,MAAQ,CAGNC,EAAY,MAAM,sBAAsB,CAC1C,CACA,OAAON,EAAA,EAAwB,CACjC,CAUA,SAASO,EACP,EACA,EACA,EACA,EACe,CACf,OACED,EAAY,MAAM,sBAAuB,8BAA8BE,EAAM,cAC3EC,EAAOD,EAAM,CAAC,CAAC,CAAC,QAAQZ,CAAG,CAC7B,GAAK,IAET,CAWA,SAASc,EACP,EACA,EACA,EACA,EACA,EACM,CACNJ,EAAY,MACV,sBACA,kCAAkCE,EAAM,cAClC,CACJC,EAAOD,EAAM,CAAC,CAAC,CAAC,QAAQZ,EAAKC,CAAK,CACpC,CACF,CACF,CAUA,SAASc,EACP,EACA,EACA,EACA,EACoB,CACpB,IAAMC,EAAML,EAASE,EAAQ,QAASvB,EAAAA,GAAgBoB,CAAW,EACjE,GAAKM,EAIL,GAAI,CACF,IAAMC,EAAS,KAAK,MAAMD,CAAG,EAC7B,OAAOC,EAAO,KAAOC,IAAW,MAAQC,GAAOF,EAAO,YAAc,GAAKC,GACrED,EAAO,GACP,IAAA,EACN,MAAQ,CACNP,EAAY,OACV,mBACA,yEACF,EACA,MACF,CACF,CAOA,SAASU,EAAY,EAAuC,CAC1D,GAAI,CACF,OAAOP,EAAO,SAAS,CAAC,EAAE,QAAA,sBAAkB,GAAK,IACnD,MAAQ,CAGN,OAAO,IACT,CACF,CAQA,SAAgBQ,EACd,EACA,EAAyB1B,EACzB,EAAwBJ,EAAAA,GACd,CACV,IAAM+B,EAAYb,EAAMC,CAAW,EAC7BS,EAAM,KAAK,IAAI,EAEfI,EAASd,EAAMC,CAAW,EAC1Bc,EAAYT,EAAYF,EAAQH,EAAaS,EAAKD,CAAM,GAAKK,EAC7DE,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYL,CAAI,CAAC,EACjEL,EAAUD,EAAQ,QAASvB,EAAAA,GAAgBmC,EAASf,CAAW,EAE/D,IAAIgB,EAAQf,EAASE,EAAQ,UAAA,uBAAuBH,CAAW,GAAK,GAQpE,OALKgB,GAASA,IAAUN,EAAYP,CAAM,IACxC,EAAQJ,EAAMC,CAAW,EACzBI,EAAUD,EAAQ,UAAWrB,EAAAA,GAAYkC,EAAOhB,CAAW,GAGtD,CAAE,YAAW,QAAO,WAAU,CACvC,CAQA,SAAgBiB,EACd,EACA,EACA,EACM,CACNb,EAAUD,EAAQ,UAAWrB,EAAAA,GAAYkC,EAAOhB,CAAW,CAC7D,CAOA,IAAakB,EAAb,KAA0B,CAQxB,YACE,EACA,EAA0CjC,EAC1C,EAAyCJ,EAAAA,GACzC,CAHQG,EAAA,EAAA,KAAA,cAAA,IAAA,EAAA,EACSA,EAAA,EAAA,KAAA,SAAA,IAAA,EAAA,EACAA,EAAA,EAAA,KAAA,SAAA,IAAA,EAAA,EATnBA,EAAA,EAAA,KAAA,cAAsB,CAAA,EAOZ,KAAA,YAAAgB,EACS,KAAA,OAAAG,EACA,KAAA,OAAAK,CAChB,CAMH,MAAM,EAAyB,CAC7B,IAAMC,EAAM,KAAK,IAAI,EAErB,GAAIA,EAAM,KAAK,YAAA,IACb,OAKF,IAAMU,EAASd,EAAY,KAAK,OAAQ,KAAK,YAAaI,EAAK,KAAK,MAAM,EACtEU,IAAW,IAAA,IAAaA,IAAWL,EACrC,KAAK,YAAcL,EAIrB,KAAK,MAAMK,EAAWL,CAAG,CAC3B,CAMA,QAA6B,CAC3B,OAAOJ,EAAY,KAAK,OAAQ,KAAK,YAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAC3E,CAMA,QAAQ,EAAyB,CAC/B,KAAK,MAAMS,EAAW,KAAK,IAAI,CAAC,CAClC,CAOA,MAAc,EAAmB,EAAmB,CAClD,KAAK,YAAcL,EACnB,IAAMM,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYL,CAAI,CAAC,EACjEL,EAAU,KAAK,OAAQ,QAASxB,EAAAA,GAAgBmC,EAAS,KAAK,WAAW,CAC3E,CACF,E"}
|
|
1
|
+
{"version":3,"file":"identity-BzAzdQyv.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","require_constants","require_defineProperty","BROWSER_STORES","opener","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","openerTabId","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n /**\n * Returns the live opener's tab store, or null without one. Memory stores leave it out,\n * because they can't hold a copied tab id. A cross-origin opener throws.\n */\n opener?(): KeyValueStore | null;\n}\n\n/** The opener's fields that the copy check reads. A worker's global has no opener. */\ninterface OpenerWindow {\n closed: boolean;\n sessionStorage: KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n opener: () => {\n const { opener } = globalThis as { opener?: OpenerWindow | null };\n return opener && !opener.closed ? opener.sessionStorage : null;\n },\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Reads the tab id in the opener's session store.\n * @param stores Identity stores.\n * @returns The opener's tab id, or null without a live same-origin opener.\n */\nfunction openerTabId(stores: IdentityStores): string | null {\n try {\n return stores.opener?.()?.getItem(TAB_ID_KEY) ?? null;\n } catch {\n // A cross-origin opener blocks the read, and that's the expected answer. The fallback is\n // null, so the popup keeps its stored id.\n return null;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n // window.open copies sessionStorage, so a popup starts with its opener's tab id. After the\n // popup stores its own id the two differ, and a reload keeps it.\n if (!tabId || tabId === openerTabId(stores)) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"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"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-CtF52hIV.cjs"),t=require("./log-record-Bmx6etMh.cjs"),n=require("./error-like-gGRx2s36.cjs"),r=require("./guards-EjG3ahFp.cjs"),i=require("./unref-CU9Nyz_9.cjs"),a=require("./platform-BqRc-7RO.cjs"),o=require("./defineProperty-X1c4tIPD.cjs"),s=require("./identity-CvuyqZk7.cjs"),c=require("./profiler-BvWW2kNM.cjs"),l=require("./library-console-DJUQzcgM.cjs"),u=require("./sanitize-Qj6LuZqp.cjs"),d=require("./library-request-kY9iTpIF.cjs"),f=require("./config-CybPP5VM.cjs"),p=require("./batch-DnYRJqhU.cjs"),m=require("./journey-nMbob3OB.cjs"),h=require("./sampling-B46LW0cy.cjs"),g=require("./observed-windows-B3gJkdql.cjs");var _=new WeakMap;function v(e){let t=e.idle;t!==void 0&&(e.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be cancelled.`,()=>{cancelIdleCallback(t)}),e.idle=void 0),clearTimeout(e.timer),e.timer=void 0}function y(t,n){typeof requestIdleCallback==`function`&&typeof cancelIdleCallback==`function`&&(n.idle=n.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be scheduled.`,()=>requestIdleCallback(e=>{b(t,n,e)},{timeout:e.q})),n.idle!==void 0)||(n.timer=setTimeout(()=>{b(t,n)},0),i.t(n.timer))}function b(e,t,n){if(_.get(e)!==t||t.draining)return;v(t),t.draining=!0;let r=t.work;t.work=[];let i=0;for(;i<r.length&&(!n||n.didTimeout&&i===0||n.timeRemaining()>0);)if(t.diagnostics.guard(`pipeline.crashed`,`The library could not build a deferred record.`,r[i]),i++,_.get(e)!==t)return;t.work=[...r.slice(i),...t.work],t.draining=!1,t.work.length>0?y(e,t):_.delete(e)}function x(t,n,r,i){let a=_.get(t),o=i===null?e.J:Math.min(i,e.J);if(a&&a.work.length>=o&&!a.draining&&(b(t,a),a=_.get(t)),a){if(a.work.length>=o){r.count(`record.dropped_by_ceiling`);return}a.work.push(n)}else a={work:[n],diagnostics:r,draining:!1},_.set(t,a),y(t,a)}function S(e){let t=_.get(e);t&&b(e,t)}function C(e){let t=_.get(e);if(t){v(t),_.delete(e);for(let e of t.work)t.diagnostics.count(`record.dropped_by_ceiling`);t.work=[]}}var w=[e.P,e.Jn,e.Y];function ee(e,t){let r=t.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>{if(!(e instanceof Error)&&!n.r(e))return;let t=Error(e.message);return t.name=e.name,t.stack=e.stack,t});if(r)return r;let i=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(i??typeof e)}function te(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function ne(e,t){if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return e;if(typeof e==`object`&&e)return t.guard(`record.sanitize_failed`,`The library could not read the properties of the error reason.`,()=>{let t=e,r=n.r(e),i={},a=0;for(let e of Object.keys(t)){let o=t[e];r&&n.t.has(e)||!n.n(o)||(i[e]=o,a++)}return a===0?void 0:i})}function re(e){if(!r.n(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function ie(e){return w.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function T(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var E=class n{constructor(e,t,n={}){o.t(this,`bind`,void 0),o.t(this,`namespace`,void 0),o.t(this,`options`,void 0),o.t(this,`levelType`,void 0),o.t(this,`trace`,(e,t)=>{this.write(`TRACE`,this.levelType,e,t)}),o.t(this,`debug`,(e,t)=>{this.write(`DEBUG`,this.levelType,e,t)}),o.t(this,`info`,(e,t)=>{this.write(`INFO`,this.levelType,e,t)}),o.t(this,`warn`,(e,t)=>{this.write(`WARN`,this.levelType,e,t)}),o.t(this,`error`,(e,t,n)=>{this.writeError(`ERROR`,e,t,n)}),o.t(this,`fatal`,(e,t,n)=>{this.writeError(`FATAL`,e,t,n)}),o.t(this,`logAction`,(e,t)=>{this.write(`INFO`,`action`,e,t)}),o.t(this,`logEvent`,(e,t)=>{this.write(`INFO`,`event`,e,t)}),this.bind=e,this.namespace=t,this.options=n,this.levelType=ie(t)}child(e,t={}){return new n(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...t.scopedContext}})}write(e,t,n,r){let i=this.bind();this.submit(i,e,t,a=>{this.writeNow(i,e,t,n,r,!1,a)})}submit(e,n,r,i){if(!e.isDestroyed()){if(e.isRotating())e.diagnostics.count(`record.dropped_during_rotation`);else if(e.config.payloadMode===`defer`&&e.config.enabled&&!e.config.debugBuffer.enabled&&this.namespace!==`uiobs.diagnostics`){if(!e.builder.isEnabled(n,this.namespace,r)&&!this.mirrors(e,n))return;let o=e.journey.current(),s={timeUnixNano:t.r(),trace:e.tracing.resolve(),journey:o?{...o}:null,context:e.context.getAll(),url:a.t(e.diagnostics)};x(e,()=>{i(s)},e.diagnostics,e.config.buffering.maxPendingRecords)}else i()}}writeNow(e,t,n,r,i,a,o){if(!(e.config.enabled&&e.config.debugBuffer.enabled)&&!e.builder.isEnabled(t,this.namespace,n)){this.mirrors(e,t)&&this.print(e,t,r,i,void 0,null,void 0,o);return}let s={snapshot:o,level:t,type:n,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:a?i:T(i,e.diagnostics)},{record:c,dropped:l}=e.builder.build(s),u=!!e.config.redact||e.config.processors.length>0,d=n!==`metric`&&e.config.captureLimits.breadcrumbs>0,f=l===`sampling`&&u&&d?e.builder.build(s,!0):void 0,p=c??f?.record??null,m=p?p.body:l===`sampling`&&!u?r:void 0;d&&m!==void 0&&e.breadcrumbs.push({t:o?Number(o.timeUnixNano.slice(0,-6)):Date.now(),category:n===`action`?`action`:n===`event`?`event`:`log`,message:m}),this.print(e,t,r,i,void 0,p,f?.dropped??l,o),e.emit(c)}writeError(e,t,n,r){let i=this.bind();this.submit(i,e,this.levelType,a=>{this.writeErrorNow(i,e,t,n,r,a)})}writeErrorNow(t,n,r,i,a,o){let s=t.builder.isEnabled(n,this.namespace);if(!s&&!this.mirrors(t,n))return;let c=a===void 0&&(t.diagnostics.guard(`record.sanitize_failed`,`The library could not read the error slot.`,()=>re(i))??!1),l=c?i:a,u=c?void 0:i,d=u===void 0?void 0:ee(u,t.diagnostics),f=d===void 0?void 0:te(u,d,t.diagnostics);if(!s){this.print(t,n,r,l,f,null,void 0,o);return}let p=d?ne(u,t.diagnostics):void 0,{record:m,dropped:h}=t.builder.build({snapshot:o,level:n,type:this.levelType,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(l,t.diagnostics),...d?{"error.type":d.name,"error.message":d.message,"error.stack_trace":d.stack}:{},...p===void 0?{}:{[e.d]:p},[e.c]:t.breadcrumbs.snapshot()}});this.print(t,n,r,l,f,m,h,o),t.emit(m)}print(e,t,n,r,i,a,o,s){if(!e.config.redact&&e.config.processors.length===0){e.console.write(this.namespace,t,n,r,i);return}if(a){e.console.write(this.namespace,t,a.body,a.attributes);return}if(o===`processor`||o===`redact`||o===`malformed`||!e.config.enabled||!e.console.accepts(t))return;let c=e.builder.build({snapshot:s,level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(r,e.diagnostics),...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{}}},!0).record;c&&e.console.write(this.namespace,t,c.body,c.attributes)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},ae=class extends E{constructor(...t){super(...t),o.t(this,`logMetric`,(t,n,r=e.K,i=`gauge`,a,o)=>{if(!Number.isFinite(n)){this.bind().diagnostics.report(`record.dropped_malformed`,`The metric value is not a finite number. The library dropped the metric.`,{"metric.name":t});return}let s=this.bind();this.submit(s,`INFO`,`metric`,c=>{let l=T(a,s.diagnostics),u={...T(o,s.diagnostics),...l,"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,[e.Bt.attributeKeys]:Object.keys(l)};this.writeNow(s,`INFO`,`metric`,t,u,!0,c)})})}},oe=/^[0-9a-f]{32}$/,se=/^[0-9a-f]{16}$/,D=/[1-9a-f]/;function ce(e){return oe.test(e.traceId)&&D.test(e.traceId)&&se.test(e.spanId)&&D.test(e.spanId)}function le(){return s.o(16)}function O(){return s.o(8)}function ue(e){return{traceId:le(),spanId:O(),traceFlags:1,startedAt:Date.now(),reason:e,ended:!1}}function de(e,t,n){return`00-${e}-${t}-${(n&255).toString(16).padStart(2,`0`)}`}function fe(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var pe=class{constructor(t,n=e.ar,r,i){o.t(this,`diagnostics`,void 0),o.t(this,`maxAgeMs`,void 0),o.t(this,`load`,void 0),o.t(this,`spans`,void 0),o.t(this,`ambient`,ue(`start`)),o.t(this,`otel`,void 0),this.diagnostics=t,this.maxAgeMs=n,this.load=r,this.spans=i}setup(e,t){this.maxAgeMs=e,this.load=t}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){return this.activeSpanContext()??this.ambientContext()}ambientContext(){return Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),fe(this.ambient)}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(ce(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){let t=this.ambient;this.ambient=ue(e);let n=fe(this.ambient);return this.finish(t),n}end(){this.finish(this.ambient)}finish(e){e.ended||(e.ended=!0,this.spans?.onEnd({traceId:e.traceId,spanId:e.spanId,reason:e.reason,startedAt:e.startedAt,endedAt:Date.now()}))}headers(){return this.trace(!1).headers}request(){return this.trace(!0)}trace(t){let n={},r=this.otel;if(r&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{r.propagation.inject(r.context.active(),n)}),n.traceparent)return{headers:n};let i=this.activeSpanContext(),a=i??this.ambientContext(),o=i?void 0:this.spans;if(!o?.enabled())return n[e.ir]=de(a.traceId,a.spanId,a.traceFlags),{headers:n};let s=o.keeps(a.traceId),c=s?a.traceFlags:a.traceFlags&-2,l=t?O():a.spanId;return n[e.ir]=de(a.traceId,l,c),!t||!s?{headers:n}:{headers:n,span:{traceId:a.traceId,spanId:l,parentSpanId:a.spanId}}}},me={name:`ui.measure.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Rt},he={name:`ui.measure.phase.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Rt};function ge(e,t,n,r){let i=String(e),a=Date.now(),o=performance.now(),s,c=!1,l=e=>a+e-o,u=(e,a)=>{s&&=(r.metric(he,e-s.at,{...t,"measure.name":i,"measure.phase":s.name}),n&&r.span({name:s.name,kind:`internal`,traceId:n.traceId,spanId:O(),parentSpanId:n.spanId,startMs:l(s.at),endMs:l(e),error:a,attributes:{"measure.name":i}}),void 0)};return{phase:e=>{if(c)return;let t=performance.now();u(t,!1),s={name:String(e),at:t}},end:(e=`ok`)=>{if(c)return;c=!0;let s=performance.now(),d=e===`error`;u(s,d);let f={...t,"measure.outcome":e};r.metric(me,s-o,{...f,"measure.name":i}),n&&r.span({...n,name:i,kind:`internal`,startMs:a,endMs:l(s),error:d,attributes:f})}}}function _e(e,t,n){let r=`error`;try{let i=t(),a=n.guard(`record.sanitize_failed`,`The library could not read what the function of the measure returned. The measure ends now.`,()=>i?.then);if(typeof a!=`function`)return r=`ok`,i;let o=a.call(i,t=>(e.end(),t),t=>{throw e.end(`error`),t});return r=void 0,o}finally{r!==void 0&&e.end(r)}}var ve=`overflow`,ye=new Set([e.g,e.h,e.a,e.v,e.f,e.p,e.m]);function be(e={}){let t={};for(let n of Object.keys(e).sort()){if(n.startsWith(`metric.`)||ye.has(n))continue;let r=e[n];(typeof r==`string`||typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r)}return t}function xe(e,t){if(!Array.isArray(e))return null;let n=t===null?e.length:Math.min(e.length,t+1);return Array.from({length:n},(t,n)=>e[n])}function Se(e,t){return Array.isArray(e)&&(t===null||e.length<=t)&&e.every((t,n)=>typeof t==`number`&&Number.isFinite(t)&&(n===0||t>e[n-1]))}function Ce(t,n,r){let i={"metric.name":t.name,"metric.unit":t.unit,"metric.type":t.kind,[e.Bt.start]:r,[e.Bt.attributeKeys]:Object.keys(n.attributes)};return t.kind===`histogram`?{...i,[e.Bt.count]:n.count,[e.Bt.sum]:n.sum,[e.Bt.min]:n.min,[e.Bt.max]:n.max,[e.Bt.bounds]:t.boundaries,[e.Bt.buckets]:n.buckets}:(i[`metric.value`]=t.kind===`gauge`?n.last:n.sum,i)}function we(e,t){try{return{unit:e.unit,boundaries:e.boundaries}}catch(e){return t(e),{unit:void 0,boundaries:void 0}}}function Te(e,t,n,r){return{name:e,kind:t,unit:we(n,r).unit??`count`,boundaries:[]}}function k(e,t,n,r){let i=Te(e,`counter`,t,r);return{add:(e,t)=>{n(i,e,t)}}}function Ee(e,t,n,r){let i=Te(e,`gauge`,t,r);return{set:(e,t)=>{n(i,e,t)}}}function De(t,n,r,i){let{unit:a,boundaries:o}=we(n,i),s={name:t,kind:`histogram`,unit:a??`count`,boundaries:o??e.Rt,fromApp:o!==void 0};return{record:(e,t)=>{r(s,e,t)}}}var Oe=class{constructor(e,t,n,r={maxSeries:100,maxInstruments:1e3,maxHistogramBoundaries:50}){o.t(this,`intervalMs`,void 0),o.t(this,`emit`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`policy`,void 0),o.t(this,`instruments`,new Map),o.t(this,`timer`,null),o.t(this,`startedAt`,0),this.intervalMs=e,this.emit=t,this.diagnostics=n,this.policy=r}record(e,t,n){!Number.isFinite(t)||e.kind===`counter`&&t<0?this.diagnostics.report(`record.dropped_malformed`,`The value of the metric ${e.name} is not valid. The library dropped it.`,{"metric.name":e.name}):this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the metric ${e.name}.`,()=>{let r=this.instrumentOf(e);r&&(this.add(r,t,be(n)),this.arm())})}collect(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let e=`${String(this.startedAt)}000000`,t=[...this.instruments.values()];this.instruments.clear();for(let{def:n,series:r}of t)for(let t of r.values())this.emit(n.name,t.attributes,Ce(n,t,e))}instrumentOf(t){let n=this.instruments.get(t.name);if(n)return n.def.kind===t.kind?n:(this.diagnostics.report(`record.dropped_malformed`,`The metric ${t.name} is a ${n.def.kind} and a ${t.kind}. The library dropped the value.`,{"metric.name":t.name}),null);let{maxInstruments:r}=this.policy;if(r!==null&&this.instruments.size>=r)return this.diagnostics.count(`record.dropped_by_ceiling`),null;let i=t.fromApp===!0?this.policy.maxHistogramBoundaries:null,a=xe(t.boundaries,i),o=Se(a,i);t.kind===`histogram`&&!o&&this.diagnostics.report(`config.invalid`,`The boundaries of the metric ${t.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`);let s={def:{...t,boundaries:o?a:[...e.Rt]},series:new Map};return this.instruments.set(t.name,s),s}add(t,n,r){let i=JSON.stringify(r),a=t.series.get(i),o=r,{maxSeries:s}=this.policy;if(!a&&s!==null&&t.series.size>=s&&(i=ve,a=t.series.get(i),o={[e._]:!0}),!a){let e=t.def.kind===`histogram`?t.def.boundaries.length+1:0,r=Array(e).fill(0);a={attributes:o,count:0,sum:0,min:n,max:n,last:n,buckets:r},t.series.set(i,a)}if(a.count+=1,a.sum+=n,a.min=Math.min(a.min,n),a.max=Math.max(a.max,n),a.last=n,a.buckets.length>0){let e=t.def.boundaries.findIndex(e=>n<=e);a.buckets[e===-1?a.buckets.length-1:e]+=1}}arm(){this.timer===null&&(this.startedAt=Date.now(),this.timer=setTimeout(()=>{this.collect()},this.intervalMs()),i.t(this.timer))}},ke={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},Ae=class{constructor(t,n,r=e.ln){o.t(this,`settings`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`limits`,void 0),this.settings=t,this.diagnostics=n,this.limits=r}update(e){this.settings=e}accepts(t){return this.settings.level===null||!r.t(e.At,this.settings.level)?!1:e.At[t]>=e.At[this.settings.level]}write(e,t,n,r,i){if(!this.accepts(t)||typeof console>`u`||l.t())return;let a=`%c[%s]%c[${t}]%c`,{styles:o}=this.settings,s=ke[t];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${s}.`,()=>{let c=[];i!==void 0&&c.push(i),r!==void 0&&c.push(u.n(r,this.limits,this.diagnostics)),l.n(()=>{console[s](a,o.namespace,e,o[t],``,n,...c)})})}},je=class{constructor(){o.t(this,`value`,0)}next(){return++this.value}},Me=class{constructor(e){o.t(this,`buffer`,void 0),o.t(this,`pointer`,0),o.t(this,`filled`,!1),o.t(this,`capacity`,void 0),this.capacity=e===0?0:Math.max(e,1),this.buffer=Array(this.capacity)}resize(e){let t=this.snapshot().slice(-e);if(this.capacity=e,this.buffer=Array(e),this.pointer=0,this.filled=!1,e)for(let e of t)this.push(e)}push(e){this.capacity!==0&&(this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0))}retain(e){let t=this.snapshot().filter(e);this.clear();for(let e of t)this.push(e)}clear(){this.buffer.fill(void 0),this.pointer=0,this.filled=!1}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}},Ne=class{constructor(){o.t(this,`map`,new Map)}merge(e){for(let[t,n]of Object.entries(e))n===null?this.map.delete(t):n!==void 0&&this.map.set(t,n)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},Pe=class{constructor(e){o.t(this,`policy`,void 0),o.t(this,`kept`,[]),this.policy=e}push(e){let{enabled:t,maxRecords:n}=this.policy();t&&(this.kept.push({at:Date.now(),record:e}),this.kept.length>=n*2&&(this.kept=this.kept.slice(-n)))}drain(){let t=this.live();return this.kept=[],t.map(({record:t})=>({...t,attributes:{...t.attributes,[e.u]:!0}}))}snapshot(){return this.live().map(({record:e})=>e)}live(){let{enabled:e,maxRecords:t,maxAgeMs:n}=this.policy();if(!e)return this.kept=[],[];let r=n===null?-1/0:Date.now()-n;return this.kept.slice(-t).filter(e=>e.at>=r)}clear(){this.kept=[]}},A=class{constructor(t,n=e.X,r=!1){o.t(this,`handler`,void 0),o.t(this,`throttleMs`,void 0),o.t(this,`consoleFallback`,void 0),o.t(this,`counters`,new Map),o.t(this,`lastEmitted`,new Map),this.handler=t,this.throttleMs=n,this.consoleFallback=r}setPolicy(e,t){this.throttleMs=e,this.consoleFallback=t}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return!1;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a},{handler:c}=this;if(!c)return!0;try{l.n(()=>{c(s)})}catch{this.count(`handler.threw`),this.consoleFallback&&typeof console<`u`&&l.n(()=>{console.warn(`${e.Mt} The onDiagnostic handler threw an error.`)})}return!0}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}};function j(e,t){e.length<20&&!e.includes(t)&&e.push(t)}var Fe=class{constructor(e,t){o.t(this,`config`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`pending`,new Map),o.t(this,`scheduled`,!1),o.t(this,`reporting`,!1),o.t(this,`lost`,{}),this.config=e,this.diagnostics=t}add(t,n,r=[],i=n.length){if(i>0&&(this.lost[t]=(this.lost[t]??0)+i),!this.config.onDrop||this.reporting||n.length===0&&r.length===0)return;let a=this.pending.get(t);a||(a={reason:t,records:0,batchIds:[],journeyIds:[],actions:[]},this.pending.set(t,a)),a.records+=i;for(let e of r)j(a.batchIds,e);for(let t of n){let n=p.t(t,e.f);typeof n==`string`&&j(a.journeyIds,n);let r=p.r(t)?t.body:void 0;typeof r==`string`&&j(a.actions,r)}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.flush()}))}counts(){return{...this.lost}}flush(){this.scheduled=!1;let e=[...this.pending.values()];this.pending.clear();let t=this.config.onDrop;if(t){this.reporting=!0;for(let n of e)this.diagnostics.guard(`handler.threw`,`The onDrop hook threw an error.`,()=>{d.r(()=>{l.n(()=>{t(n)})})});this.reporting=!1}}},Ie=class{constructor(e){o.t(this,`onDrop`,void 0),o.t(this,`actions`,{head:[],tail:[]}),o.t(this,`others`,{head:[],tail:[]}),o.t(this,`arrivals`,0),this.onDrop=e}get records(){return this.inOrder()}get length(){let{actions:e,others:t}=this;return e.head.length+e.tail.length+t.head.length+t.tail.length}push(t,n){let r=p.r(t),i=r?this.actions:this.others,a=r?e.j:n,o={record:t,arrival:this.arrivals};if(this.arrivals+=1,i.head.length<100)i.head.push(o);else if(i.tail.push(o),i.head.length+i.tail.length>a){let e=i.tail[0];i.tail.shift(),this.onDrop(e.record)}}take(){let e=this.inOrder();return this.actions={head:[],tail:[]},this.others={head:[],tail:[]},this.arrivals=0,e}inOrder(){let{actions:e,others:t}=this;return[...e.head,...e.tail,...t.head,...t.tail].sort((e,t)=>e.arrival-t.arrival).map(e=>e.record)}},Le=`error.`,Re=[e.v,e.f,e.p],ze={processor:{label:`A processor`,code:`record.dropped_by_processor`,refused:`processors is not a list of functions. The library drops each record until processors is a list of functions or [].`},redact:{label:`The redact hook`,code:`record.dropped_by_redact`,refused:`redact is not a function. The library drops each record until redact is a function or null.`}},M=e=>typeof e==`number`&&Number.isFinite(e),N=e=>Array.isArray(e)&&e.every(M),P=e=>typeof e==`string`&&/^\d{1,20}$/.test(e),Be=e=>typeof e==`string`&&/^[0-9a-f]{32}$/.test(e),Ve=e=>typeof e==`string`&&/^[0-9a-f]{16}$/.test(e),He=e=>e===``||Ve(e),Ue=e=>e===`counter`,We=e=>e===`histogram`,Ge=e=>e===`client`||e===`internal`,Ke=e=>e===`error`||e===`unset`,qe={"metric.type":Ue,"metric.value":M,[e.Bt.start]:P},Je={"metric.type":We,[e.Bt.start]:P,[e.Bt.count]:M,[e.Bt.sum]:M,[e.Bt.min]:M,[e.Bt.max]:M,[e.Bt.bounds]:N,[e.Bt.buckets]:N},Ye={[e.Gn.kind]:Ge,[e.Gn.parentId]:He,[e.Gn.start]:P,[e.Gn.end]:P,[e.Gn.status]:Ke},Xe={[e.Gn.linkTraceId]:Be,[e.Gn.linkSpanId]:Ve};function Ze(t){let n=t[e.g],r=t[e.a];return n===`span`&&r===`uiobs.traces`?[Ye,Xe]:n!==`metric`||r!==`uiobs.metrics`?[]:t[`metric.type`]===`histogram`?[Je]:[qe]}function Qe(e){let t={};for(let n of Ze(e)){let r=Object.keys(n);if(r.every(t=>n[t](e[t])))for(let n of r)t[n]=e[n]}return t}function F(e){return e}var $e=class{constructor(e){o.t(this,`deps`,void 0),o.t(this,`resourceCache`,null),this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(e,t,n){return this.deps.config.enabled&&this.passesLevel(e,t,n)}passesLevel(t,n,r){let{config:i}=this.deps;if(r!==void 0&&e.kt.includes(r))return!0;let a=this.deps.remote.sampling?.minLevelFor(n)??h.n(n,i);return e.At[t]>=e.At[a]}keepForDebug(e){let{config:t,debug:n}=this.deps;if(!n||!t.enabled||!t.debugBuffer.enabled)return;let{record:r}=this.build(e,!0);r&&n.push(r)}build(n,r=!1){let{config:i,diagnostics:o,tracing:s,journey:c,sequence:l,limits:d,remote:f}=this.deps;if(!r&&!this.isEnabled(n.level,n.namespace,n.type))return o.count(`record.dropped_by_level`),this.keepForDebug(n),{record:null,dropped:`level`};let p=n.trace??n.snapshot?.trace??s.resolve(),m=n.snapshot?n.snapshot.journey:c.current(),g=h.o({level:n.level,type:n.type,namespace:n.namespace,journeyId:m?.id??``,traceId:p.traceId,aggregated:n.aggregated},i,f.sampling?.current()??null);if(!r&&!g)return o.count(`record.dropped_by_sampling`),this.keepForDebug(n),{record:null,dropped:`sampling`};let _=l.next(),v=n.snapshot?.url??a.t(o),y=i.metadata.pageUrl?a.i(v,i.capture.fullUrls,i.capture.urlTransform,o):``,b,x=0;try{let e=u.r(n.snapshot?.context??this.deps.context.getAll(),d,o),t=u.r(this.provided(),d,o),r=u.r(n.scoped??{},d,o),i=u.r(n.payload??{},d,o);x=e.bytes+t.bytes+r.bytes+i.bytes,b={...F(e.value),...F(t.value),...F(r.value),...F(i.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),b={[e.y]:!0}}Object.assign(b,n.fixed),b[e.g]=n.type,b[e.h]=_,b[e.a]=n.namespace,b[e.v]=y,m&&(b[e.f]=m.id,b[e.p]=m.name,m.parentId!==void 0&&(b[e.m]=m.parentId));let S=u.i(n.body,d.maxBodyChars);S!==n.body&&o.count(`record.truncated`);let C={timeUnixNano:n.snapshot?.timeUnixNano??t.r(),traceId:p.traceId,spanId:p.spanId,traceFlags:p.traceFlags,severityNumber:e.Wn[n.level],severityText:n.level,body:S,attributes:b,resource:this.resource()},w=this.hookStages();if(w.length>0){let e=this.applyHooks(C,w,n.fixed);if(typeof e==`string`)return{record:null,dropped:e};({record:C,bytes:x}=e)}let ee={[e.g]:n.type,[e.h]:_,[e.a]:n.namespace};return{record:this.fit(C,x,ee,n.fixed)}}redactForwarded(e){let{redact:t}=this.deps.config;if(!t)return e;let n=[[t,`redact`]],r=this.applyHooks(e,n,Qe(e.attributes));return typeof r==`string`?null:r.record}rehook(t){let{config:n,diagnostics:r,limits:i,remote:o,debug:s}=this.deps,{attributes:c}=t,l=String(c[e.a]),d=this.passesLevel(t.severityText,l,c[e.g]),f=d&&h.a(t,n,o.sampling?.current()??null),p=n.metadata.pageUrl?a.i(String(c[e.v]),n.capture.fullUrls,n.capture.urlTransform,r):``,m=u.i(t.body,i.maxBodyChars);m!==t.body&&r.count(`record.truncated`);let g=Qe(c),_={...t,body:m,attributes:{...c,[e.v]:p},resource:this.resource()},v=this.applyHooks(_,this.hookStages(),g),y=typeof v==`string`?null:this.fit(v.record,v.bytes,c,g);return f?y:(r.count(d?`record.dropped_by_sampling`:`record.dropped_by_level`),y&&s&&n.enabled&&n.debugBuffer.enabled&&s.push(y),null)}fit(t,n,r,i){let{diagnostics:a,limits:o}=this.deps;if(n<=o.maxRecordBytes)return t;a.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped the caller attributes.`,{bytes:n,body:t.body});let s={[e.g]:r[e.g],[e.h]:r[e.h],[e.a]:r[e.a],[e.s]:!0,[e.o]:n};for(let e of Re)e in t.attributes&&(s[e]=t.attributes[e]);for(let[e,n]of Object.entries(t.attributes))e.startsWith(Le)&&(s[e]=n);let c=u.r(s,o,a).bytes;c>o.maxRecordBytes&&`error.data`in s&&(Reflect.deleteProperty(s,e.d),c=u.r(s,o,a).bytes);let l=t.attributes[e.c];if(l!==void 0){let t=u.r(l,o,a).bytes;c+t<=o.maxRecordBytes&&(s[e.c]=l)}return Object.assign(s,i),t.attributes=s,t}hookStages(){let{processors:e,redact:t}=this.deps.config,n=e.map(e=>[e,`processor`]);return t&&n.push([t,`redact`]),n}applyHooks(e,t,n){let r=e;for(let[e,n]of t){let t=this.runHook(e,n,r);if(typeof t==`string`)return t;r=t}let{diagnostics:i,limits:a}=this.deps,o=u.r(r.attributes,a,i),s=F(o.value);return Object.assign(s,n),{record:{...r,attributes:s},bytes:o.bytes}}runHook(n,r,i){let{diagnostics:a}=this.deps,{label:o,code:s,refused:c}=ze[r],l;try{l=n(i)}catch(e){return a.report(s,`${o} threw an error. The library dropped the record.`,void 0,e),r}if(l===null)return n===f.t?a.report(s,c):a.count(s),r;let u=l??i;return t.n(u)?t.t(u.severityText)?{...u,severityNumber:e.Wn[u.severityText]}:(a.report(`record.dropped_malformed`,`${o} set a severityText that is not a log level. The library dropped the record.`),`malformed`):u===i?(a.report(`record.dropped_malformed`,`${o} changed the record to a shape that is not a record. The library dropped it.`),`malformed`):(a.report(s,`${o} returned a value that is not a record. The library dropped the record.`),r)}provided(){let e=this.deps.config.contextProvider;if(!e)return{};let{diagnostics:t}=this.deps,n=t.guard(`handler.threw`,`The contextProvider threw an error. The record has no attributes from it.`,()=>{let t=e();return t===void 0?{}:r.n(t)&&typeof t.then!=`function`?t:null});return n===null&&t.report(`config.invalid`,`contextProvider must return an object of attributes. The library ignores the value.`),n??{}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Cn]:t.serviceName,[e.wn]:t.serviceVersion,[e.yn]:t.environment,[e.kn]:e.nr,[e.An]:e.rr,[e.On]:e.tr,[e.bn]:r.platform,[e.Tn]:n.sessionId,[e.Dn]:n.tabId,[e.vn]:n.contextId,...t.metadata.userAgent?{[e._n]:r.userAgent}:{},...!t.metadata.openfin||r.openfinUuid===void 0?{}:{[e.Sn]:r.openfinUuid},...!t.metadata.openfin||r.openfinName===void 0?{}:{[e.xn]:r.openfinName}},this.resourceCache}},et=1e3,tt={start:`ui.start`,interaction:`ui.interaction`,navigation:`ui.navigation`,explicit:`ui.trace`,maxAge:`ui.trace`};function nt(e){return`${String(Math.round(e*et))}000`}function rt(e){return{name:tt[e.reason],kind:`internal`,traceId:e.traceId,spanId:e.spanId,parentSpanId:``,startMs:e.startedAt,endMs:e.endedAt,error:!1,attributes:{}}}function it(t){return{[e.Gn.kind]:t.kind,[e.Gn.parentId]:t.parentSpanId,[e.Gn.start]:nt(t.startMs),[e.Gn.end]:nt(t.endMs),[e.Gn.status]:t.error?`error`:`unset`,...t.link?{[e.Gn.linkTraceId]:t.link.traceId,[e.Gn.linkSpanId]:t.link.spanId}:{}}}var at={errors:async()=>(await Promise.resolve().then(()=>require("./errors-DP2RUm4V.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-BCn8Gn47.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-OK85T-Dk.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-__X7t4pj.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-lhtONgGt.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-Dkxs6IVQ.cjs"))).ConsoleCapture,uncleanExit:async()=>(await Promise.resolve().then(()=>require("./unclean-exit-BYPYYkQ5.cjs"))).UncleanExitCapture,userTiming:async()=>(await Promise.resolve().then(()=>require("./user-timing-BsU2wQKE.cjs"))).UserTimingCapture,reports:async()=>(await Promise.resolve().then(()=>require("./reports-ojuMKGO7.cjs"))).ReportCapture,resourceTiming:async()=>(await Promise.resolve().then(()=>require("./resource-timing-pAG3ZhB5.cjs"))).ResourceTimingCapture,lifecycle:async()=>(await Promise.resolve().then(()=>require("./lifecycle-DaMdH_X7.cjs"))).LifecycleCapture,framePhases:async()=>(await Promise.resolve().then(()=>require("./profiler-frames-DeaBiB-5.cjs"))).FramePhasesCapture,framePacing:async()=>(await Promise.resolve().then(()=>require("./profiler-frames-DeaBiB-5.cjs"))).FramePacingCapture,replay:async()=>(await Promise.resolve().then(()=>require("./replay-QOFBpAXh.cjs"))).ReplayCapture},ot=new WeakMap,st=0;function I(e){let t=ot.get(e);return t===void 0&&(t=++st,ot.set(e,t)),t}var L=Symbol.for(e.Fn),R=Symbol.for(e.In),ct=[`batching`,`retention`],lt=[`log`,`event`,`action`],z=`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.`,B=`shutdown() got invalid options. The library discards the records in memory. An invalid clearStorage removes the "context" scope.`,V=`flush() got invalid options. The library waits the default 5000 ms.`,ut=new Set([`bus.role_resolved`,`config.reconfigured`,`security.rotated`,`journey.adopted`,`journey.expired`]);function dt(e){return JSON.stringify({...e,urlTransform:e.urlTransform?I(e.urlTransform):void 0,webVitals:typeof e.webVitals==`object`?{loader:e.webVitals.loader!==void 0}:e.webVitals,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String),userTiming:typeof e.userTiming==`object`?{include:e.userTiming.include?.map(String)}:e.userTiming,plugins:e.plugins.map(I)})}function ft(e){if(!r.n(e))return e;let t={...e};for(let e of[`url`,`endpoint`]){let n=t[e];typeof n==`string`&&(t[e]=a.i(n,!1))}return t}function pt(e){return{...e,endpoint:null,metricsEndpoint:null,tracesEndpoint:null,transport:null,transportOnExit:null,transportWorker:null,bus:{...e.bus,mode:`off`}}}function mt(e){return!!e.endpoint||!!e.metricsEndpoint||!!e.tracesEndpoint||!!e.transport||!!e.transportWorker}function H(e,t){return{status:e,accepted:0,stored:0,dropped:0,forwarded:0,pending:0,...t}}function U(e){return H(e.pending>0?`timeout`:`complete`,e)}function W(t){return t.sdkVersion===e.rr}var G=class n{isRotating(){return this.rotating}setConfigurationLocked(e){typeof e==`boolean`&&(this.config.lockConfiguration=e)}constructor(t,n){o.t(this,`rotating`,!1),o.t(this,`rotationSeq`,0),o.t(this,`profilerOn`,!1),o.t(this,`closingContext`,!1),o.t(this,`mismatchVersion`,null),o.t(this,`contextMismatch`,!1),o.t(this,`rotation`,void 0),o.t(this,`memoryStorage`,void 0),o.t(this,`storagePersistence`,`off`),o.t(this,`recordingDiagnostic`,!1),o.t(this,`holdingRecords`,!1),o.t(this,`heldDiagnostics`,[]),o.t(this,`diagnosticLogger`,new E(()=>this,e.Y)),o.t(this,`debugBuffer`,new Pe(()=>this.config.debugBuffer)),o.t(this,`explicitSecurityContext`,void 0),o.t(this,`ownerAdopted`,!1),o.t(this,`sdkVersion`,e.rr),o.t(this,`protocol`,e.M),o.t(this,`diagnostics`,void 0),o.t(this,`config`,void 0),o.t(this,`platform`,void 0),o.t(this,`identity`,void 0),o.t(this,`backing`,s.r()),o.t(this,`stores`,{local:()=>this.backing.local(),session:()=>this.backing.session(),opener:()=>this.backing.opener?.()??null}),o.t(this,`identityBuiltAs`,void 0),o.t(this,`sessionTouch`,void 0),o.t(this,`context`,new Ne),o.t(this,`breadcrumbs`,void 0),o.t(this,`tracing`,void 0),o.t(this,`sequence`,new je),o.t(this,`journey`,void 0),o.t(this,`builder`,void 0),o.t(this,`remote`,{sampling:null,changed:()=>{this.refreshCaptures()}}),o.t(this,`identityEpoch`,0),o.t(this,`errorHook`,void 0),o.t(this,`replayConsent`,void 0),o.t(this,`replay`,void 0),o.t(this,`remoteCaptureTimer`,void 0),o.t(this,`installedCaptureKey`,``),o.t(this,`replayBuiltKey`,``),o.t(this,`console`,void 0),o.t(this,`drops`,void 0),o.t(this,`meter`,void 0),o.t(this,`bus`,null),o.t(this,`busBuilt`,void 0),o.t(this,`busLoad`,void 0),o.t(this,`sender`,void 0),o.t(this,`senderLoad`,void 0),o.t(this,`pendingRecords`,new Ie(e=>{this.dropHeld(e)})),o.t(this,`pausedLoss`,new WeakSet),o.t(this,`carried`,[]),o.t(this,`sessionPicked`,!1),o.t(this,`deliveryClosed`,!1),o.t(this,`parkedSender`,void 0),o.t(this,`retiring`,void 0),o.t(this,`startFailed`,!1),o.t(this,`running`,!1),o.t(this,`openGate`,void 0),o.t(this,`startGate`,new Promise(e=>{this.openGate=e})),o.t(this,`captures`,[]),o.t(this,`captureGeneration`,0),o.t(this,`captureOnce`,{webVitals:!1,navigationTiming:!1,longFrames:!1,uncleanExit:!1,userTiming:!1}),o.t(this,`bootBuffer`,new Ie(e=>{this.dropHeld(e)})),o.t(this,`forwardBuffer`,[]),o.t(this,`forwardScheduled`,!1),o.t(this,`roleResolved`,!1),o.t(this,`started`,Promise.resolve()),o.t(this,`ready`,!1),o.t(this,`destroyed`,!1),o.t(this,`stopping`,void 0),o.t(this,`lastSendAt`,null),o.t(this,`lastGapAt`,0),o.t(this,`limits`,void 0),o.t(this,`journeyOptions`,void 0),o.t(this,`tunablesLocked`,!1),o.t(this,`degraded`,void 0),o.t(this,`serverReported`,!1),o.t(this,`onPageHide`,()=>{S(this),this.dropPaused(),this.role()===`forwarder`&&(this.tracing.end(),this.sendForwarded())}),o.t(this,`busCanAccept`,(e,t)=>this.bus?.isRegistered(e,t)??!1),o.t(this,`busAccept`,(e,t,n)=>{this.destroyed||this.ensureBus().then(r=>{r&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{r.acceptDirect(e,t,n)})})}),o.t(this,`reportLoss`,(e,t,n,r)=>{this.drops.add(e,t,n,r)}),o.t(this,`reportGap`,(t,n)=>{this.drops.add(t.reason,n.flatMap(e=>e.records),n.map(e=>e.id));let r=Date.now();r-this.lastGapAt<6e4||(this.lastGapAt=r,new E(()=>this,e.Jn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))}),this.diagnostics=new A(typeof t.onDiagnostic==`function`?t.onDiagnostic:void 0),this.platform=a.n(this.diagnostics),this.degraded=n||this.onServer(),this.config=f.r(this.allowed(t),this.diagnostics),this.explicitSecurityContext=!!t.securityContext?.id,this.config.securityContext.id||=s.i(this.diagnostics),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.identityBuiltAs=this.config.identity,this.identity=s.s(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.sessionTouch=new s.n(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.breadcrumbs=new Me(this.config.captureLimits.breadcrumbs);let r=e=>h.i(e,this.config.sampling.defaultRate);this.tracing=new pe(this.diagnostics,this.config.correlation.traceMaxAgeMs??1/0,this.config.otelLoader,{enabled:()=>this.config.tracesEndpoint!==null,keeps:r,onEnd:e=>{r(e.traceId)&&this.recordSpan(rt(e))}}),this.limits={...this.config.limits},this.console=new Ae(this.config.consoleOutput,this.diagnostics,this.limits),this.drops=new Fe(this.config,this.diagnostics),this.journeyOptions={...m.t,maxAgeMs:this.config.journey.maxAgeMs},this.journey=new m.n(this.journeyOptions,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new $e({remote:this.remote,config:this.config,limits:this.limits,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform,debug:this.debugBuffer}),this.meter=new Oe(()=>this.config.metrics.intervalMs,(e,t,n)=>{this.emitPoint(e,t,n)},this.diagnostics,this.config.metrics),this.diagnostics.setHandler(this.diagnosticHandler()),this.syncProfiler()}diagnosticHandler(){return this.config.diagnostics.records===!1?this.config.onDiagnostic:e=>{this.recordDiagnostic(e),this.config.onDiagnostic?.(e)}}recordDiagnostic(e){let{records:t}=this.config.diagnostics;if((t===!0||t!==!1&&t.includes(e.code))&&!this.recordingDiagnostic){if(this.holdingRecords)this.heldDiagnostics.push(e);else{this.recordingDiagnostic=!0;try{(ut.has(e.code)?this.diagnosticLogger.info:this.diagnosticLogger.warn)(e.message,{"diagnostic.code":e.code,"diagnostic.count":e.count,"diagnostic.detail":ft(e.detail)})}finally{this.recordingDiagnostic=!1}}}}dropHeldRecords(){let e=this.heldDiagnostics.length;this.heldDiagnostics=[],e>0&&this.diagnostics.count(`record.dropped_during_rotation`,e)}addBreadcrumb(e,t){this.rotating||this.destroyed||this.diagnostics.guard(`record.sanitize_failed`,`The library could not add the breadcrumb.`,()=>{let n={t:Date.now(),category:`custom`,message:u.i(String(e),this.limits.maxBodyChars)};if(t!==void 0){let e=u.n(t,this.limits,this.diagnostics);n.data=r.n(e)?e:{value:e}}this.breadcrumbs.push(n)})}recordMetric(e,t,n){!this.destroyed&&!this.rotating&&this.config.enabled&&this.meter.record(e,t,n)}startMeasure(e,t){let n=this.identityEpoch,r=()=>!this.destroyed&&!this.rotating&&(!this.config.securityContext.isolation||this.identityEpoch===n),i=this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the measure.`,()=>({...t}));return ge(this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the name of the measure.`,()=>`${e}`)??``,i??{},this.tracing.request().span,{metric:(e,t,n)=>{r()&&this.recordMetric(e,t,n)},span:e=>{r()&&this.recordSpan(e)}})}recordSpan(t){if(this.config.tracesEndpoint===null)return;let{record:n}=this.builder.build({level:`INFO`,type:`span`,body:t.name,namespace:e.or,payload:t.attributes,fixed:it(t),trace:{traceId:t.traceId,spanId:t.spanId,traceFlags:1}});this.emit(n)}emitPoint(t,n,r){if(this.destroyed)return;let{record:i}=this.builder.build({level:`INFO`,type:`metric`,body:t,namespace:e.Vt,payload:n,fixed:r,aggregated:!0});this.emit(i)}syncProfiler(){let e=this.config.profiler.enabled&&this.config.enabled;if(e===this.profilerOn)return;this.profilerOn=e;let t=c.t();if(!e){t.collect(!1),t.detach();return}let n={capacity:this.config.profiler.maxProbes,intervalMs:()=>this.config.metrics.intervalMs,emit:(e,t,n)=>{this.emitPoint(e,t,n)},diagnostics:this.diagnostics,ready:()=>!this.rotating||this.closingContext,outlier:(e,t)=>{this.breadcrumbs.push({t:Date.now(),category:`profile`,message:`${e} ${String(Math.round(t))} ms`})}};t.attach(n)}setReplay(e){this.replayConsent=e,e?this.replay?.start():this.replay?.stop()}collectPoints(){this.meter.collect(),this.profilerOn&&c.t().collect(!1)}advanceIdentity(){this.identityEpoch++,this.profilerOn&&this.config.securityContext.isolation&&c.t().reset(),this.remote.sampling=null,this.refreshCaptures()}static pinned(){return globalThis[L]??null}static current(){let e=n.local;if(e)return e.destroyed?null:e;let t=n.pinned();return t&&W(t)?t:null}static stopped(){let e=n.local;if(e?.destroyed)return e;let t=globalThis[R];return t&&W(t)?t:null}isDestroyed(){return this.destroyed}static configure(e,t=!1){try{return n.startOrUpdate(e,t)}catch(e){let t=n.current();if(t?.tunablesLocked)return t.diagnostics.report(`config.invalid`,`configure() could not read its options. The library keeps the current settings.`,void 0,e),t;let r=t??n.startOrUpdate({},!0);return r.refuse(e),r}}refuse(t){this.startFailed=!0;let n=f.r({redact:f.t},new A,this.config);f.n(this.config,n),l.n(()=>{console.warn(`${e.Mt} ${z}`)}),this.diagnostics.report(`config.invalid`,z,void 0,t),this.rehookHeld()}static startOrUpdate(e,t){let r=n.local;if(r&&!r.destroyed)return r.reconfigure(e),r;n.local=null;let i=n.pinned();if(i){if(!W(i))return n.startDegraded(e,i.sdkVersion,t);if(!i.destroyed)return i.reconfigure(e),i}let a=new n(e,!1);return globalThis[L]=a,Reflect.deleteProperty(globalThis,R),t||a.launch(),a}static startDegraded(t,r,i){let a=new n(t,!0);n.local=a;let o=typeof r==`string`?r:`before 0.9.0`;return a.mismatchVersion=o,a.diagnostics.report(`runtime.version_mismatch`,`Another copy of the library, version ${o}, owns the page runtime. This copy, version ${e.rr}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:o,own:e.rr}),i||a.launch(),a}reconfigure(e){if(this.rotating){this.diagnostics.report(`config.locked`,`Configuration cannot change during security-context rotation.`);return}if(this.config.lockConfiguration){let t=f.r(e,this.diagnostics,this.config);K(this.config,t)||this.diagnostics.report(`config.locked`,`Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.`);return}S(this);let t=this.keepDestination(this.keepRouting(this.allowed(e)));!this.tunablesLocked&&t.securityContext?.id&&(this.explicitSecurityContext=!0);let n=f.r(t,this.diagnostics,this.config),r=this.tunablesLocked?[`correlation`,`storage`]:[];for(let e of r)K(n[e],this.config[e])||(this.diagnostics.report(`config.invalid`,`${e} cannot change after startup. The library keeps the current settings.`),Object.assign(n,{[e]:this.config[e]}));this.keepStartupTunables(n);let{redact:i,processors:a,enabled:o}=this.config;o&&!n.enabled&&this.collectPoints(),f.n(this.config,n),this.config.redact!==f.t&&(this.startFailed=!1),(this.config.redact!==i||this.config.processors!==a)&&this.debugBuffer.clear(),this.breadcrumbs.resize(this.config.captureLimits.breadcrumbs),this.diagnostics.setHandler(this.diagnosticHandler()),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.builder.invalidateResource(),this.console.update(this.config.consoleOutput),this.keepBuiltIdentity(),this.syncProfiler(),this.launch(),this.running&&o!==this.config.enabled&&this.sender?.hold(!this.config.enabled),this.refreshCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}onServer(){return this.platform.platform===`node`}allowed(e){return this.degraded?(this.onServer()&&!this.serverReported&&mt(e)&&(this.serverReported=!0,this.diagnostics.report(`config.invalid`,`The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.`)),pt(e)):e}keepRouting(t){if(!this.tunablesLocked||this.degraded||!this.config.securityContext.isolation)return t;let n=f.r(t,new A,this.config),r=e.Nn.filter(e=>!K(n[e],this.config[e]));if(n.securityContext.id!==this.config.securityContext.id&&r.push(`securityContext.id`),r.length===0)return t;let i={...t};for(let t of e.Nn)r.includes(t)&&Reflect.deleteProperty(i,t);if(r.includes(`securityContext.id`)){let e={...t.securityContext};Reflect.deleteProperty(e,`id`),i.securityContext=e}return this.diagnostics.report(`config.invalid`,`Isolation refuses changes to ${r.join(`, `)}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`),i}keepStartupTunables(e){if(this.senderLoad!==void 0&&this.keepSections(e,ct),!this.tunablesLocked){Object.assign(this.limits,e.limits),this.journeyOptions.maxAgeMs=e.journey.maxAgeMs;return}this.keepSections(e,[`limits`]);for(let t of[`mode`,`openFinRole`])e.bus[t]!==this.config.bus[t]&&(this.diagnostics.report(`config.invalid`,`bus.${t} cannot change after startup. The library keeps "${this.config.bus[t]}".`,{requested:e.bus[t]}),Object.assign(e.bus,{[t]:this.config.bus[t]}));let{maxAgeMs:t}=this.config.journey;e.journey.maxAgeMs!==t&&(this.diagnostics.report(`config.invalid`,`journey.maxAgeMs cannot change after startup. It stays ${String(t)}.`,{requested:e.journey.maxAgeMs}),e.journey.maxAgeMs=t);let{maxProbes:n}=this.config.profiler;e.profiler.maxProbes!==n&&(this.diagnostics.report(`config.invalid`,`profiler.maxProbes cannot change after startup. It stays ${String(n)}.`,{requested:e.profiler.maxProbes}),e.profiler.maxProbes=n)}keepSections(e,t){for(let n of t)K(e[n],this.config[n])||(this.diagnostics.report(`config.invalid`,`${n} cannot change after startup. The current values stay.`,{requested:e[n]}),Object.assign(e,{[n]:this.config[n]}))}keepDestination(e){if(this.senderLoad===void 0)return e;let t=e;for(let n of[`transport`,`transportWorker`]){let r=e[n],i=typeof r==`function`&&this.config[n]===void 0,a=r===null&&this.config[n]!==void 0;(i||a)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove ${n} after the delivery stack loads. The current transport stays.`),t={...t},Reflect.deleteProperty(t,n))}return(t.endpoint===null||t.endpoint===``)&&this.config.transport===void 0&&(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The current endpoint stays.`),t={...t,endpoint:void 0}),t}keepBuiltIdentity(){if(!this.tunablesLocked){this.identityBuiltAs=this.config.identity;return}let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}launch(){this.startFailed||(this.tunablesLocked||(this.tunablesLocked=!0,this.config.enabled||this.drops.add(`disabled`,this.rehookHeld())),!this.running&&this.config.enabled&&this.start())}start(){this.running=!0,this.identityBuiltAs===`storage`&&!this.onServer()&&(this.backing=s.t);let{sessionIdleMs:e,traceMaxAgeMs:t}=this.config.correlation,{sessionId:n,tabId:r}=s.s(this.diagnostics,this.stores,e);this.sessionTouch=new s.n(this.diagnostics,this.stores,e),this.sessionPicked?this.sessionTouch.restart(this.identity.sessionId):this.identity.sessionId=n,this.identity.tabId=r,this.builder.invalidateResource(),this.breadcrumbs.retain(e=>!lt.includes(e.category)),this.tracing.setup(t??1/0,this.config.otelLoader),this.tracing.loadOtel();for(let e of this.rehookHeld())this.bootBuffer.push(e,this.config.buffering.maxHeldRecords);this.openGate(),this.init()}rehookHeld(){return this.bootBuffer.take().map(e=>this.builder.rehook(e)).filter(e=>e!==null)}async init(){this.degraded||addEventListener(`pagehide`,this.onPageHide);let e=this.installCaptures();this.started=this.boot(),await this.started,await e}async boot(){try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{await this.startGate;let{Bus:e}=await Promise.resolve().then(()=>require("./bus-B__467mL.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onSecurityContext:e=>{if(this.explicitSecurityContext&&this.config.securityContext.id!==e)return this.contextMismatch=!0,this.diagnostics.report(`security.context_mismatch`,`The configured security context differs from the upstream owner.`),!1;if(this.contextMismatch=!1,this.config.securityContext.id!==e){if(this.ownerAdopted){S(this),this.drops.add(`security_context`,[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer]),this.forwardBuffer=[],this.context.clear(),this.breadcrumbs.clear();let e=this.rotating;this.rotating=!0,this.collectPoints(),this.profilerOn&&c.t().reset();let t=this.sessionTouch.stored();this.resetSession(t!==void 0&&t!==this.identity.sessionId?t:s.i(this.diagnostics)),this.rotating=e,this.advanceIdentity()}this.config.securityContext.id=e}return this.ownerAdopted=!0,!0},onRecords:e=>{this.ingestForwarded(e)},paused:()=>!this.config.enabled,onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()},onFlush:e=>this.flushFor(e,!1),remote:this.remote});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.running||!this.config.enabled||this.deliveryClosed||this.destroyed||!this.hasDestination()||this.role()!==`sender`?Promise.resolve():this.loadSender()}hasDestination(){return!!this.config.endpoint||this.config.transport!==void 0}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-DR7ZycZY.cjs")),t=this.destroyed?null:await e.create({storage:this.memoryStorage,onStorage:e=>{e.name===`memory`&&(this.memoryStorage=e)},onPersistence:e=>{this.storagePersistence=e},config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,onLoss:this.reportLoss,remote:this.remote,beforeExit:()=>{S(this),this.collectPoints(),this.tracing.end()},onSent:e=>{this.lastSendAt=e}});if(!t||this.destroyed){await t?.discard();return}if(this.deliveryClosed){await this.parkSender(t);return}this.sender=t,this.config.enabled||t.hold(!0)}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e),this.drops.add(`load_failed`,this.pendingRecords.records)}for(let e of this.pendingRecords.take())this.sender?.push(e);if(this.sender&&this.carried.length>0){let e=this.carried;this.carried=[],await this.adoptStored(this.sender,e)}}async adoptStored(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store the carried batches under the new context.`,()=>e.adopt(t,this.config.securityContext.id))}refreshCaptures(){if(clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 0,this.destroyed)return;let e=this.remote.sampling?.wire();e&&(this.remoteCaptureTimer=setTimeout(()=>{this.refreshCaptures()},e.ttlMs),i.t(this.remoteCaptureTimer)),this.captureState(this.effectiveCapture())!==this.installedCaptureKey&&this.installCaptures()}captureState(e){let{enabled:t,framePhases:n,framePacing:r}=this.config.profiler;return`${String(this.config.enabled)}${dt(e)}${String(t&&n)}${String(t&&r)}${this.replayState(e)}`}replayState(e){let{replay:t}=this.config;return t.enabled?JSON.stringify([t.loader&&I(t.loader),t.onSegment&&I(t.onSegment),I(t.recordOptions),t.endpoint,t.requireConsent,t.mode,t.maskText,t.maskInputs,t.maskSelectors,t.blockSelectors,t.recordCanvas,t.bufferMs,t.plugins.map(I),e.fullUrls,e.ignoreUrls.map(String)]):``}effectiveCapture(){let t={...this.config.capture},n=this.remote.sampling?.current()?.capture;for(let r of e.un){let e=n?.[r];if(t.remoteToggles.includes(r)&&e!==void 0){if(e&&typeof t[r]==`object`)continue;t[r]=e}}return t}async installCaptures(){if(this.degraded||!this.running)return;let t=++this.captureGeneration,n=this.effectiveCapture();if(this.installedCaptureKey=this.captureState(n),!this.config.enabled){this.uninstallCaptures();return}let r=this.replayState(n);r!==this.replayBuiltKey&&(this.replayBuiltKey=``);let i=r!==``&&r===this.replayBuiltKey?this.replay:void 0,a=[],{profiler:o}=this.config;(n.errors||n.rejections||n.resourceErrors)&&a.push(`errors`),(n.fetch||n.xhr)&&a.push(`network`),(n.interactions||n.navigation)&&a.push(`interactions`),n.webVitals&&a.push(`webVitals`),n.longFrames&&a.push(`longFrames`),(typeof n.console==`object`?n.console.levels?.length!==0:n.console)&&a.push(`console`),n.uncleanExit&&a.push(`uncleanExit`),n.userTiming&&a.push(`userTiming`),n.reports&&a.push(`reports`),n.resourceTiming&&a.push(`resourceTiming`),n.lifecycle&&a.push(`lifecycle`),o.enabled&&o.framePhases&&a.push(`framePhases`),o.enabled&&o.framePacing&&a.push(`framePacing`),this.config.replay.enabled&&!i&&a.push(`replay`);let[s,c]=await Promise.all([Promise.all(a.map(e=>this.loadCapture(e))),n.webSocket?this.loadWebSocket():void 0]);if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures(i);let l={isActive:()=>!this.destroyed&&!this.rotating,config:Object.assign(Object.create(this.config),{capture:n}),diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new ae(()=>this,e.P),once:this.captureOnce,recordMetric:(e,t,n)=>{this.recordMetric(e,t,n)},recordSpan:e=>{this.recordSpan(e)},sessionId:()=>this.identity.sessionId,onError:e=>{this.errorHook=e},setContext:(e,t)=>{this.context.merge({[e]:t??null})},replayConsent:()=>this.replayConsent};s.forEach((e,t)=>{if(e){let n=new e(l);this.captures.push(n),a[t]===`replay`&&(this.replay=n,this.replayBuiltKey=r)}});let u=c?[...n.plugins,new c(this.diagnostics,l.config)]:n.plugins;for(let e of u)this.captures.push(this.pluginCapture(e));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(e){for(let t of this.captures)t!==e&&this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${t.name} capture.`,()=>{t.uninstall()});this.captures.length=0,this.replay=e,e&&this.captures.push(e)}loadWebSocket(){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the webSocket capture.`,async()=>(await Promise.resolve().then(()=>require("./web-socket-Cs1ZbmmN.cjs"))).WebSocketCapture)}pluginCapture(t){let{name:n}=t,r=(e,t,n)=>{this.recordMetric(e,t,n)},i=t=>{this.diagnostics.report(`config.invalid`,e.St,void 0,t)},a={logger:new E(()=>this,`${e.P}.${n}`),counter:(e,t={})=>k(e,t,r,i),histogram:(e,t={})=>De(e,t,r,i),addBreadcrumb:(e,t)=>{this.addBreadcrumb(e,t)},ownRequest:d.r};return{name:n,install:()=>{t.install(a)},uninstall:()=>{t.uninstall()}}}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,at[e])}registerWorker(e,t={}){let n=!1,r;return this.destroyed?()=>void 0:(this.constructBus().then(i=>{!i||this.destroyed||n||(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{r=i.attachWorker(e,t)}),this.ensureBus())}),()=>{n=!0,r?.()})}registerFrame(e,t){let n=!1,r;return this.constructBus().then(i=>{!i||this.destroyed||n||(r=this.diagnostics.guard(`bus.send_failed`,`The frame could not be registered.`,()=>i.registerFrame(e,t)),this.ensureBus())}),()=>{n=!0,r?.()}}async destroy(e){let{discard:t,scope:n}=this.shutdownRule(e);this.stopping??=this.stop(t),await this.stopping,n!==void 0&&await this.clearStorage(n)}async stop(e){e||(S(this),this.collectPoints(),this.tracing.end()),this.profilerOn&&(this.profilerOn=!1,c.t().detach()),this.destroyed=!0,this.backing=s.r(),C(this),this.collectPoints(),clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 0,this.degraded||removeEventListener(`pagehide`,this.onPageHide),this.uninstallCaptures();let t=e?this.discardHeld():this.flushHeld();this.journey.destroy(),this.bus?.destroy(),await t,await this.senderLoad,await this.rotation?.catch(()=>void 0);let r=this.parkedSender;this.parkedSender=void 0,await this.diagnostics.guardAsync(`pipeline.crashed`,`The delivery stack of the old context did not stop at shutdown. The library leaves its stored batches in storage.`,async()=>{await(e?r?.discard():r?.retire(`retain`,0,this.config.securityContext.id))}),await this.memoryStorage?.close(),n.pinned()===this&&(Reflect.deleteProperty(globalThis,L),globalThis[R]=this)}shutdownRule(e){let t=this.readOptions(e,B);if(t===void 0)return{discard:!0};let{pending:n,clearStorage:r}=t,i=r==null,a=i||r===`context`||r===`namespace`,o;i||(o=r===`namespace`?`namespace`:`context`);let s=n===void 0||n===`flush`;return(!a||!(s||n===`discard`)||n===`flush`&&o)&&this.diagnostics.report(`config.invalid`,B),{discard:!s||o!==void 0,scope:o}}async flushHeld(){this.sender&&this.releaseBootBuffer(),this.dropPaused();let e=this.sender?.destroy();this.sendForwarded();let t=[...this.bootBuffer.take(),...this.pendingRecords.take()];this.drops.add(`load_failed`,this.unreported(t)),await e}async discardHeld(){let e=[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer];this.forwardBuffer=[],this.breadcrumbs.clear(),this.debugBuffer.clear(),this.context.clear(),this.journey.applyRemote(null);let t=await this.sender?.discard()??[];this.drops.add(`discarded`,this.unreported([...e,...t]))}async clearStorage(e){this.tunablesLocked&&await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove the stored batches at shutdown.`,async()=>{let{clearStored:t}=await Promise.resolve().then(()=>require("./stored-context-BOu54M8Y.cjs")),n=this.carried.map(e=>e.id);this.carried=[],await t(this.storeAccess(),e,n,this.identityBuiltAs===`storage`&&!this.onServer())})}emit(e){if(!e||this.destroyed)return;if(this.rotating&&!this.closingContext){this.drops.add(`security_context`,[e]);return}this.sessionTouch.touch(this.identity.sessionId);let t=e.severityText===`ERROR`||e.severityText===`FATAL`,n=t?[...this.debugBuffer.drain(),e]:[e];t&&this.errorHook?.(e);for(let e of n)this.ready?this.route(e):this.bootBuffer.push(e,this.config.buffering.maxHeldRecords)}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){if(this.deliveryClosed){this.drops.add(`security_context`,[e]);return}if(this.sender){this.sender.push(e);return}let t=!this.config.enabled&&this.hasDestination();!this.senderLoad&&!t?(this.diagnostics.count(`record.dropped_no_destination`),this.hasDestination()&&this.drops.add(`load_failed`,[e])):this.pendingRecords.push(e,this.config.buffering.maxHeldRecords)}dropPaused(){if(this.config.enabled)return;let e=this.unreported([...this.pendingRecords.records,...this.sender?.records()??[]]);for(let t of e)this.pausedLoss.add(t);this.drops.add(`disabled`,e)}unreported(e){return e.filter(e=>!this.pausedLoss.has(e))}dropHeld(e){this.diagnostics.count(`record.dropped_boot_buffer_full`),this.drops.add(`buffer_full`,[e])}forward(e){this.forwardBuffer.push(e),this.forwardScheduled||(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1,this.sendForwarded()}))}sendForwarded(){let e=this.forwardBuffer;this.forwardBuffer=[];let{bus:t}=this;return e.length===0||!t?0:t.sendRecords(e)}ingestForwarded(e){if(this.destroyed)return;if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}let n=[];for(let r of e){if(!t.n(r)){this.diagnostics.count(`record.dropped_malformed`);continue}if(r.attributes[`uiobs.debug_buffer`]!==!0&&!h.a(r,this.config,this.remote.sampling?.current()??null)){this.diagnostics.count(`record.dropped_by_sampling`);continue}let e=this.builder.redactForwarded(r);e&&n.push(e)}if(this.rotating)this.drops.add(`security_context`,n);else if(!this.config.enabled)this.drops.add(`disabled`,n);else for(let e of n)this.deliver(e)}releaseBootBuffer(){let e=this.bootBuffer.take(),{processors:t,redact:n}=this.config,r=t.length===0&&n===void 0?this.journey.current():null;for(let t of e)r&&!t.attributes[`journey.id`]&&(t.attributes[`journey.id`]=r.id,t.attributes[`journey.name`]=r.name),this.route(t)}regenerateTabId(){let e=s.i(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,s.a(e,this.diagnostics,this.stores),this.builder.invalidateResource(),this.bus?.setTabId(e)}newSession(){this.destroyed||(S(this),this.resetSession(s.i(this.diagnostics)))}resetSession(e){this.sessionPicked=!0,this.collectPoints(),this.tracing.rotate(`explicit`),this.journey.end(),this.breadcrumbs.clear(),this.debugBuffer.clear(),this.replay?.reset(),this.identity.sessionId=e,this.sessionTouch.restart(e),this.builder.invalidateResource()}rotateSecurityContext(e,t={}){if(this.destroyed)return Promise.reject(Error(`The runtime has stopped.`));if(!this.tunablesLocked)return Promise.reject(Error(`The runtime is not configured. Call configure() before rotateSecurityContext().`));S(this),this.rotating=!0;let n=++this.rotationSeq,r=(this.rotation??Promise.resolve()).catch(()=>void 0).then(()=>this.runRotation(e,t,n));this.rotation=r;let i=()=>{this.rotation===r&&(this.rotation=void 0,this.rotating=!1,this.retiring=void 0)};return r.then(i,i),r}async runRotation(e,t,n){if(this.destroyed)throw Error(`The runtime has stopped.`);if(await this.started,this.role()===`forwarder`)throw Error(`Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.`);let r;try{r=(await Promise.resolve().then(()=>require("./rotation-E2eKClIs.cjs"))).rotateContext}catch(e){throw this.diagnostics.report(`pipeline.crashed`,`The library could not load the security-context rotation.`,void 0,e),await this.closeDelivery(),e}if(this.isDestroyed())throw Error(`The runtime has stopped.`);try{await r(this.rotationHost(),e,t,n)}finally{this.dropHeldRecords()}}rotationHost(){return{runtime:this,quiet:new A,senderLoaded:async()=>{await this.senderLoad},holdRecords:e=>{this.holdingRecords=!0;try{return e()}finally{this.holdingRecords=!1}},allowed:e=>this.allowed(e),closeDelivery:()=>this.closeDelivery(),closeContext:()=>{this.closingContext=!0;try{this.collectPoints(),this.tracing.end(),this.journey.end()}finally{this.closingContext=!1}},takeOld:()=>{let e=[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer],t=this.sender??this.parkedSender;this.retiring=t;let n=this.carried;return this.forwardBuffer=[],this.carried=[],this.sender=void 0,this.senderLoad=void 0,this.parkedSender=void 0,{held:e,sender:t,closed:this.deliveryClosed,carried:n}},drop:e=>{this.drops.add(`security_context`,this.unreported(e))},storeAccess:()=>this.storeAccess(),advanceIdentity:()=>{this.advanceIdentity()},openDelivery:async()=>{this.deliveryClosed=!1,await this.syncSender(),this.bus?.rotateContext()},endRotation:e=>{if(this.rotating=e!==this.rotationSeq,this.rotating){this.dropHeldRecords();return}let t=this.heldDiagnostics;this.heldDiagnostics=[];for(let e of t)this.recordDiagnostic(e)},route:e=>{this.route(e)},adopt:async e=>{!this.config.enabled||this.destroyed?this.carried=[...e]:await this.sender?.adopt(e,this.config.securityContext.id)}}}async closeDelivery(){this.deliveryClosed=!0,this.diagnostics.report(`security.rotation_failed`,`The security-context rotation failed. The library sends no record until a rotation succeeds.`),await this.senderLoad;let e=this.sender;this.sender=void 0,this.senderLoad=void 0,e&&await this.parkSender(e),this.drops.add(`security_context`,this.unreported(this.pendingRecords.take()))}async parkSender(e){this.parkedSender=e,await this.diagnostics.guardAsync(`pipeline.crashed`,`The delivery stack of the old context did not stop. The next rotation that succeeds retires it.`,()=>e.pause(this.config.securityContext.id))}async debugBundle(t){let{configSummary:n}=await Promise.resolve().then(()=>require("./debug-bundle-B2v6Cym-.cjs")),{record:r}=this.builder.build({level:`INFO`,type:`system`,body:`debug bundle`,namespace:e.Y,payload:{[e.c]:this.breadcrumbs.snapshot()}},!0),i=r?.attributes??{},a=i[e.c],o=i[e.v];return{createdAt:new Date().toISOString(),sdkVersion:this.sdkVersion,health:t,diagnostics:this.diagnostics.snapshot(),resource:r?.resource??{},pageUrl:typeof o==`string`?o:``,breadcrumbs:Array.isArray(a)?a:[],debugBuffer:this.debugBuffer.snapshot(),config:n(this.config,this.limits,this.diagnostics)}}async health(){let e=this.sender?.stats(),t=[];this.mismatchVersion&&t.push(`runtime.version_mismatch`),this.contextMismatch&&t.push(`security.context_mismatch`);let{redact:n,processors:r}=this.config;(n===f.t||r.includes(f.t))&&t.push(`records.refused`),this.deliveryClosed?t.push(`security.rotation_failed`):this.ready&&this.config.enabled&&this.hasDestination()&&this.role()===`sender`&&!this.sender&&t.push(`sender.unavailable`);let{sourcePolicy:i,maxMessageBytes:a,maxRecordsPerMessage:o,maxMessagesPerSecond:s}=this.config.bus;return{delivery:{pending:(e?.pending??0)+this.heldRecords(),inFlight:e?.inFlight??0,stored:await this.storedBatches(),lastSendAt:this.lastSendAt,lastFailureAt:e?.lastFailureAt??null,consecutiveFailures:e?.consecutiveFailures??0,throttledUntil:e?.throttledUntil??null,dropped:this.drops.counts()},sdkVersion:this.sdkVersion,owningSdkVersion:this.mismatchVersion,status:this.destroyed?`stopped`:this.tunablesLocked?this.config.enabled?this.rotating?`rotating`:t.length?`degraded`:this.ready?`ready`:`starting`:`disabled`:`unconfigured`,mode:this.role()===`forwarder`?`forwarder`:this.hasDestination()?`sender`:`console-only`,senderReady:this.sender!==void 0&&this.config.enabled&&!this.destroyed&&!this.rotating&&!this.deliveryClosed,configurationLocked:this.config.lockConfiguration,issues:t,securityContext:{...this.config.securityContext},storagePersistence:this.storagePersistence,bus:{sourcePolicy:i,maxMessageBytes:a,maxRecordsPerMessage:o,maxMessagesPerSecond:s}}}storeAccess(){return{config:this.config,diagnostics:this.diagnostics,memory:this.memoryStorage}}async storedBatches(){return await(this.sender??this.parkedSender)?.queueDepth()??0}flush(e){return this.flushFor(this.flushTimeout(e),!0)}async flushFor(e,t){S(this),t&&this.collectPoints();let n=this.idle();if(n)return n;let r=Date.now()+e,a,o=new Promise(t=>{let n=setTimeout(t,e);i.t(n),a=()=>{clearTimeout(n)}});try{return await this.flushBefore(r,o)}finally{a()}}async flushBefore(t,n){let r=this.heldRecords(),i=this.ready?this.senderLoad:this.started;if(i&&(!this.ready||!this.sender)&&!await Promise.race([i.then(()=>!0),n.then(()=>!1)]))return U({pending:this.waiting()});let{bus:a}=this,o=a?.getRole()===`forwarder`,s=this.idle();if(s)return s;if(o){let r=this.forwardBuffer.length,i=this.sendForwarded(),o=r-i,s=Math.floor(Math.max(0,t-Date.now())*e.it),c=await a.requestFlush(s,n);return c?{...c,forwarded:i,dropped:c.dropped+o}:U({forwarded:i,pending:i,dropped:o})}let{sender:c}=this;return c?U(await c.flushUntil(n)):this.rotating?U({pending:r+this.waiting()}):H(`complete`,{dropped:r})}idle(){return this.tunablesLocked&&this.config.enabled&&!this.destroyed?null:H(`inactive`,{pending:this.destroyed?0:this.waiting()})}heldRecords(){return this.bootBuffer.length+this.pendingRecords.length+this.forwardBuffer.length}waiting(){let e=this.heldRecords();for(let t of[this.sender,this.retiring]){let n=t?.stats();e+=n?n.pending+n.inFlight:0}return e}readOptions(e,t){if(typeof e!=`object`&&e!==void 0)this.diagnostics.report(`config.invalid`,t);else return this.diagnostics.guard(`config.invalid`,t,()=>({...e}))}flushTimeout(t){let n=this.readOptions(t,V);if(!n)return e.ot;let r=n.timeoutMs??5e3;return typeof r==`number`&&r>=0&&r<=6e5?r:(this.diagnostics.report(`config.invalid`,V),e.ot)}};o.t(G,`local`,null);function K(e,t,n=new WeakMap){if(Object.is(e,t))return!0;if(e instanceof RegExp&&t instanceof RegExp)return String(e)===String(t);if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let i=Object.keys(e),a=Object.keys(t);return i.length===a.length&&i.every(i=>r.t(t,i)&&K(Reflect.get(e,i),Reflect.get(t,i),n))}var q;function ht(t={}){if(q)return q;let n=new A(t.onDiagnostic);if(typeof document<`u`||typeof addEventListener!=`function`)return n.report(`config.invalid`,`Call serveTransportWorker() in a dedicated worker.`),()=>void 0;let i=!1,a,o,s=t=>{n.guard(`transport.http_error`,`The transport worker could not read its connection.`,()=>{let s=t.data;if(!r.n(s)||s.p!==`ui-observability.transport/1`||s.t!==e.ur.connect||t.ports.length===0)return;let c=t.ports[0];a||s.v!==`1.1.0`?(c.postMessage(e.lr),c.close()):(a=c,Promise.resolve().then(()=>require("./worker-server--yGTadTA.cjs")).then(e=>{i||(o=e.serveWorkerPort(c,n))}).catch(t=>{n.report(`transport.http_error`,`The transport worker delivery module could not load.`,void 0,t),n.guard(`transport.http_error`,`The failed transport port could not be closed.`,()=>{c.postMessage(e.lr),c.close()})}))})},c=()=>{i||(i=!0,q=void 0,removeEventListener(`message`,s),o?.(),n.guard(`transport.http_error`,`The transport service could not close its port.`,()=>{a?.postMessage(e.lr)}),n.guard(`transport.http_error`,`The transport port could not close.`,()=>{a?.close()}))};return addEventListener(`message`,s),q=c,c}function gt(){let e=[],t=[],n={status:200};return{transport:r=>(e.push(r),n.status>=200&&n.status<300&&t.push(r),Promise.resolve({...n})),records:()=>t.flatMap(e=>[...e.records]),batches:()=>[...e],clear:()=>{e.length=0,t.length=0},respondWith:(e,t)=>{n=t===void 0?{status:e}:{status:e,retryAfterMs:t}}}}var J=new Map;function Y(){return(G.current()??G.stopped())||G.configure({},!0)}function _t(e){G.configure(e),Z()}function vt(e){Y().setConfigurationLocked(e)}function yt(e,t){return Y().rotateSecurityContext(e,t)}async function X(){let e=Y();return Z(),{...await e.health(),loggerCache:{...e.config.loggerCache,size:J.size}}}async function bt(){let e=await X();return Y().debugBundle(e)}function Z(){let e=(G.current()??G.stopped())?.config.loggerCache.maxEntries,t=e===void 0?256:e;if(t!==null)for(let e of J.keys()){if(J.size<=t)break;J.delete(e)}return t}function xt(e,t){let n=Z();if(t||n===0)return new E(Y,e,t);let r=J.get(e);return r??=new E(Y,e),J.delete(e),J.set(e,r),Z(),r}function Q(){return xt(`app`)}function St(e,t){Q().trace(e,t)}function Ct(e,t){Q().debug(e,t)}function wt(e,t){Q().info(e,t)}function Tt(e,t){Q().warn(e,t)}function Et(e,t,n){Q().error(e,t,n)}function Dt(e,t,n){Q().fatal(e,t,n)}function Ot(e,t){Q().logAction(e,t)}function kt(e,t){Q().logEvent(e,t)}function $(t){G.current()?.diagnostics.report(`config.invalid`,e.St,void 0,t)}function At(e,t={}){return k(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function jt(e,t={}){return Ee(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function Mt(e,t={}){return De(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function Nt(e,t){return Y().startMeasure(e,t)}function Pt(e,t,n){let r=Y();return _e(r.startMeasure(e,n),t,r.diagnostics)}function Ft(){Y().setReplay(!0)}function It(){Y().setReplay(!1)}var Lt={probe:(e,t)=>c.t().probe(e,t,G.current()?.diagnostics),time:(e,t)=>c.t().time(e,t,G.current()?.diagnostics)};function Rt(e,t){Y().addBreadcrumb(e,t)}function zt(e){let t=Y();r.n(e)?t.diagnostics.guard(`record.sanitize_failed`,`The library could not read the values of setContext().`,()=>{t.context.merge(e)}):t.diagnostics.report(`config.invalid`,`setContext() takes an object. The library keeps the current context.`)}function Bt(e){Y().context.remove(e)}function Vt(e,t){return Y().journey.start(e,t)}function Ht(){Y().journey.end()}function Ut(){return Y().journey.current()}function Wt(){return Y().journey.getToken()}function Gt(e){return Y().journey.adopt(e,`manual`,!0)}function Kt(e,t){return Y().registerWorker(e,t)}function qt(e,t){return Y().registerFrame(e,t)}function Jt(){Y().tracing.rotate(`explicit`)}function Yt(){return Y().tracing.headers()}function Xt(e){return Y().flush(e)}function Zt(){Y().newSession()}function Qt(){return Y().diagnostics.snapshot()}async function $t(e){await(G.current()??G.stopped())?.destroy(e)}exports.addBreadcrumb=Rt,exports.adoptJourney=Gt,exports.collectDebugBundle=bt,exports.configure=_t,exports.counter=At,exports.createMemoryTransport=gt,exports.currentJourney=Ut,exports.debug=Ct,exports.endJourney=Ht,exports.error=Et,exports.fatal=Dt,exports.flush=Xt,exports.gauge=jt,exports.getDiagnosticCounters=Qt,exports.getHealth=X,exports.getJourneyToken=Wt,exports.getLogger=xt,exports.getTraceHeaders=Yt,exports.histogram=Mt,exports.info=wt,exports.logAction=Ot,exports.logEvent=kt,exports.measure=Pt,exports.newSession=Zt,exports.newTrace=Jt,exports.observeWindow=g.r,exports.profiler=Lt,exports.registerFrame=qt,exports.registerWorker=Kt,exports.removeContext=Bt,exports.rotateSecurityContext=yt,exports.serveTransportWorker=ht,exports.setConfigurationLocked=vt,exports.setContext=zt,exports.shutdown=$t,exports.startJourney=Vt,exports.startMeasure=Nt,exports.startReplay=Ft,exports.stopReplay=It,exports.trace=St,exports.warn=Tt;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-NtiQDWL_.cjs"),t=require("./log-record-Bdywwg0k.cjs"),n=require("./error-like-gGRx2s36.cjs"),r=require("./guards-EjG3ahFp.cjs"),i=require("./unref-CU9Nyz_9.cjs"),a=require("./platform-BZjp9wp1.cjs"),o=require("./defineProperty-X1c4tIPD.cjs"),s=require("./identity-BzAzdQyv.cjs"),c=require("./profiler-DpoPi1hH.cjs"),l=require("./library-console-DdIlzzph.cjs"),u=require("./sanitize-BZdhoghq.cjs"),d=require("./library-request-DO3Ec7KE.cjs"),f=require("./config-C0PtemvC.cjs"),p=require("./batch-C3uNp5kU.cjs"),m=require("./journey-BUmsrgaw.cjs"),h=require("./sampling-wAVJIZXp.cjs"),g=require("./observed-windows-BlE25nrn.cjs");var _=new WeakMap;function v(e){let t=e.idle;t!==void 0&&(e.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be cancelled.`,()=>{cancelIdleCallback(t)}),e.idle=void 0),clearTimeout(e.timer),e.timer=void 0}function y(t,n){typeof requestIdleCallback==`function`&&typeof cancelIdleCallback==`function`&&(n.idle=n.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be scheduled.`,()=>requestIdleCallback(e=>{b(t,n,e)},{timeout:e.q})),n.idle!==void 0)||(n.timer=setTimeout(()=>{b(t,n)},0),i.t(n.timer))}function b(e,t,n){if(_.get(e)!==t||t.draining)return;v(t),t.draining=!0;let r=t.work;t.work=[];let i=0;for(;i<r.length&&(!n||n.didTimeout&&i===0||n.timeRemaining()>0);)if(t.diagnostics.guard(`pipeline.crashed`,`The library could not build a deferred record.`,r[i]),i++,_.get(e)!==t)return;t.work=[...r.slice(i),...t.work],t.draining=!1,t.work.length>0?y(e,t):_.delete(e)}function x(t,n,r,i){let a=_.get(t),o=i===null?e.J:Math.min(i,e.J);if(a&&a.work.length>=o&&!a.draining&&(b(t,a),a=_.get(t)),a){if(a.work.length>=o){r.count(`record.dropped_by_ceiling`);return}a.work.push(n)}else a={work:[n],diagnostics:r,draining:!1},_.set(t,a),y(t,a)}function S(e){let t=_.get(e);t&&b(e,t)}function C(e){let t=_.get(e);if(t){v(t),_.delete(e);for(let e of t.work)t.diagnostics.count(`record.dropped_by_ceiling`);t.work=[]}}var w=[e.P,e.Yn,e.Y];function ee(e,t){let r=t.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>{if(!(e instanceof Error)&&!n.r(e))return;let t=Error(e.message);return t.name=e.name,t.stack=e.stack,t});if(r)return r;let i=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(i??typeof e)}function te(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function ne(e,t){if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return e;if(typeof e==`object`&&e)return t.guard(`record.sanitize_failed`,`The library could not read the properties of the error reason.`,()=>{let t=e,r=n.r(e),i={},a=0;for(let e of Object.keys(t)){let o=t[e];r&&n.t.has(e)||!n.n(o)||(i[e]=o,a++)}return a===0?void 0:i})}function re(e){if(!r.n(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function ie(e){return w.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function T(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var E=class n{constructor(e,t,n={}){o.t(this,`bind`,void 0),o.t(this,`namespace`,void 0),o.t(this,`options`,void 0),o.t(this,`levelType`,void 0),o.t(this,`trace`,(e,t)=>{this.write(`TRACE`,this.levelType,e,t)}),o.t(this,`debug`,(e,t)=>{this.write(`DEBUG`,this.levelType,e,t)}),o.t(this,`info`,(e,t)=>{this.write(`INFO`,this.levelType,e,t)}),o.t(this,`warn`,(e,t)=>{this.write(`WARN`,this.levelType,e,t)}),o.t(this,`error`,(e,t,n)=>{this.writeError(`ERROR`,e,t,n)}),o.t(this,`fatal`,(e,t,n)=>{this.writeError(`FATAL`,e,t,n)}),o.t(this,`logAction`,(e,t)=>{this.write(`INFO`,`action`,e,t)}),o.t(this,`logEvent`,(e,t)=>{this.write(`INFO`,`event`,e,t)}),this.bind=e,this.namespace=t,this.options=n,this.levelType=ie(t)}child(e,t={}){return new n(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...t.scopedContext}})}write(e,t,n,r){let i=this.bind();this.submit(i,e,t,a=>{this.writeNow(i,e,t,n,r,!1,a)})}submit(e,n,r,i){if(!e.isDestroyed()){if(e.isRotating())e.diagnostics.count(`record.dropped_during_rotation`);else if(e.config.payloadMode===`defer`&&e.config.enabled&&!e.config.debugBuffer.enabled&&this.namespace!==`uiobs.diagnostics`){if(!e.builder.isEnabled(n,this.namespace,r)&&!this.mirrors(e,n))return;let o=e.journey.current(),s={timeUnixNano:t.r(),trace:e.tracing.resolve(),journey:o?{...o}:null,context:e.context.getAll(),url:a.t(e.diagnostics)};x(e,()=>{i(s)},e.diagnostics,e.config.buffering.maxPendingRecords)}else i()}}writeNow(e,t,n,r,i,a,o){if(!(e.config.enabled&&e.config.debugBuffer.enabled)&&!e.builder.isEnabled(t,this.namespace,n)){this.mirrors(e,t)&&this.print(e,t,r,i,void 0,null,void 0,o);return}let s={snapshot:o,level:t,type:n,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:a?i:T(i,e.diagnostics)},{record:c,dropped:l}=e.builder.build(s),u=!!e.config.redact||e.config.processors.length>0,d=n!==`metric`&&e.config.captureLimits.breadcrumbs>0,f=l===`sampling`&&u&&d?e.builder.build(s,!0):void 0,p=c??f?.record??null,m=p?p.body:l===`sampling`&&!u?r:void 0;d&&m!==void 0&&e.breadcrumbs.push({t:o?Number(o.timeUnixNano.slice(0,-6)):Date.now(),category:n===`action`?`action`:n===`event`?`event`:`log`,message:m}),this.print(e,t,r,i,void 0,p,f?.dropped??l,o),e.emit(c)}writeError(e,t,n,r){let i=this.bind();this.submit(i,e,this.levelType,a=>{this.writeErrorNow(i,e,t,n,r,a)})}writeErrorNow(t,n,r,i,a,o){let s=t.builder.isEnabled(n,this.namespace);if(!s&&!this.mirrors(t,n))return;let c=a===void 0&&(t.diagnostics.guard(`record.sanitize_failed`,`The library could not read the error slot.`,()=>re(i))??!1),l=c?i:a,u=c?void 0:i,d=u===void 0?void 0:ee(u,t.diagnostics),f=d===void 0?void 0:te(u,d,t.diagnostics);if(!s){this.print(t,n,r,l,f,null,void 0,o);return}let p=d?ne(u,t.diagnostics):void 0,{record:m,dropped:h}=t.builder.build({snapshot:o,level:n,type:this.levelType,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(l,t.diagnostics),...d?{"error.type":d.name,"error.message":d.message,"error.stack_trace":d.stack}:{},...p===void 0?{}:{[e.d]:p},[e.c]:t.breadcrumbs.snapshot()}});this.print(t,n,r,l,f,m,h,o),t.emit(m)}print(e,t,n,r,i,a,o,s){if(!e.config.redact&&e.config.processors.length===0){e.console.write(this.namespace,t,n,r,i);return}if(a){e.console.write(this.namespace,t,a.body,a.attributes);return}if(o===`processor`||o===`redact`||o===`malformed`||!e.config.enabled||!e.console.accepts(t))return;let c=e.builder.build({snapshot:s,level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(r,e.diagnostics),...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{}}},!0).record;c&&e.console.write(this.namespace,t,c.body,c.attributes)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},ae=class extends E{constructor(...t){super(...t),o.t(this,`logMetric`,(t,n,r=e.K,i=`gauge`,a,o)=>{if(!Number.isFinite(n)){this.bind().diagnostics.report(`record.dropped_malformed`,`The metric value is not a finite number. The library dropped the metric.`,{"metric.name":t});return}let s=this.bind();this.submit(s,`INFO`,`metric`,c=>{let l=T(a,s.diagnostics),u={...T(o,s.diagnostics),...l,"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,[e.Bt.attributeKeys]:Object.keys(l)};this.writeNow(s,`INFO`,`metric`,t,u,!0,c)})})}},oe=/^[0-9a-f]{32}$/,se=/^[0-9a-f]{16}$/,D=/[1-9a-f]/;function ce(e){return oe.test(e.traceId)&&D.test(e.traceId)&&se.test(e.spanId)&&D.test(e.spanId)}function le(){return s.o(16)}function O(){return s.o(8)}function ue(e){return{traceId:le(),spanId:O(),traceFlags:1,startedAt:Date.now(),reason:e,ended:!1}}function de(e,t,n){return`00-${e}-${t}-${(n&255).toString(16).padStart(2,`0`)}`}function fe(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var pe=class{constructor(t,n=e.or,r,i){o.t(this,`diagnostics`,void 0),o.t(this,`maxAgeMs`,void 0),o.t(this,`load`,void 0),o.t(this,`spans`,void 0),o.t(this,`ambient`,ue(`start`)),o.t(this,`otel`,void 0),this.diagnostics=t,this.maxAgeMs=n,this.load=r,this.spans=i}setup(e,t){this.maxAgeMs=e,this.load=t}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){return this.activeSpanContext()??this.ambientContext()}ambientContext(){return Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),fe(this.ambient)}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(ce(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){let t=this.ambient;this.ambient=ue(e);let n=fe(this.ambient);return this.finish(t),n}end(){this.finish(this.ambient)}finish(e){e.ended||(e.ended=!0,this.spans?.onEnd({traceId:e.traceId,spanId:e.spanId,reason:e.reason,startedAt:e.startedAt,endedAt:Date.now()}))}headers(){return this.trace(!1).headers}request(){return this.trace(!0)}trace(t){let n={},r=this.otel;if(r&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{r.propagation.inject(r.context.active(),n)}),n.traceparent)return{headers:n};let i=this.activeSpanContext(),a=i??this.ambientContext(),o=i?void 0:this.spans;if(!o?.enabled())return n[e.ar]=de(a.traceId,a.spanId,a.traceFlags),{headers:n};let s=o.keeps(a.traceId),c=s?a.traceFlags:a.traceFlags&-2,l=t?O():a.spanId;return n[e.ar]=de(a.traceId,l,c),!t||!s?{headers:n}:{headers:n,span:{traceId:a.traceId,spanId:l,parentSpanId:a.spanId}}}},me={name:`ui.measure.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Rt},he={name:`ui.measure.phase.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Rt};function ge(e,t,n,r){let i=String(e),a=Date.now(),o=performance.now(),s,c=!1,l=e=>a+e-o,u=(e,a)=>{s&&=(r.metric(he,e-s.at,{...t,"measure.name":i,"measure.phase":s.name}),n&&r.span({name:s.name,kind:`internal`,traceId:n.traceId,spanId:O(),parentSpanId:n.spanId,startMs:l(s.at),endMs:l(e),error:a,attributes:{"measure.name":i}}),void 0)};return{phase:e=>{if(c)return;let t=performance.now();u(t,!1),s={name:String(e),at:t}},end:(e=`ok`)=>{if(c)return;c=!0;let s=performance.now(),d=e===`error`;u(s,d);let f={...t,"measure.outcome":e};r.metric(me,s-o,{...f,"measure.name":i}),n&&r.span({...n,name:i,kind:`internal`,startMs:a,endMs:l(s),error:d,attributes:f})}}}function _e(e,t,n){let r=`error`;try{let i=t(),a=n.guard(`record.sanitize_failed`,`The library could not read what the function of the measure returned. The measure ends now.`,()=>i?.then);if(typeof a!=`function`)return r=`ok`,i;let o=a.call(i,t=>(e.end(),t),t=>{throw e.end(`error`),t});return r=void 0,o}finally{r!==void 0&&e.end(r)}}var ve=`overflow`,ye=new Set([e.g,e.h,e.a,e.v,e.f,e.p,e.m]);function be(e={}){let t={};for(let n of Object.keys(e).sort()){if(n.startsWith(`metric.`)||ye.has(n))continue;let r=e[n];(typeof r==`string`||typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r)}return t}function xe(e,t){if(!Array.isArray(e))return null;let n=t===null?e.length:Math.min(e.length,t+1);return Array.from({length:n},(t,n)=>e[n])}function Se(e,t){return Array.isArray(e)&&(t===null||e.length<=t)&&e.every((t,n)=>typeof t==`number`&&Number.isFinite(t)&&(n===0||t>e[n-1]))}function Ce(t,n,r){let i={"metric.name":t.name,"metric.unit":t.unit,"metric.type":t.kind,[e.Bt.start]:r,[e.Bt.attributeKeys]:Object.keys(n.attributes)};return t.kind===`histogram`?{...i,[e.Bt.count]:n.count,[e.Bt.sum]:n.sum,[e.Bt.min]:n.min,[e.Bt.max]:n.max,[e.Bt.bounds]:t.boundaries,[e.Bt.buckets]:n.buckets}:(i[`metric.value`]=t.kind===`gauge`?n.last:n.sum,i)}function we(e,t){try{return{unit:e.unit,boundaries:e.boundaries}}catch(e){return t(e),{unit:void 0,boundaries:void 0}}}function Te(e,t,n,r){return{name:e,kind:t,unit:we(n,r).unit??`count`,boundaries:[]}}function k(e,t,n,r){let i=Te(e,`counter`,t,r);return{add:(e,t)=>{n(i,e,t)}}}function Ee(e,t,n,r){let i=Te(e,`gauge`,t,r);return{set:(e,t)=>{n(i,e,t)}}}function De(t,n,r,i){let{unit:a,boundaries:o}=we(n,i),s={name:t,kind:`histogram`,unit:a??`count`,boundaries:o??e.Rt,fromApp:o!==void 0};return{record:(e,t)=>{r(s,e,t)}}}var Oe=class{constructor(e,t,n,r={maxSeries:100,maxInstruments:1e3,maxHistogramBoundaries:50}){o.t(this,`intervalMs`,void 0),o.t(this,`emit`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`policy`,void 0),o.t(this,`instruments`,new Map),o.t(this,`timer`,null),o.t(this,`startedAt`,0),this.intervalMs=e,this.emit=t,this.diagnostics=n,this.policy=r}record(e,t,n){!Number.isFinite(t)||e.kind===`counter`&&t<0?this.diagnostics.report(`record.dropped_malformed`,`The value of the metric ${e.name} is not valid. The library dropped it.`,{"metric.name":e.name}):this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the metric ${e.name}.`,()=>{let r=this.instrumentOf(e);r&&(this.add(r,t,be(n)),this.arm())})}collect(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let e=`${String(this.startedAt)}000000`,t=[...this.instruments.values()];this.instruments.clear();for(let{def:n,series:r}of t)for(let t of r.values())this.emit(n.name,t.attributes,Ce(n,t,e))}instrumentOf(t){let n=this.instruments.get(t.name);if(n)return n.def.kind===t.kind?n:(this.diagnostics.report(`record.dropped_malformed`,`The metric ${t.name} is a ${n.def.kind} and a ${t.kind}. The library dropped the value.`,{"metric.name":t.name}),null);let{maxInstruments:r}=this.policy;if(r!==null&&this.instruments.size>=r)return this.diagnostics.count(`record.dropped_by_ceiling`),null;let i=t.fromApp===!0?this.policy.maxHistogramBoundaries:null,a=xe(t.boundaries,i),o=Se(a,i);t.kind===`histogram`&&!o&&this.diagnostics.report(`config.invalid`,`The boundaries of the metric ${t.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`);let s={def:{...t,boundaries:o?a:[...e.Rt]},series:new Map};return this.instruments.set(t.name,s),s}add(t,n,r){let i=JSON.stringify(r),a=t.series.get(i),o=r,{maxSeries:s}=this.policy;if(!a&&s!==null&&t.series.size>=s&&(i=ve,a=t.series.get(i),o={[e._]:!0}),!a){let e=t.def.kind===`histogram`?t.def.boundaries.length+1:0,r=Array(e).fill(0);a={attributes:o,count:0,sum:0,min:n,max:n,last:n,buckets:r},t.series.set(i,a)}if(a.count+=1,a.sum+=n,a.min=Math.min(a.min,n),a.max=Math.max(a.max,n),a.last=n,a.buckets.length>0){let e=t.def.boundaries.findIndex(e=>n<=e);a.buckets[e===-1?a.buckets.length-1:e]+=1}}arm(){this.timer===null&&(this.startedAt=Date.now(),this.timer=setTimeout(()=>{this.collect()},this.intervalMs()),i.t(this.timer))}},ke={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},Ae=class{constructor(t,n,r=e.un){o.t(this,`settings`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`limits`,void 0),this.settings=t,this.diagnostics=n,this.limits=r}update(e){this.settings=e}accepts(t){return this.settings.level===null||!r.t(e.At,this.settings.level)?!1:e.At[t]>=e.At[this.settings.level]}write(e,t,n,r,i){if(!this.accepts(t)||typeof console>`u`||l.t())return;let a=`%c[%s]%c[${t}]%c`,{styles:o}=this.settings,s=ke[t];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${s}.`,()=>{let c=[];i!==void 0&&c.push(i),r!==void 0&&c.push(u.n(r,this.limits,this.diagnostics)),l.n(()=>{console[s](a,o.namespace,e,o[t],``,n,...c)})})}},je=class{constructor(){o.t(this,`value`,0)}next(){return++this.value}},Me=class{constructor(e){o.t(this,`buffer`,void 0),o.t(this,`pointer`,0),o.t(this,`filled`,!1),o.t(this,`capacity`,void 0),this.capacity=e===0?0:Math.max(e,1),this.buffer=Array(this.capacity)}resize(e){let t=this.snapshot().slice(-e);if(this.capacity=e,this.buffer=Array(e),this.pointer=0,this.filled=!1,e)for(let e of t)this.push(e)}push(e){this.capacity!==0&&(this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0))}retain(e){let t=this.snapshot().filter(e);this.clear();for(let e of t)this.push(e)}clear(){this.buffer.fill(void 0),this.pointer=0,this.filled=!1}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}},Ne=class{constructor(){o.t(this,`map`,new Map)}merge(e){for(let[t,n]of Object.entries(e))n===null?this.map.delete(t):n!==void 0&&this.map.set(t,n)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},Pe=class{constructor(e){o.t(this,`policy`,void 0),o.t(this,`kept`,[]),this.policy=e}push(e){let{enabled:t,maxRecords:n}=this.policy();t&&(this.kept.push({at:Date.now(),record:e}),this.kept.length>=n*2&&(this.kept=this.kept.slice(-n)))}drain(){let t=this.live();return this.kept=[],t.map(({record:t})=>({...t,attributes:{...t.attributes,[e.u]:!0}}))}snapshot(){return this.live().map(({record:e})=>e)}live(){let{enabled:e,maxRecords:t,maxAgeMs:n}=this.policy();if(!e)return this.kept=[],[];let r=n===null?-1/0:Date.now()-n;return this.kept.slice(-t).filter(e=>e.at>=r)}clear(){this.kept=[]}},A=class{constructor(t,n=e.X,r=!1){o.t(this,`handler`,void 0),o.t(this,`throttleMs`,void 0),o.t(this,`consoleFallback`,void 0),o.t(this,`counters`,new Map),o.t(this,`lastEmitted`,new Map),this.handler=t,this.throttleMs=n,this.consoleFallback=r}setPolicy(e,t){this.throttleMs=e,this.consoleFallback=t}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return!1;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a},{handler:c}=this;if(!c)return!0;try{l.n(()=>{c(s)})}catch{this.count(`handler.threw`),this.consoleFallback&&typeof console<`u`&&l.n(()=>{console.warn(`${e.Mt} The onDiagnostic handler threw an error.`)})}return!0}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}};function j(e,t){e.length<20&&!e.includes(t)&&e.push(t)}var Fe=class{constructor(e,t){o.t(this,`config`,void 0),o.t(this,`diagnostics`,void 0),o.t(this,`pending`,new Map),o.t(this,`scheduled`,!1),o.t(this,`reporting`,!1),o.t(this,`lost`,{}),this.config=e,this.diagnostics=t}add(t,n,r=[],i=n.length){if(i>0&&(this.lost[t]=(this.lost[t]??0)+i),!this.config.onDrop||this.reporting||n.length===0&&r.length===0)return;let a=this.pending.get(t);a||(a={reason:t,records:0,batchIds:[],journeyIds:[],actions:[]},this.pending.set(t,a)),a.records+=i;for(let e of r)j(a.batchIds,e);for(let t of n){let n=p.t(t,e.f);typeof n==`string`&&j(a.journeyIds,n);let r=p.r(t)?t.body:void 0;typeof r==`string`&&j(a.actions,r)}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.flush()}))}counts(){return{...this.lost}}flush(){this.scheduled=!1;let e=[...this.pending.values()];this.pending.clear();let t=this.config.onDrop;if(t){this.reporting=!0;for(let n of e)this.diagnostics.guard(`handler.threw`,`The onDrop hook threw an error.`,()=>{d.r(()=>{l.n(()=>{t(n)})})});this.reporting=!1}}},Ie=class{constructor(e){o.t(this,`onDrop`,void 0),o.t(this,`actions`,{head:[],tail:[]}),o.t(this,`others`,{head:[],tail:[]}),o.t(this,`arrivals`,0),this.onDrop=e}get records(){return this.inOrder()}get length(){let{actions:e,others:t}=this;return e.head.length+e.tail.length+t.head.length+t.tail.length}push(t,n){let r=p.r(t),i=r?this.actions:this.others,a=r?e.j:n,o={record:t,arrival:this.arrivals};if(this.arrivals+=1,i.head.length<100)i.head.push(o);else if(i.tail.push(o),i.head.length+i.tail.length>a){let e=i.tail[0];i.tail.shift(),this.onDrop(e.record)}}take(){let e=this.inOrder();return this.actions={head:[],tail:[]},this.others={head:[],tail:[]},this.arrivals=0,e}inOrder(){let{actions:e,others:t}=this;return[...e.head,...e.tail,...t.head,...t.tail].sort((e,t)=>e.arrival-t.arrival).map(e=>e.record)}},Le=`error.`,Re=[e.v,e.f,e.p],ze={processor:{label:`A processor`,code:`record.dropped_by_processor`,refused:`processors is not a list of functions. The library drops each record until processors is a list of functions or [].`},redact:{label:`The redact hook`,code:`record.dropped_by_redact`,refused:`redact is not a function. The library drops each record until redact is a function or null.`}},M=e=>typeof e==`number`&&Number.isFinite(e),N=e=>Array.isArray(e)&&e.every(M),P=e=>typeof e==`string`&&/^\d{1,20}$/.test(e),Be=e=>typeof e==`string`&&/^[0-9a-f]{32}$/.test(e),Ve=e=>typeof e==`string`&&/^[0-9a-f]{16}$/.test(e),He=e=>e===``||Ve(e),Ue=e=>e===`counter`,We=e=>e===`histogram`,Ge=e=>e===`client`||e===`internal`,Ke=e=>e===`error`||e===`unset`,qe={"metric.type":Ue,"metric.value":M,[e.Bt.start]:P},Je={"metric.type":We,[e.Bt.start]:P,[e.Bt.count]:M,[e.Bt.sum]:M,[e.Bt.min]:M,[e.Bt.max]:M,[e.Bt.bounds]:N,[e.Bt.buckets]:N},Ye={[e.Kn.kind]:Ge,[e.Kn.parentId]:He,[e.Kn.start]:P,[e.Kn.end]:P,[e.Kn.status]:Ke},Xe={[e.Kn.linkTraceId]:Be,[e.Kn.linkSpanId]:Ve};function Ze(t){let n=t[e.g],r=t[e.a];return n===`span`&&r===`uiobs.traces`?[Ye,Xe]:n!==`metric`||r!==`uiobs.metrics`?[]:t[`metric.type`]===`histogram`?[Je]:[qe]}function Qe(e){let t={};for(let n of Ze(e)){let r=Object.keys(n);if(r.every(t=>n[t](e[t])))for(let n of r)t[n]=e[n]}return t}function F(e){return e}var $e=class{constructor(e){o.t(this,`deps`,void 0),o.t(this,`resourceCache`,null),this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(e,t,n){return this.deps.config.enabled&&this.passesLevel(e,t,n)}passesLevel(t,n,r){let{config:i}=this.deps;if(r!==void 0&&e.kt.includes(r))return!0;let a=this.deps.remote.sampling?.minLevelFor(n)??h.n(n,i);return e.At[t]>=e.At[a]}keepForDebug(e){let{config:t,debug:n}=this.deps;if(!n||!t.enabled||!t.debugBuffer.enabled)return;let{record:r}=this.build(e,!0);r&&n.push(r)}build(n,r=!1){let{config:i,diagnostics:o,tracing:s,journey:c,sequence:l,limits:d,remote:f}=this.deps;if(!r&&!this.isEnabled(n.level,n.namespace,n.type))return o.count(`record.dropped_by_level`),this.keepForDebug(n),{record:null,dropped:`level`};let p=n.trace??n.snapshot?.trace??s.resolve(),m=n.snapshot?n.snapshot.journey:c.current(),g=h.o({level:n.level,type:n.type,namespace:n.namespace,journeyId:m?.id??``,traceId:p.traceId,aggregated:n.aggregated},i,f.sampling?.current()??null);if(!r&&!g)return o.count(`record.dropped_by_sampling`),this.keepForDebug(n),{record:null,dropped:`sampling`};let _=l.next(),v=n.snapshot?.url??a.t(o),y=i.metadata.pageUrl?a.a(v,i.capture.fullUrls,i.capture.urlTransform,o):``,b,x=0;try{let e=u.r(n.snapshot?.context??this.deps.context.getAll(),d,o),t=u.r(this.provided(),d,o),r=u.r(n.scoped??{},d,o),i=u.r(n.payload??{},d,o);x=e.bytes+t.bytes+r.bytes+i.bytes,b={...F(e.value),...F(t.value),...F(r.value),...F(i.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),b={[e.y]:!0}}Object.assign(b,n.fixed),b[e.g]=n.type,b[e.h]=_,b[e.a]=n.namespace,b[e.v]=y,m&&(b[e.f]=m.id,b[e.p]=m.name,m.parentId!==void 0&&(b[e.m]=m.parentId));let S=u.i(n.body,d.maxBodyChars);S!==n.body&&o.count(`record.truncated`);let C={timeUnixNano:n.snapshot?.timeUnixNano??t.r(),traceId:p.traceId,spanId:p.spanId,traceFlags:p.traceFlags,severityNumber:e.Gn[n.level],severityText:n.level,body:S,attributes:b,resource:this.resource()},w=this.hookStages();if(w.length>0){let e=this.applyHooks(C,w,n.fixed);if(typeof e==`string`)return{record:null,dropped:e};({record:C,bytes:x}=e)}let ee={[e.g]:n.type,[e.h]:_,[e.a]:n.namespace};return{record:this.fit(C,x,ee,n.fixed)}}redactForwarded(e){let{config:t,diagnostics:n,limits:r}=this.deps,i=Qe(e.attributes),a=Math.max(r.maxAttributeCount,128),o={...r,maxAttributeCount:a},s=F(u.r(e.resource,o,n).value),c=t.redact?[[t.redact,`redact`]]:[],l=this.applyHooks({...e,resource:s},c,i);return typeof l==`string`?null:l.record}rehook(t){let{config:n,diagnostics:r,limits:i,remote:o,debug:s}=this.deps,{attributes:c}=t,l=String(c[e.a]),d=this.passesLevel(t.severityText,l,c[e.g]),f=d&&h.a(t,n,o.sampling?.current()??null),p=n.metadata.pageUrl?a.a(String(c[e.v]),n.capture.fullUrls,n.capture.urlTransform,r):``,m=u.i(t.body,i.maxBodyChars);m!==t.body&&r.count(`record.truncated`);let g=Qe(c),_={...t,body:m,attributes:{...c,[e.v]:p},resource:this.resource()},v=this.applyHooks(_,this.hookStages(),g),y=typeof v==`string`?null:this.fit(v.record,v.bytes,c,g);return f?y:(r.count(d?`record.dropped_by_sampling`:`record.dropped_by_level`),y&&s&&n.enabled&&n.debugBuffer.enabled&&s.push(y),null)}fit(t,n,r,i){let{diagnostics:a,limits:o}=this.deps;if(n<=o.maxRecordBytes)return t;a.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped the caller attributes.`,{bytes:n,body:t.body});let s={[e.g]:r[e.g],[e.h]:r[e.h],[e.a]:r[e.a],[e.s]:!0,[e.o]:n};for(let e of Re)e in t.attributes&&(s[e]=t.attributes[e]);for(let[e,n]of Object.entries(t.attributes))e.startsWith(Le)&&(s[e]=n);let c=u.r(s,o,a).bytes;c>o.maxRecordBytes&&`error.data`in s&&(Reflect.deleteProperty(s,e.d),c=u.r(s,o,a).bytes);let l=t.attributes[e.c];if(l!==void 0){let t=u.r(l,o,a).bytes;c+t<=o.maxRecordBytes&&(s[e.c]=l)}return Object.assign(s,i),t.attributes=s,t}hookStages(){let{processors:e,redact:t}=this.deps.config,n=e.map(e=>[e,`processor`]);return t&&n.push([t,`redact`]),n}applyHooks(e,t,n){let r=e;for(let[e,n]of t){let t=this.runHook(e,n,r);if(typeof t==`string`)return t;r=t}let{diagnostics:i,limits:a}=this.deps,o=u.r(r.attributes,a,i),s=F(o.value);return Object.assign(s,n),{record:{...r,attributes:s},bytes:o.bytes}}runHook(n,r,i){let{diagnostics:a}=this.deps,{label:o,code:s,refused:c}=ze[r],l;try{l=n(i)}catch(e){return a.report(s,`${o} threw an error. The library dropped the record.`,void 0,e),r}if(l===null)return n===f.t?a.report(s,c):a.count(s),r;let u=l??i;return t.n(u)?t.t(u.severityText)?{...u,severityNumber:e.Gn[u.severityText]}:(a.report(`record.dropped_malformed`,`${o} set a severityText that is not a log level. The library dropped the record.`),`malformed`):u===i?(a.report(`record.dropped_malformed`,`${o} changed the record to a shape that is not a record. The library dropped it.`),`malformed`):(a.report(s,`${o} returned a value that is not a record. The library dropped the record.`),r)}provided(){let e=this.deps.config.contextProvider;if(!e)return{};let{diagnostics:t}=this.deps,n=t.guard(`handler.threw`,`The contextProvider threw an error. The record has no attributes from it.`,()=>{let t=e();return t===void 0?{}:r.n(t)&&typeof t.then!=`function`?t:null});return n===null&&t.report(`config.invalid`,`contextProvider must return an object of attributes. The library ignores the value.`),n??{}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.wn]:t.serviceName,[e.Tn]:t.serviceVersion,[e.bn]:t.environment,[e.An]:e.rr,[e.jn]:e.ir,[e.kn]:e.nr,[e.xn]:r.platform,[e.En]:n.sessionId,[e.On]:n.tabId,[e.yn]:n.contextId,...t.metadata.userAgent?{[e.vn]:r.userAgent}:{},...!t.metadata.openfin||r.openfinUuid===void 0?{}:{[e.Cn]:r.openfinUuid},...!t.metadata.openfin||r.openfinName===void 0?{}:{[e.Sn]:r.openfinName}},this.resourceCache}},et=1e3,tt={start:`ui.start`,interaction:`ui.interaction`,navigation:`ui.navigation`,explicit:`ui.trace`,maxAge:`ui.trace`};function nt(e){return`${String(Math.round(e*et))}000`}function rt(e){return{name:tt[e.reason],kind:`internal`,traceId:e.traceId,spanId:e.spanId,parentSpanId:``,startMs:e.startedAt,endMs:e.endedAt,error:!1,attributes:{}}}function it(t){return{[e.Kn.kind]:t.kind,[e.Kn.parentId]:t.parentSpanId,[e.Kn.start]:nt(t.startMs),[e.Kn.end]:nt(t.endMs),[e.Kn.status]:t.error?`error`:`unset`,...t.link?{[e.Kn.linkTraceId]:t.link.traceId,[e.Kn.linkSpanId]:t.link.spanId}:{}}}var at={errors:async()=>(await Promise.resolve().then(()=>require("./errors-07pmZ7VY.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-BNHBI0Fc.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-BXzEel4F.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-Df4Wsfx9.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-D9DfSWqv.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-Dk6GH4yj.cjs"))).ConsoleCapture,uncleanExit:async()=>(await Promise.resolve().then(()=>require("./unclean-exit-CuBh-ee5.cjs"))).UncleanExitCapture,userTiming:async()=>(await Promise.resolve().then(()=>require("./user-timing-BWqzYF2Q.cjs"))).UserTimingCapture,reports:async()=>(await Promise.resolve().then(()=>require("./reports-CGK9YQch.cjs"))).ReportCapture,resourceTiming:async()=>(await Promise.resolve().then(()=>require("./resource-timing-DalulXiR.cjs"))).ResourceTimingCapture,lifecycle:async()=>(await Promise.resolve().then(()=>require("./lifecycle-B5yfH5is.cjs"))).LifecycleCapture,framePhases:async()=>(await Promise.resolve().then(()=>require("./profiler-frames-C9zJNd8_.cjs"))).FramePhasesCapture,framePacing:async()=>(await Promise.resolve().then(()=>require("./profiler-frames-C9zJNd8_.cjs"))).FramePacingCapture,replay:async()=>(await Promise.resolve().then(()=>require("./replay-Cab-lSit.cjs"))).ReplayCapture},ot=new WeakMap,st=0;function I(e){let t=ot.get(e);return t===void 0&&(t=++st,ot.set(e,t)),t}var L=Symbol.for(e.In),R=Symbol.for(e.Ln),ct=[`batching`,`retention`],lt=[`log`,`event`,`action`],z=`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.`,B=`shutdown() got invalid options. The library discards the records in memory. An invalid clearStorage removes the "context" scope.`,V=`flush() got invalid options. The library waits the default 5000 ms.`,ut=new Set([`bus.role_resolved`,`bus.tab_id_changed`,`config.reconfigured`,`security.rotated`,`journey.adopted`,`journey.expired`]);function dt(e){return JSON.stringify({...e,urlTransform:e.urlTransform?I(e.urlTransform):void 0,webVitals:typeof e.webVitals==`object`?{loader:e.webVitals.loader!==void 0}:e.webVitals,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String),userTiming:typeof e.userTiming==`object`?{include:e.userTiming.include?.map(String)}:e.userTiming,plugins:e.plugins.map(I)})}function ft(e){if(!r.n(e))return e;let t={...e};for(let e of[`url`,`endpoint`]){let n=t[e];typeof n==`string`&&(t[e]=a.a(n,!1))}return t}function pt(e){return{...e,endpoint:null,metricsEndpoint:null,tracesEndpoint:null,transport:null,transportOnExit:null,transportWorker:null,bus:{...e.bus,mode:`off`}}}function mt(e){return!!e.endpoint||!!e.metricsEndpoint||!!e.tracesEndpoint||!!e.transport||!!e.transportWorker}function H(e,t){return{status:e,accepted:0,stored:0,dropped:0,forwarded:0,pending:0,...t}}function U(e){return H(e.pending>0?`timeout`:`complete`,e)}function W(t){return t.sdkVersion===e.ir}var G=class n{isRotating(){return this.rotating}setConfigurationLocked(e){typeof e==`boolean`&&(this.config.lockConfiguration=e)}constructor(t,n){o.t(this,`rotating`,!1),o.t(this,`rotationSeq`,0),o.t(this,`profilerOn`,!1),o.t(this,`closingContext`,!1),o.t(this,`mismatchVersion`,null),o.t(this,`contextMismatch`,!1),o.t(this,`rotation`,void 0),o.t(this,`memoryStorage`,void 0),o.t(this,`storagePersistence`,`off`),o.t(this,`recordingDiagnostic`,!1),o.t(this,`holdingRecords`,!1),o.t(this,`heldDiagnostics`,[]),o.t(this,`diagnosticLogger`,new E(()=>this,e.Y)),o.t(this,`debugBuffer`,new Pe(()=>this.config.debugBuffer)),o.t(this,`explicitSecurityContext`,void 0),o.t(this,`ownerAdopted`,!1),o.t(this,`sdkVersion`,e.ir),o.t(this,`protocol`,e.M),o.t(this,`diagnostics`,void 0),o.t(this,`config`,void 0),o.t(this,`platform`,void 0),o.t(this,`identity`,void 0),o.t(this,`backing`,s.r()),o.t(this,`stores`,{local:()=>this.backing.local(),session:()=>this.backing.session(),opener:()=>this.backing.opener?.()??null}),o.t(this,`identityBuiltAs`,void 0),o.t(this,`sessionTouch`,void 0),o.t(this,`context`,new Ne),o.t(this,`breadcrumbs`,void 0),o.t(this,`tracing`,void 0),o.t(this,`sequence`,new je),o.t(this,`journey`,void 0),o.t(this,`builder`,void 0),o.t(this,`remote`,{sampling:null,changed:()=>{this.refreshCaptures()}}),o.t(this,`identityEpoch`,0),o.t(this,`errorHook`,void 0),o.t(this,`replayConsent`,void 0),o.t(this,`replay`,void 0),o.t(this,`remoteCaptureTimer`,void 0),o.t(this,`installedCaptureKey`,``),o.t(this,`replayBuiltKey`,``),o.t(this,`console`,void 0),o.t(this,`drops`,void 0),o.t(this,`meter`,void 0),o.t(this,`bus`,null),o.t(this,`busBuilt`,void 0),o.t(this,`busLoad`,void 0),o.t(this,`sender`,void 0),o.t(this,`senderLoad`,void 0),o.t(this,`pendingRecords`,new Ie(e=>{this.dropHeld(e)})),o.t(this,`pausedLoss`,new WeakSet),o.t(this,`carried`,[]),o.t(this,`sessionPicked`,!1),o.t(this,`deliveryClosed`,!1),o.t(this,`parkedSender`,void 0),o.t(this,`retiring`,void 0),o.t(this,`startFailed`,!1),o.t(this,`running`,!1),o.t(this,`openGate`,void 0),o.t(this,`startGate`,new Promise(e=>{this.openGate=e})),o.t(this,`captures`,[]),o.t(this,`captureGeneration`,0),o.t(this,`captureOnce`,{webVitals:!1,navigationTiming:!1,longFrames:!1,uncleanExit:!1,userTiming:!1}),o.t(this,`bootBuffer`,new Ie(e=>{this.dropHeld(e)})),o.t(this,`forwardBuffer`,[]),o.t(this,`forwardScheduled`,!1),o.t(this,`roleResolved`,!1),o.t(this,`started`,Promise.resolve()),o.t(this,`ready`,!1),o.t(this,`destroyed`,!1),o.t(this,`stopping`,void 0),o.t(this,`lastSendAt`,null),o.t(this,`lastGapAt`,0),o.t(this,`limits`,void 0),o.t(this,`journeyOptions`,void 0),o.t(this,`tunablesLocked`,!1),o.t(this,`degraded`,void 0),o.t(this,`serverReported`,!1),o.t(this,`onPageHide`,()=>{S(this),this.dropPaused(),this.role()===`forwarder`&&(this.tracing.end(),this.sendForwarded())}),o.t(this,`busCanAccept`,(e,t)=>this.bus?.isRegistered(e,t)??!1),o.t(this,`busAccept`,(e,t,n)=>{this.destroyed||this.ensureBus().then(r=>{r&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{r.acceptDirect(e,t,n)})})}),o.t(this,`reportLoss`,(e,t,n,r)=>{this.drops.add(e,t,n,r)}),o.t(this,`reportGap`,(t,n)=>{this.drops.add(t.reason,n.flatMap(e=>e.records),n.map(e=>e.id));let r=Date.now();r-this.lastGapAt<6e4||(this.lastGapAt=r,new E(()=>this,e.Yn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))}),this.diagnostics=new A(typeof t.onDiagnostic==`function`?t.onDiagnostic:void 0),this.platform=a.n(this.diagnostics),this.degraded=n||this.onServer(),this.config=f.r(this.allowed(t),this.diagnostics),this.explicitSecurityContext=!!t.securityContext?.id,this.config.securityContext.id||=s.i(this.diagnostics),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.identityBuiltAs=this.config.identity,this.identity=s.s(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.sessionTouch=new s.n(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.breadcrumbs=new Me(this.config.captureLimits.breadcrumbs);let r=e=>h.i(e,this.config.sampling.defaultRate);this.tracing=new pe(this.diagnostics,this.config.correlation.traceMaxAgeMs??1/0,this.config.otelLoader,{enabled:()=>this.config.tracesEndpoint!==null,keeps:r,onEnd:e=>{r(e.traceId)&&this.recordSpan(rt(e))}}),this.limits={...this.config.limits},this.console=new Ae(this.config.consoleOutput,this.diagnostics,this.limits),this.drops=new Fe(this.config,this.diagnostics),this.journeyOptions={...m.t,maxAgeMs:this.config.journey.maxAgeMs},this.journey=new m.n(this.journeyOptions,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new $e({remote:this.remote,config:this.config,limits:this.limits,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform,debug:this.debugBuffer}),this.meter=new Oe(()=>this.config.metrics.intervalMs,(e,t,n)=>{this.emitPoint(e,t,n)},this.diagnostics,this.config.metrics),this.diagnostics.setHandler(this.diagnosticHandler()),this.syncProfiler()}diagnosticHandler(){return this.config.diagnostics.records===!1?this.config.onDiagnostic:e=>{this.recordDiagnostic(e),this.config.onDiagnostic?.(e)}}recordDiagnostic(e){let{records:t}=this.config.diagnostics;if((t===!0||t!==!1&&t.includes(e.code))&&!this.recordingDiagnostic){if(this.holdingRecords)this.heldDiagnostics.push(e);else{this.recordingDiagnostic=!0;try{(ut.has(e.code)?this.diagnosticLogger.info:this.diagnosticLogger.warn)(e.message,{"diagnostic.code":e.code,"diagnostic.count":e.count,"diagnostic.detail":ft(e.detail)})}finally{this.recordingDiagnostic=!1}}}}dropHeldRecords(){let e=this.heldDiagnostics.length;this.heldDiagnostics=[],e>0&&this.diagnostics.count(`record.dropped_during_rotation`,e)}addBreadcrumb(e,t){this.rotating||this.destroyed||this.diagnostics.guard(`record.sanitize_failed`,`The library could not add the breadcrumb.`,()=>{let n={t:Date.now(),category:`custom`,message:u.i(String(e),this.limits.maxBodyChars)};if(t!==void 0){let e=u.n(t,this.limits,this.diagnostics);n.data=r.n(e)?e:{value:e}}this.breadcrumbs.push(n)})}recordMetric(e,t,n){!this.destroyed&&!this.rotating&&this.config.enabled&&this.meter.record(e,t,n)}startMeasure(e,t){let n=this.identityEpoch,r=()=>!this.destroyed&&!this.rotating&&(!this.config.securityContext.isolation||this.identityEpoch===n),i=this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the measure.`,()=>({...t}));return ge(this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the name of the measure.`,()=>`${e}`)??``,i??{},this.tracing.request().span,{metric:(e,t,n)=>{r()&&this.recordMetric(e,t,n)},span:e=>{r()&&this.recordSpan(e)}})}recordSpan(t){if(this.config.tracesEndpoint===null)return;let{record:n}=this.builder.build({level:`INFO`,type:`span`,body:t.name,namespace:e.sr,payload:t.attributes,fixed:it(t),trace:{traceId:t.traceId,spanId:t.spanId,traceFlags:1}});this.emit(n)}emitPoint(t,n,r){if(this.destroyed)return;let{record:i}=this.builder.build({level:`INFO`,type:`metric`,body:t,namespace:e.Vt,payload:n,fixed:r,aggregated:!0});this.emit(i)}syncProfiler(){let e=this.config.profiler.enabled&&this.config.enabled;if(e===this.profilerOn)return;this.profilerOn=e;let t=c.t();if(!e){t.collect(!1),t.detach();return}let n={capacity:this.config.profiler.maxProbes,intervalMs:()=>this.config.metrics.intervalMs,emit:(e,t,n)=>{this.emitPoint(e,t,n)},diagnostics:this.diagnostics,ready:()=>!this.rotating||this.closingContext,outlier:(e,t)=>{this.breadcrumbs.push({t:Date.now(),category:`profile`,message:`${e} ${String(Math.round(t))} ms`})}};t.attach(n)}setReplay(e){this.replayConsent=e,e?this.replay?.start():this.replay?.stop()}collectPoints(){this.meter.collect(),this.profilerOn&&c.t().collect(!1)}advanceIdentity(){this.identityEpoch++,this.profilerOn&&this.config.securityContext.isolation&&c.t().reset(),this.remote.sampling=null,this.refreshCaptures()}static pinned(){return globalThis[L]??null}static current(){let e=n.local;if(e)return e.destroyed?null:e;let t=n.pinned();return t&&W(t)?t:null}static stopped(){let e=n.local;if(e?.destroyed)return e;let t=globalThis[R];return t&&W(t)?t:null}isDestroyed(){return this.destroyed}static configure(e,t=!1){try{return n.startOrUpdate(e,t)}catch(e){let t=n.current();if(t?.tunablesLocked)return t.diagnostics.report(`config.invalid`,`configure() could not read its options. The library keeps the current settings.`,void 0,e),t;let r=t??n.startOrUpdate({},!0);return r.refuse(e),r}}refuse(t){this.startFailed=!0;let n=f.r({redact:f.t},new A,this.config);f.n(this.config,n),l.n(()=>{console.warn(`${e.Mt} ${z}`)}),this.diagnostics.report(`config.invalid`,z,void 0,t),this.rehookHeld()}static startOrUpdate(e,t){let r=n.local;if(r&&!r.destroyed)return r.reconfigure(e),r;n.local=null;let i=n.pinned();if(i){if(!W(i))return n.startDegraded(e,i.sdkVersion,t);if(!i.destroyed)return i.reconfigure(e),i}let a=new n(e,!1);return globalThis[L]=a,Reflect.deleteProperty(globalThis,R),t||a.launch(),a}static startDegraded(t,r,i){let a=new n(t,!0);n.local=a;let o=typeof r==`string`?r:`before 0.9.0`;return a.mismatchVersion=o,a.diagnostics.report(`runtime.version_mismatch`,`Another copy of the library, version ${o}, owns the page runtime. This copy, version ${e.ir}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:o,own:e.ir}),i||a.launch(),a}reconfigure(e){if(this.rotating){this.diagnostics.report(`config.locked`,`Configuration cannot change during security-context rotation.`);return}if(this.config.lockConfiguration){let t=f.r(e,this.diagnostics,this.config);K(this.config,t)||this.diagnostics.report(`config.locked`,`Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.`);return}S(this);let t=this.keepDestination(this.keepRouting(this.allowed(e)));!this.tunablesLocked&&t.securityContext?.id&&(this.explicitSecurityContext=!0);let n=f.r(t,this.diagnostics,this.config),r=this.tunablesLocked?[`correlation`,`storage`]:[];for(let e of r)K(n[e],this.config[e])||(this.diagnostics.report(`config.invalid`,`${e} cannot change after startup. The library keeps the current settings.`),Object.assign(n,{[e]:this.config[e]}));this.keepStartupTunables(n);let{redact:i,processors:a,enabled:o}=this.config;o&&!n.enabled&&this.collectPoints(),f.n(this.config,n),this.config.redact!==f.t&&(this.startFailed=!1),(this.config.redact!==i||this.config.processors!==a)&&this.debugBuffer.clear(),this.breadcrumbs.resize(this.config.captureLimits.breadcrumbs),this.diagnostics.setHandler(this.diagnosticHandler()),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.builder.invalidateResource(),this.console.update(this.config.consoleOutput),this.keepBuiltIdentity(),this.syncProfiler(),this.launch(),this.running&&o!==this.config.enabled&&this.sender?.hold(!this.config.enabled),this.refreshCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}onServer(){return this.platform.platform===`node`}allowed(e){return this.degraded?(this.onServer()&&!this.serverReported&&mt(e)&&(this.serverReported=!0,this.diagnostics.report(`config.invalid`,`The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.`)),pt(e)):e}keepRouting(t){if(!this.tunablesLocked||this.degraded||!this.config.securityContext.isolation)return t;let n=f.r(t,new A,this.config),r=e.Pn.filter(e=>!K(n[e],this.config[e]));if(n.securityContext.id!==this.config.securityContext.id&&r.push(`securityContext.id`),r.length===0)return t;let i={...t};for(let t of e.Pn)r.includes(t)&&Reflect.deleteProperty(i,t);if(r.includes(`securityContext.id`)){let e={...t.securityContext};Reflect.deleteProperty(e,`id`),i.securityContext=e}return this.diagnostics.report(`config.invalid`,`Isolation refuses changes to ${r.join(`, `)}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`),i}keepStartupTunables(e){if(this.senderLoad!==void 0&&this.keepSections(e,ct),!this.tunablesLocked){Object.assign(this.limits,e.limits),this.journeyOptions.maxAgeMs=e.journey.maxAgeMs;return}this.keepSections(e,[`limits`]);for(let t of[`mode`,`openFinRole`])e.bus[t]!==this.config.bus[t]&&(this.diagnostics.report(`config.invalid`,`bus.${t} cannot change after startup. The library keeps "${this.config.bus[t]}".`,{requested:e.bus[t]}),Object.assign(e.bus,{[t]:this.config.bus[t]}));let{maxAgeMs:t}=this.config.journey;e.journey.maxAgeMs!==t&&(this.diagnostics.report(`config.invalid`,`journey.maxAgeMs cannot change after startup. It stays ${String(t)}.`,{requested:e.journey.maxAgeMs}),e.journey.maxAgeMs=t);let{maxProbes:n}=this.config.profiler;e.profiler.maxProbes!==n&&(this.diagnostics.report(`config.invalid`,`profiler.maxProbes cannot change after startup. It stays ${String(n)}.`,{requested:e.profiler.maxProbes}),e.profiler.maxProbes=n),e.otelLoader!==this.config.otelLoader&&(this.diagnostics.report(`config.invalid`,`otelLoader cannot change after startup. The library keeps the current loader.`),e.otelLoader=this.config.otelLoader)}keepSections(e,t){for(let n of t)K(e[n],this.config[n])||(this.diagnostics.report(`config.invalid`,`${n} cannot change after startup. The current values stay.`,{requested:e[n]}),Object.assign(e,{[n]:this.config[n]}))}keepDestination(e){if(this.senderLoad===void 0)return e;let t=e;for(let n of[`transport`,`transportWorker`]){let r=e[n],i=typeof r==`function`&&this.config[n]===void 0,a=r===null&&this.config[n]!==void 0;(i||a)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove ${n} after the delivery stack loads. The current transport stays.`),t={...t},Reflect.deleteProperty(t,n))}return(t.endpoint===null||t.endpoint===``)&&this.config.transport===void 0&&(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The current endpoint stays.`),t={...t,endpoint:void 0}),t}keepBuiltIdentity(){if(!this.tunablesLocked){this.identityBuiltAs=this.config.identity;return}let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}launch(){this.startFailed||(this.tunablesLocked||(this.tunablesLocked=!0,this.config.enabled||this.drops.add(`disabled`,this.rehookHeld())),!this.running&&this.config.enabled&&this.start())}start(){this.running=!0,this.identityBuiltAs===`storage`&&!this.onServer()&&(this.backing=s.t);let{sessionIdleMs:e,traceMaxAgeMs:t}=this.config.correlation,{sessionId:n,tabId:r}=s.s(this.diagnostics,this.stores,e);this.sessionTouch=new s.n(this.diagnostics,this.stores,e),this.sessionPicked?this.sessionTouch.restart(this.identity.sessionId):this.identity.sessionId=n,this.identity.tabId=r,this.builder.invalidateResource(),this.breadcrumbs.retain(e=>!lt.includes(e.category)),this.tracing.setup(t??1/0,this.config.otelLoader),this.tracing.loadOtel();for(let e of this.rehookHeld())this.bootBuffer.push(e,this.config.buffering.maxHeldRecords);this.openGate(),this.init()}rehookHeld(){return this.bootBuffer.take().map(e=>this.builder.rehook(e)).filter(e=>e!==null)}async init(){this.degraded||addEventListener(`pagehide`,this.onPageHide);let e=this.installCaptures();this.started=this.boot(),await this.started,await e}async boot(){try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{await this.startGate;let{Bus:e}=await Promise.resolve().then(()=>require("./bus-Dj8IEVcC.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onSecurityContext:e=>{if(this.explicitSecurityContext&&this.config.securityContext.id!==e)return this.contextMismatch=!0,this.diagnostics.report(`security.context_mismatch`,`The configured security context differs from the upstream owner.`),!1;if(this.contextMismatch=!1,this.config.securityContext.id!==e){if(this.ownerAdopted){S(this),this.drops.add(`security_context`,[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer]),this.forwardBuffer=[],this.context.clear(),this.breadcrumbs.clear();let e=this.rotating;this.rotating=!0,this.collectPoints(),this.profilerOn&&c.t().reset();let t=this.sessionTouch.stored();this.resetSession(t!==void 0&&t!==this.identity.sessionId?t:s.i(this.diagnostics)),this.rotating=e,this.advanceIdentity()}this.config.securityContext.id=e}return this.ownerAdopted=!0,!0},onRecords:e=>{this.ingestForwarded(e)},paused:()=>!this.config.enabled,onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()},onFlush:e=>this.flushFor(e,!1),remote:this.remote});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.running||!this.config.enabled||this.deliveryClosed||this.destroyed||!this.hasDestination()||this.role()!==`sender`?Promise.resolve():this.loadSender()}hasDestination(){return!!this.config.endpoint||this.config.transport!==void 0}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-CFu98DAB.cjs")),t=this.destroyed?null:await e.create({storage:this.memoryStorage,onStorage:e=>{e.name===`memory`&&(this.memoryStorage=e)},onPersistence:e=>{this.storagePersistence=e},config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,onLoss:this.reportLoss,remote:this.remote,beforeExit:()=>{S(this),this.collectPoints(),this.tracing.end()},onSent:e=>{this.lastSendAt=e}});if(!t||this.destroyed){await t?.discard();return}if(this.deliveryClosed){await this.parkSender(t);return}this.sender=t,this.config.enabled||t.hold(!0)}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e),this.drops.add(`load_failed`,this.pendingRecords.records)}for(let e of this.pendingRecords.take())this.sender?.push(e);if(this.sender&&this.carried.length>0){let e=this.carried;this.carried=[],await this.adoptStored(this.sender,e)}}async adoptStored(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store the carried batches under the new context.`,()=>e.adopt(t,this.config.securityContext.id))}refreshCaptures(){if(clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 0,this.destroyed)return;let e=this.remote.sampling?.wire();e&&(this.remoteCaptureTimer=setTimeout(()=>{this.refreshCaptures()},e.ttlMs),i.t(this.remoteCaptureTimer)),this.captureState(this.effectiveCapture())!==this.installedCaptureKey&&this.installCaptures()}captureState(e){let{enabled:t,framePhases:n,framePacing:r}=this.config.profiler;return`${String(this.config.enabled)}${dt(e)}${String(t&&n)}${String(t&&r)}${this.replayState(e)}`}replayState(e){let{replay:t}=this.config;return t.enabled?JSON.stringify([t.loader&&I(t.loader),t.onSegment&&I(t.onSegment),I(t.recordOptions),t.endpoint,t.requireConsent,t.mode,t.maskText,t.maskInputs,t.maskSelectors,t.blockSelectors,t.recordCanvas,t.bufferMs,t.plugins.map(I),e.fullUrls,e.ignoreUrls.map(String)]):``}effectiveCapture(){let t={...this.config.capture},n=this.remote.sampling?.current()?.capture;for(let r of e.dn){let e=n?.[r];if(t.remoteToggles.includes(r)&&e!==void 0){if(e&&typeof t[r]==`object`)continue;t[r]=e}}return t}async installCaptures(){if(this.degraded||!this.running)return;let t=++this.captureGeneration,n=this.effectiveCapture();if(this.installedCaptureKey=this.captureState(n),!this.config.enabled){this.uninstallCaptures();return}let r=this.replayState(n);r!==this.replayBuiltKey&&(this.replayBuiltKey=``);let i=r!==``&&r===this.replayBuiltKey?this.replay:void 0,a=[],{profiler:o}=this.config;(n.errors||n.rejections||n.resourceErrors)&&a.push(`errors`),(n.fetch||n.xhr)&&a.push(`network`),(n.interactions||n.navigation)&&a.push(`interactions`),n.webVitals&&a.push(`webVitals`),n.longFrames&&a.push(`longFrames`),(typeof n.console==`object`?n.console.levels?.length!==0:n.console)&&a.push(`console`),n.uncleanExit&&a.push(`uncleanExit`),n.userTiming&&a.push(`userTiming`),n.reports&&a.push(`reports`),n.resourceTiming&&a.push(`resourceTiming`),n.lifecycle&&a.push(`lifecycle`),o.enabled&&o.framePhases&&a.push(`framePhases`),o.enabled&&o.framePacing&&a.push(`framePacing`),this.config.replay.enabled&&!i&&a.push(`replay`);let[s,c]=await Promise.all([Promise.all(a.map(e=>this.loadCapture(e))),n.webSocket?this.loadWebSocket():void 0]);if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures(i);let l={isActive:()=>!this.destroyed&&!this.rotating,config:Object.assign(Object.create(this.config),{capture:n}),diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new ae(()=>this,e.P),once:this.captureOnce,recordMetric:(e,t,n)=>{this.recordMetric(e,t,n)},recordSpan:e=>{this.recordSpan(e)},sessionId:()=>this.identity.sessionId,onError:e=>{this.errorHook=e},setContext:(e,t)=>{this.context.merge({[e]:t??null})},replayConsent:()=>this.replayConsent};s.forEach((e,t)=>{if(e){let n=new e(l);this.captures.push(n),a[t]===`replay`&&(this.replay=n,this.replayBuiltKey=r)}});let u=c?[...n.plugins,new c(this.diagnostics,l.config)]:n.plugins;for(let e of u)this.captures.push(this.pluginCapture(e));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(e){for(let t of this.captures)t!==e&&this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${t.name} capture.`,()=>{t.uninstall()});this.captures.length=0,this.replay=e,e&&this.captures.push(e)}loadWebSocket(){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the webSocket capture.`,async()=>(await Promise.resolve().then(()=>require("./web-socket-sm3rD-A_.cjs"))).WebSocketCapture)}pluginCapture(t){let{name:n}=t,r=(e,t,n)=>{this.recordMetric(e,t,n)},i=t=>{this.diagnostics.report(`config.invalid`,e.St,void 0,t)},a={logger:new E(()=>this,`${e.P}.${n}`),counter:(e,t={})=>k(e,t,r,i),histogram:(e,t={})=>De(e,t,r,i),addBreadcrumb:(e,t)=>{this.addBreadcrumb(e,t)},ownRequest:d.r};return{name:n,install:()=>{t.install(a)},uninstall:()=>{t.uninstall()}}}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,at[e])}registerWorker(e,t={}){let n=!1,r;return this.destroyed?()=>void 0:(this.constructBus().then(i=>{!i||this.destroyed||n||(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{r=i.attachWorker(e,t)}),this.ensureBus())}),()=>{n=!0,r?.()})}registerFrame(e,t){let n=!1,r;return this.constructBus().then(i=>{!i||this.destroyed||n||(r=this.diagnostics.guard(`bus.send_failed`,`The frame could not be registered.`,()=>i.registerFrame(e,t)),this.ensureBus())}),()=>{n=!0,r?.()}}async destroy(e){let{discard:t,scope:n}=this.shutdownRule(e);this.stopping??=this.stop(t),await this.stopping,n!==void 0&&await this.clearStorage(n)}async stop(e){e||(S(this),this.collectPoints(),this.tracing.end()),this.profilerOn&&(this.profilerOn=!1,c.t().detach()),this.destroyed=!0,this.backing=s.r(),C(this),this.collectPoints(),clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 0,this.degraded||removeEventListener(`pagehide`,this.onPageHide),this.uninstallCaptures();let t=e?this.discardHeld():this.flushHeld();this.journey.destroy(),this.bus?.destroy(),await t,await this.senderLoad,await this.rotation?.catch(()=>void 0);let r=this.parkedSender;this.parkedSender=void 0,await this.diagnostics.guardAsync(`pipeline.crashed`,`The delivery stack of the old context did not stop at shutdown. The library leaves its stored batches in storage.`,async()=>{await(e?r?.discard():r?.retire(`retain`,0,this.config.securityContext.id))}),await this.memoryStorage?.close(),n.pinned()===this&&(Reflect.deleteProperty(globalThis,L),globalThis[R]=this)}shutdownRule(e){let t=this.readOptions(e,B);if(t===void 0)return{discard:!0};let{pending:n,clearStorage:r}=t,i=r==null,a=i||r===`context`||r===`namespace`,o;i||(o=r===`namespace`?`namespace`:`context`);let s=n===void 0||n===`flush`;return(!a||!(s||n===`discard`)||n===`flush`&&o)&&this.diagnostics.report(`config.invalid`,B),{discard:!s||o!==void 0,scope:o}}async flushHeld(){this.sender&&this.releaseBootBuffer(),this.dropPaused();let e=this.sender?.destroy();this.sendForwarded();let t=[...this.bootBuffer.take(),...this.pendingRecords.take()];this.drops.add(`load_failed`,this.unreported(t)),await e}async discardHeld(){let e=[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer];this.forwardBuffer=[],this.breadcrumbs.clear(),this.debugBuffer.clear(),this.context.clear(),this.journey.applyRemote(null);let t=await this.sender?.discard()??[];this.drops.add(`discarded`,this.unreported([...e,...t]))}async clearStorage(e){this.tunablesLocked&&await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove the stored batches at shutdown.`,async()=>{let{clearStored:t}=await Promise.resolve().then(()=>require("./stored-context-CPLlzgpm.cjs")),n=this.carried.map(e=>e.id);this.carried=[],await t(this.storeAccess(),e,n,this.identityBuiltAs===`storage`&&!this.onServer())})}emit(e){if(!e||this.destroyed)return;if(this.rotating&&!this.closingContext){this.drops.add(`security_context`,[e]);return}this.sessionTouch.touch(this.identity.sessionId);let t=e.severityText===`ERROR`||e.severityText===`FATAL`,n=t?[...this.debugBuffer.drain(),e]:[e];t&&this.errorHook?.(e);for(let e of n)this.ready?this.route(e):this.bootBuffer.push(e,this.config.buffering.maxHeldRecords)}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){if(this.deliveryClosed){this.drops.add(`security_context`,[e]);return}if(this.sender){this.sender.push(e);return}let t=!this.config.enabled&&this.hasDestination();!this.senderLoad&&!t?(this.diagnostics.count(`record.dropped_no_destination`),this.hasDestination()&&this.drops.add(`load_failed`,[e])):this.pendingRecords.push(e,this.config.buffering.maxHeldRecords)}dropPaused(){if(this.config.enabled)return;let e=this.unreported([...this.pendingRecords.records,...this.sender?.records()??[]]);for(let t of e)this.pausedLoss.add(t);this.drops.add(`disabled`,e)}unreported(e){return e.filter(e=>!this.pausedLoss.has(e))}dropHeld(e){this.diagnostics.count(`record.dropped_boot_buffer_full`),this.drops.add(`buffer_full`,[e])}forward(e){this.forwardBuffer.push(e),this.forwardScheduled||(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1,this.sendForwarded()}))}sendForwarded(){let e=this.forwardBuffer;this.forwardBuffer=[];let{bus:t}=this;return e.length===0||!t?0:t.sendRecords(e)}ingestForwarded(e){if(this.destroyed)return;if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}let n=[];for(let r of e){if(!t.n(r)){this.diagnostics.count(`record.dropped_malformed`);continue}if(r.attributes[`uiobs.debug_buffer`]!==!0&&!h.a(r,this.config,this.remote.sampling?.current()??null)){this.diagnostics.count(`record.dropped_by_sampling`);continue}let e=this.builder.redactForwarded(r);e&&n.push(e)}if(this.rotating)this.drops.add(`security_context`,n);else if(!this.config.enabled)this.drops.add(`disabled`,n);else for(let e of n)this.deliver(e)}releaseBootBuffer(){let e=this.bootBuffer.take(),{processors:t,redact:n}=this.config,r=t.length===0&&n===void 0?this.journey.current():null;for(let t of e)r&&!t.attributes[`journey.id`]&&(t.attributes[`journey.id`]=r.id,t.attributes[`journey.name`]=r.name),this.route(t)}regenerateTabId(){let e=s.i(this.diagnostics);this.diagnostics.report(`bus.tab_id_changed`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,s.a(e,this.diagnostics,this.stores),this.builder.invalidateResource(),this.bus?.setTabId(e)}newSession(){this.destroyed||(S(this),this.resetSession(s.i(this.diagnostics)))}resetSession(e){this.sessionPicked=!0,this.collectPoints(),this.tracing.rotate(`explicit`),this.journey.end(),this.breadcrumbs.clear(),this.debugBuffer.clear(),this.replay?.reset(),this.identity.sessionId=e,this.sessionTouch.restart(e),this.builder.invalidateResource()}rotateSecurityContext(e,t={}){if(this.destroyed)return Promise.reject(Error(`The runtime has stopped.`));if(!this.tunablesLocked)return Promise.reject(Error(`The runtime is not configured. Call configure() before rotateSecurityContext().`));S(this),this.rotating=!0;let n=++this.rotationSeq,r=(this.rotation??Promise.resolve()).catch(()=>void 0).then(()=>this.runRotation(e,t,n));this.rotation=r;let i=()=>{this.rotation===r&&(this.rotation=void 0,this.rotating=!1,this.retiring=void 0)};return r.then(i,i),r}async runRotation(e,t,n){if(this.destroyed)throw Error(`The runtime has stopped.`);if(await this.started,this.role()===`forwarder`)throw Error(`Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.`);let r;try{r=(await Promise.resolve().then(()=>require("./rotation-fTnNJcfH.cjs"))).rotateContext}catch(e){throw this.diagnostics.report(`pipeline.crashed`,`The library could not load the security-context rotation.`,void 0,e),await this.closeDelivery(),e}if(this.isDestroyed())throw Error(`The runtime has stopped.`);try{await r(this.rotationHost(),e,t,n)}finally{this.dropHeldRecords()}}rotationHost(){return{runtime:this,quiet:new A,senderLoaded:async()=>{await this.senderLoad},holdRecords:e=>{this.holdingRecords=!0;try{return e()}finally{this.holdingRecords=!1}},allowed:e=>this.allowed(e),closeDelivery:()=>this.closeDelivery(),closeContext:()=>{this.closingContext=!0;try{this.collectPoints(),this.tracing.end(),this.journey.end()}finally{this.closingContext=!1}},takeOld:()=>{let e=[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer],t=this.sender??this.parkedSender;this.retiring=t;let n=this.carried;return this.forwardBuffer=[],this.carried=[],this.sender=void 0,this.senderLoad=void 0,this.parkedSender=void 0,{held:e,sender:t,closed:this.deliveryClosed,carried:n}},drop:e=>{this.drops.add(`security_context`,this.unreported(e))},storeAccess:()=>this.storeAccess(),advanceIdentity:()=>{this.advanceIdentity()},openDelivery:async()=>{this.deliveryClosed=!1,await this.syncSender(),this.bus?.rotateContext()},endRotation:e=>{if(this.rotating=e!==this.rotationSeq,this.rotating){this.dropHeldRecords();return}let t=this.heldDiagnostics;this.heldDiagnostics=[];for(let e of t)this.recordDiagnostic(e)},route:e=>{this.route(e)},adopt:async e=>{!this.config.enabled||this.destroyed?this.carried=[...e]:await this.sender?.adopt(e,this.config.securityContext.id)}}}async closeDelivery(){this.deliveryClosed=!0,this.diagnostics.report(`security.rotation_failed`,`The security-context rotation failed. The library sends no record until a rotation succeeds.`),await this.senderLoad;let e=this.sender;this.sender=void 0,this.senderLoad=void 0,e&&await this.parkSender(e),this.drops.add(`security_context`,this.unreported(this.pendingRecords.take()))}async parkSender(e){this.parkedSender=e,await this.diagnostics.guardAsync(`pipeline.crashed`,`The delivery stack of the old context did not stop. The next rotation that succeeds retires it.`,()=>e.pause(this.config.securityContext.id))}async debugBundle(t){let{configSummary:n}=await Promise.resolve().then(()=>require("./debug-bundle-DMzUfiQc.cjs")),{record:r}=this.builder.build({level:`INFO`,type:`system`,body:`debug bundle`,namespace:e.Y,payload:{[e.c]:this.breadcrumbs.snapshot()}},!0),i=r?.attributes??{},a=i[e.c],o=i[e.v];return{createdAt:new Date().toISOString(),sdkVersion:this.sdkVersion,health:t,diagnostics:this.diagnostics.snapshot(),resource:r?.resource??{},pageUrl:typeof o==`string`?o:``,breadcrumbs:Array.isArray(a)?a:[],debugBuffer:this.debugBuffer.snapshot(),config:n(this.config,this.limits,this.diagnostics)}}async health(){let e=this.sender?.stats(),t=[];this.mismatchVersion&&t.push(`runtime.version_mismatch`),this.contextMismatch&&t.push(`security.context_mismatch`);let{redact:n,processors:r}=this.config;(n===f.t||r.includes(f.t))&&t.push(`records.refused`),this.deliveryClosed?t.push(`security.rotation_failed`):this.ready&&this.config.enabled&&this.hasDestination()&&this.role()===`sender`&&!this.sender&&t.push(`sender.unavailable`);let{sourcePolicy:i,maxMessageBytes:a,maxRecordsPerMessage:o,maxMessagesPerSecond:s}=this.config.bus;return{delivery:{pending:(e?.pending??0)+this.heldRecords(),inFlight:e?.inFlight??0,stored:await this.storedBatches(),lastSendAt:this.lastSendAt,lastFailureAt:e?.lastFailureAt??null,consecutiveFailures:e?.consecutiveFailures??0,throttledUntil:e?.throttledUntil??null,dropped:this.drops.counts()},sdkVersion:this.sdkVersion,owningSdkVersion:this.mismatchVersion,status:this.destroyed?`stopped`:this.tunablesLocked?this.config.enabled?this.rotating?`rotating`:t.length?`degraded`:this.ready?`ready`:`starting`:`disabled`:`unconfigured`,mode:this.role()===`forwarder`?`forwarder`:this.hasDestination()?`sender`:`console-only`,senderReady:this.sender!==void 0&&this.config.enabled&&!this.destroyed&&!this.rotating&&!this.deliveryClosed,configurationLocked:this.config.lockConfiguration,issues:t,securityContext:{...this.config.securityContext},storagePersistence:this.storagePersistence,bus:{sourcePolicy:i,maxMessageBytes:a,maxRecordsPerMessage:o,maxMessagesPerSecond:s}}}storeAccess(){return{config:this.config,diagnostics:this.diagnostics,memory:this.memoryStorage}}async storedBatches(){return await(this.sender??this.parkedSender)?.queueDepth()??0}flush(e){return this.flushFor(this.flushTimeout(e),!0)}async flushFor(e,t){S(this),t&&this.collectPoints();let n=this.idle();if(n)return n;let r=Date.now()+e,a,o=new Promise(t=>{let n=setTimeout(t,e);i.t(n),a=()=>{clearTimeout(n)}});try{return await this.flushBefore(r,o)}finally{a()}}async flushBefore(t,n){let r=this.heldRecords(),i=this.ready?this.senderLoad:this.started;if(i&&(!this.ready||!this.sender)&&!await Promise.race([i.then(()=>!0),n.then(()=>!1)]))return U({pending:this.waiting()});let{bus:a}=this,o=a?.getRole()===`forwarder`,s=this.idle();if(s)return s;if(o){let r=this.forwardBuffer.length,i=this.sendForwarded(),o=r-i,s=Math.floor(Math.max(0,t-Date.now())*e.it),c=await a.requestFlush(s,n);return c?{...c,forwarded:i,dropped:c.dropped+o}:U({forwarded:i,pending:i,dropped:o})}let{sender:c}=this;return c?U(await c.flushUntil(n)):this.rotating?U({pending:r+this.waiting()}):H(`complete`,{dropped:r})}idle(){return this.tunablesLocked&&this.config.enabled&&!this.destroyed?null:H(`inactive`,{pending:this.destroyed?0:this.waiting()})}heldRecords(){return this.bootBuffer.length+this.pendingRecords.length+this.forwardBuffer.length}waiting(){let e=this.heldRecords();for(let t of[this.sender,this.retiring]){let n=t?.stats();e+=n?n.pending+n.inFlight:0}return e}readOptions(e,t){if(typeof e!=`object`&&e!==void 0)this.diagnostics.report(`config.invalid`,t);else return this.diagnostics.guard(`config.invalid`,t,()=>({...e}))}flushTimeout(t){let n=this.readOptions(t,V);if(!n)return e.ot;let r=n.timeoutMs??5e3;return typeof r==`number`&&r>=0&&r<=6e5?r:(this.diagnostics.report(`config.invalid`,V),e.ot)}};o.t(G,`local`,null);function K(e,t,n=new WeakMap){if(Object.is(e,t))return!0;if(e instanceof RegExp&&t instanceof RegExp)return String(e)===String(t);if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let i=Object.keys(e),a=Object.keys(t);return i.length===a.length&&i.every(i=>r.t(t,i)&&K(Reflect.get(e,i),Reflect.get(t,i),n))}var q;function ht(t={}){if(q)return q;let n=new A(t.onDiagnostic);if(typeof document<`u`||typeof addEventListener!=`function`)return n.report(`config.invalid`,`Call serveTransportWorker() in a dedicated worker.`),()=>void 0;let i=!1,a,o,s=t=>{n.guard(`transport.http_error`,`The transport worker could not read its connection.`,()=>{let s=t.data;if(!r.n(s)||s.p!==`ui-observability.transport/1`||s.t!==e.dr.connect||t.ports.length===0)return;let c=t.ports[0];a||s.v!==`1.2.0`?(c.postMessage(e.ur),c.close()):(a=c,Promise.resolve().then(()=>require("./worker-server-CF1yatXq.cjs")).then(e=>{i||(o=e.serveWorkerPort(c,n))}).catch(t=>{n.report(`transport.http_error`,`The transport worker delivery module could not load.`,void 0,t),n.guard(`transport.http_error`,`The failed transport port could not be closed.`,()=>{c.postMessage(e.ur),c.close()})}))})},c=()=>{i||(i=!0,q=void 0,removeEventListener(`message`,s),o?.(),n.guard(`transport.http_error`,`The transport service could not close its port.`,()=>{a?.postMessage(e.ur)}),n.guard(`transport.http_error`,`The transport port could not close.`,()=>{a?.close()}))};return addEventListener(`message`,s),q=c,c}function gt(){let e=[],t=[],n={status:200};return{transport:r=>(e.push(r),n.status>=200&&n.status<300&&t.push(r),Promise.resolve({...n})),records:()=>t.flatMap(e=>[...e.records]),batches:()=>[...e],clear:()=>{e.length=0,t.length=0},respondWith:(e,t)=>{n=t===void 0?{status:e}:{status:e,retryAfterMs:t}}}}var J=new Map;function Y(){return(G.current()??G.stopped())||G.configure({},!0)}function _t(e){G.configure(e),Z()}function vt(e){Y().setConfigurationLocked(e)}function yt(e,t){return Y().rotateSecurityContext(e,t)}async function X(){let e=Y();return Z(),{...await e.health(),loggerCache:{...e.config.loggerCache,size:J.size}}}async function bt(){let e=await X();return Y().debugBundle(e)}function Z(){let e=(G.current()??G.stopped())?.config.loggerCache.maxEntries,t=e===void 0?256:e;if(t!==null)for(let e of J.keys()){if(J.size<=t)break;J.delete(e)}return t}function xt(e,t){let n=Z();if(t||n===0)return new E(Y,e,t);let r=J.get(e);return r??=new E(Y,e),J.delete(e),J.set(e,r),Z(),r}function Q(){return xt(`app`)}function St(e,t){Q().trace(e,t)}function Ct(e,t){Q().debug(e,t)}function wt(e,t){Q().info(e,t)}function Tt(e,t){Q().warn(e,t)}function Et(e,t,n){Q().error(e,t,n)}function Dt(e,t,n){Q().fatal(e,t,n)}function Ot(e,t){Q().logAction(e,t)}function kt(e,t){Q().logEvent(e,t)}function $(t){G.current()?.diagnostics.report(`config.invalid`,e.St,void 0,t)}function At(e,t={}){return k(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function jt(e,t={}){return Ee(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function Mt(e,t={}){return De(e,t,(e,t,n)=>{Y().recordMetric(e,t,n)},$)}function Nt(e,t){return Y().startMeasure(e,t)}function Pt(e,t,n){let r=Y();return _e(r.startMeasure(e,n),t,r.diagnostics)}function Ft(){Y().setReplay(!0)}function It(){Y().setReplay(!1)}var Lt={probe:(e,t)=>c.t().probe(e,t,G.current()?.diagnostics),time:(e,t)=>c.t().time(e,t,G.current()?.diagnostics)};function Rt(e,t){Y().addBreadcrumb(e,t)}function zt(e){let t=Y();r.n(e)?t.diagnostics.guard(`record.sanitize_failed`,`The library could not read the values of setContext().`,()=>{t.context.merge(e)}):t.diagnostics.report(`config.invalid`,`setContext() takes an object. The library keeps the current context.`)}function Bt(e){Y().context.remove(e)}function Vt(e,t){return Y().journey.start(e,t)}function Ht(){Y().journey.end()}function Ut(){return Y().journey.current()}function Wt(){return Y().journey.getToken()}function Gt(e){return Y().journey.adopt(e,`manual`,!0)}function Kt(e,t){return Y().registerWorker(e,t)}function qt(e,t){return Y().registerFrame(e,t)}function Jt(){Y().tracing.rotate(`explicit`)}function Yt(){return Y().tracing.headers()}function Xt(e){return Y().flush(e)}function Zt(){Y().newSession()}function Qt(){return Y().diagnostics.snapshot()}async function $t(e){await(G.current()??G.stopped())?.destroy(e)}exports.addBreadcrumb=Rt,exports.adoptJourney=Gt,exports.collectDebugBundle=bt,exports.configure=_t,exports.counter=At,exports.createMemoryTransport=gt,exports.currentJourney=Ut,exports.debug=Ct,exports.endJourney=Ht,exports.error=Et,exports.fatal=Dt,exports.flush=Xt,exports.gauge=jt,exports.getDiagnosticCounters=Qt,exports.getHealth=X,exports.getJourneyToken=Wt,exports.getLogger=xt,exports.getTraceHeaders=Yt,exports.histogram=Mt,exports.info=wt,exports.logAction=Ot,exports.logEvent=kt,exports.measure=Pt,exports.newSession=Zt,exports.newTrace=Jt,exports.observeWindow=g.r,exports.profiler=Lt,exports.registerFrame=qt,exports.registerWorker=Kt,exports.removeContext=Bt,exports.rotateSecurityContext=yt,exports.serveTransportWorker=ht,exports.setConfigurationLocked=vt,exports.setContext=zt,exports.shutdown=$t,exports.startJourney=Vt,exports.startMeasure=Nt,exports.startReplay=Ft,exports.stopReplay=It,exports.trace=St,exports.warn=Tt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|