@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sender-CFu98DAB.cjs","names":["TransportError","batchKind","serializeBatch","partialSuccessOf","endpointFor","batchKind","withDeadline","trackTransportCall","runAsLibraryRequest","runAsLibraryConsole","DeadlineError","TransportError","getFin","batchKind","endpointFor","estimateBytes","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","CONTENT_TYPE_TEXT_PLAIN","BEACON_LIMIT_BYTES","runAsLibraryRequest","serializeBatch","batchKind","endpointFor","isOtlpBatch","HEADER_SAMPLING","HEADER_DATE","parseRetryAfter","HEADER_RETRY_AFTER","HEADER_CONTENT_TYPE","HEADER_BATCH_ID","HEADER_ATTEMPT","HEADER_CONTENT_ENCODING","ENCODING_GZIP","estimateBytes","withDeadline","TransportError","gzip","runAsLibraryRequest","needsBody","readOptionalBody","isOnline","maxBytesOf","storageLimits","RETRY_IDLE_DELAY_MS","withDeadline","STORAGE_DEADLINE_MS","lockName","DRAIN_LOCK_NAME","withDrainLock","isOnline","batchKind","TransportError","splitBatch","ATTR_LOG_TYPE","estimateBytes","ErrorCeiling","nowUnixNano","newId","ATTR_CLOCK_OFFSET_MS","withDeadline","STORAGE_DEADLINE_MS","createStorage","storageName","storageLimits","ContextStorage","parseRemoteRules","withDeadline","clearEmergencyContext","drainEmergencyQueue","require_constants","require_factory","require_deadline","require_library_request","require_openfin","require_sanitize","require_library_console","require_response_body","require_defineProperty","require_platform","require_unref","require_compression","require_batch","require_log_record","require_identity","require_sampling","require_remote_rules","requestPersistence","storage","diagnostics","clockOffset","serverMs","date","StatusTransport","batch","cancel","cancelled","reject","work","config","onSampling","onLoss","onClock","end","serialized","kind","sampling","offset","partial","body","endpoint","rejected","total","code","status","advice","hints","throttled","retryAfterMs","toTransportRequest","isResponse","value","finiteHint","CustomTransport","transport","request","response","error","deadline","message","LATE_FLUSH_LIMIT","ExitFlush","deps","me","reason","url","inFlight","target","bytes","custom","typedHeaders","headers","plain","outcome","isOpaque","matchesGlobal","matchesLocation","onExit","backend","nav","park","caches","lastHeaders","cached","owner","resolveHeaders","resolved","resetHeaders","CREDENTIAL_ADVICE","HttpTransport","_args","onKeepalive","otlp","answer","maxBytes","text","controller","timer","keepalive","RetryEngine","batchesPerDrain","parts","written","stored","part","idle","delayMs","exponential","lock","batches","blocked","split","throttledMs","failure","kept","halves","record","STREAM_ORDER","streamOf","type","keptEnd","records","SEND_FAILED_TEXT","THROTTLED_TEXT","RecordStream","options","onFlush","LogPipeline","pending","stream","full","maxPendingRecords","maxPendingBytes","fits","overflow","retry","routingContextId","policy","flush","streamOptions","queued","name","keptAlive","snapshot","stop","held","resolve","all","expired","counts","item","items","on","buffered","settle","result","lost","report","SendOutcomes","onSent","before","at","Sender","pipeline","exitFlush","outcomes","backing","update","raw","clockOffsetMs","offsetMs","worker","http","batching","started","sender","drained","contextId","timeoutMs","discard","moved"],"sources":["../src/storage/persistence.ts","../src/transport/status-transport.ts","../src/transport/custom-transport.ts","../src/transport/exit-flush.ts","../src/transport/headers.ts","../src/transport/http-transport.ts","../src/transport/retry-engine.ts","../src/core/pipeline.ts","../src/core/sender.ts"],"sourcesContent":["// src/storage/persistence.ts\n//\n// Asks the browser to keep the stored batches under storage pressure.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StoragePersistence } from \"../models/storage\";\n\n/** The global that holds the storage manager. Workers, Node and insecure pages can lack it. */\ninterface StorageGlobal {\n navigator?: { storage?: StorageManager };\n}\n\n/**\n * Asks the browser for persistent storage. Firefox can show a permission prompt.\n * @param diagnostics Diagnostics reporter.\n * @returns The browser's answer. Never rejects.\n */\nexport async function requestPersistence(diagnostics: Diagnostics): Promise<StoragePersistence> {\n const storage = (globalThis as StorageGlobal).navigator?.storage;\n // An old browser can have navigator.storage without persist().\n if (typeof storage?.persist !== \"function\") {\n return \"unsupported\";\n }\n\n const granted = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The browser rejected the request for persistent storage.\",\n () => storage.persist(),\n );\n\n return granted === true ? \"granted\" : \"denied\";\n}\n","// src/transport/status-transport.ts\n//\n// Holds what the HTTP transport and the custom transport share, so a status code means the\n// same on both paths. 2xx accepts the batch, 413 splits it, 429 and 503 throttle, and 408 and\n// 5xx retry. Any other code drops the batch.\n\nimport {\n DATE_HEADER_HALF_STEP_MS,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REQUEST_TIMEOUT,\n HTTP_SERVER_ERROR_MIN,\n HTTP_SERVICE_UNAVAILABLE,\n HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { TransportError } from \"./errors\";\nimport { partialSuccessOf } from \"./response-body\";\nimport { batchKind, endpointFor, serializeBatch } from \"./serializers/select\";\n\n/**\n * Computes the clock offset from an answer's Date header.\n * @param date Value of the Date header. It has whole seconds.\n * @returns Server time minus client time in milliseconds, or undefined without a valid date.\n */\nfunction clockOffset(date: unknown): number | undefined {\n const serverMs = typeof date === \"string\" ? Date.parse(date) : Number.NaN;\n\n return Number.isNaN(serverMs)\n ? undefined\n : Math.round(serverMs + DATE_HEADER_HALF_STEP_MS - Date.now());\n}\n\n/** The two operations that the pipeline and the retry engine use. */\nexport interface BatchTransport {\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @returns Promise that resolves to the records lost in a send that ends without an error,\n * for example the records a server rejected in an accepted batch.\n * @throws TransportError when the batch isn't accepted.\n */\n send(batch: LogBatch, onKeepalive?: () => void): Promise<number>;\n /**\n * Returns the remaining throttle delay for a batch's endpoint.\n * @param batch Batch to send.\n * @returns Milliseconds until the throttle ends, or 0.\n */\n throttledForMs(batch: LogBatch): number;\n}\n\n/** Hints that come with a rejected batch. */\nexport interface RejectHints {\n /** Delay that the server asks for, in milliseconds. */\n retryAfterMs?: number;\n /** Largest payload that the server accepts, from a 413 answer. */\n maxBytes?: number;\n /** Extra advice for a 401 or a 403 answer. */\n advice?: string;\n}\n\n/** Base class of the HTTP transport and the custom transport. */\nexport abstract class StatusTransport implements BatchTransport {\n /** Abort controller shared by the requests of this delivery context. */\n protected readonly cancellation = new AbortController();\n /** Cancels this context's work. A custom transport receives the same abort signal. */\n stop(): void {\n this.cancellation.abort();\n }\n\n /**\n * Checks the batch context after every asynchronous step and before a send.\n * @param batch Batch to check.\n * @throws TransportError if the context stopped or the context id doesn't match.\n */\n protected assertContext(batch: LogBatch): void {\n if (\n this.cancellation.signal.aborted ||\n (this.config.securityContext.isolation &&\n this.config.securityContext.id &&\n batch.routingContextId !== this.config.securityContext.id)\n ) {\n this.diagnostics.count(\"security.context_mismatch\");\n throw new TransportError(\n \"permanent\",\n \"The delivery context is inactive or does not match the batch.\",\n );\n }\n }\n\n /**\n * Ends the wait if this context stops before the work completes.\n * @param work Work to wait for.\n * @returns The result of the work.\n * @throws TransportError if this context stops first.\n */\n protected async untilCancelled<T>(work: Promise<T>): Promise<T> {\n if (this.cancellation.signal.aborted) {\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n }\n let cancel!: () => void;\n const cancelled = new Promise<never>((_resolve, reject) => {\n cancel = () => {\n reject(new TransportError(\"permanent\", \"The delivery context retired.\"));\n };\n this.cancellation.signal.addEventListener(\"abort\", cancel, { once: true });\n });\n try {\n return await Promise.race([work, cancelled]);\n } finally {\n this.cancellation.signal.removeEventListener(\"abort\", cancel);\n }\n }\n /**\n * Epoch time in milliseconds when the server throttle ends, per endpoint, so that a 429 from\n * metricsEndpoint doesn't stop the log batches.\n */\n private readonly throttledUntil: Record<BatchKind, number> = { logs: 0, metrics: 0, traces: 0 };\n\n /** Epoch time in milliseconds when the server last accepted a batch, or null. */\n private acceptedAt: number | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param onSampling Receives an accepted batch's sampling rules, before validation.\n * @param onLoss Receives the records of a batch that the serializer can't encode.\n * @param onClock Receives an accepted batch's clock offset, in milliseconds.\n */\n constructor(\n protected readonly config: ResolvedConfig,\n protected readonly diagnostics: Diagnostics,\n private readonly onSampling: (raw: unknown) => void = () => undefined,\n private readonly onLoss: LossReporter = () => undefined,\n private readonly onClock: (offsetMs: number) => void = () => undefined,\n ) {}\n\n /**\n * Sends one batch.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @returns Promise that resolves to the records lost in a send that ends without an error.\n * @throws TransportError when the batch isn't accepted.\n */\n abstract send(batch: LogBatch, onKeepalive?: () => void): Promise<number>;\n\n /**\n * Returns the remaining throttle delay for a batch's endpoint, in milliseconds.\n * @param batch Batch to send.\n * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.\n */\n throttledForMs(batch: LogBatch): number {\n return Math.max(0, this.throttledUntil[batchKind(batch, this.config)] - Date.now());\n }\n\n /**\n * Returns when the latest server throttle ends, over all endpoints.\n * @returns Epoch time in milliseconds, or null when no endpoint is throttled now.\n */\n throttleEnd(): number | null {\n const end = Math.max(...Object.values(this.throttledUntil));\n return end > Date.now() ? end : null;\n }\n\n /**\n * Returns the time when the server last accepted a batch.\n * @returns Epoch time in milliseconds, or null before the first accepted batch.\n */\n lastSendAt(): number | null {\n return this.acceptedAt;\n }\n\n /**\n * Serializes a batch with the configured serializer. A metrics batch gets the OTLP metrics\n * format. Reports a serializer that throws.\n * @param batch Batch to serialize.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n protected serialize(batch: LogBatch): SerializedBatch | undefined {\n const serialized = serializeBatch(\n this.config,\n batch,\n this.diagnostics,\n \"The serializer threw an error. The library dropped the batch.\",\n );\n\n if (!serialized) {\n this.onLoss(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\n }\n\n /**\n * Records an accepted batch and ends the server throttle for that batch's endpoint.\n * @param kind Kind of the accepted batch.\n * @param sampling The answer's sampling rules, as text or as an object.\n * @param date The answer's Date header. Null when the server doesn't expose it.\n */\n protected accept(kind: BatchKind, sampling: unknown, date: unknown): void {\n this.throttledUntil[kind] = 0;\n this.acceptedAt = Date.now();\n\n // Only trust the answer to a batch that we sent ourselves. A null header means no rules.\n if (this.config.sampling.remote && sampling !== undefined && sampling !== null) {\n this.onSampling(sampling);\n }\n\n const offset = clockOffset(date);\n if (offset !== undefined) {\n this.onClock(offset);\n }\n }\n\n /**\n * Reports what an OTLP server rejected or warned about in a batch it accepted. The batch isn't\n * sent again, because the server kept the other records and a resend would duplicate them.\n * @param batch The accepted batch.\n * @param kind Kind of the batch, which names the count's field.\n * @param body The answer's body text.\n * @returns The number of rejected records, or 0.\n */\n protected reportPartial(batch: LogBatch, kind: BatchKind, body: string): number {\n const partial = this.diagnostics.guard(\n \"transport.http_error\",\n \"The library could not read the body of the 2xx response.\",\n () => partialSuccessOf(body, kind),\n );\n if (!partial) {\n return 0;\n }\n\n const endpoint = endpointFor(kind, this.config);\n // The server only gives a count, so onDrop can't name the journeys or the actions.\n const rejected = Math.min(partial.rejected, batch.records.length);\n if (rejected === 0) {\n this.diagnostics.report(\n \"transport.partial_success\",\n \"The server accepted the batch with a warning.\",\n { endpoint, serverMessage: partial.message },\n );\n return 0;\n }\n\n this.onLoss(\"partially_rejected\", [], [batch.id], rejected);\n const total = String(batch.records.length);\n this.diagnostics.report(\n \"transport.partial_success\",\n `The server rejected ${String(rejected)} of ${total} records in the batch. ` +\n \"The library does not send them again.\",\n { endpoint, rejected, serverMessage: partial.message },\n );\n return rejected;\n }\n\n /**\n * Converts a non-2xx status code into a classified TransportError.\n * @param status The answer's status code.\n * @param batchId Identifier of the rejected batch.\n * @param kind Kind of the rejected batch. A throttle applies only to its endpoint.\n * @param hints Delay, size limit and advice that come with the answer.\n * @returns Classified TransportError instance.\n */\n protected reject(\n status: number,\n batchId: string,\n kind: BatchKind,\n hints: RejectHints,\n ): TransportError {\n const code = String(status);\n\n if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {\n const advice = hints.advice === undefined ? \"\" : ` ${hints.advice}`;\n\n this.diagnostics.report(\n \"transport.rejected_credentials\",\n `The server returned ${code}.${advice}`,\n { status, endpoint: endpointFor(kind, this.config) },\n );\n // Classify as permanent. Retrying a rejected credential would block every batch behind it.\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n\n if (status === HTTP_PAYLOAD_TOO_LARGE) {\n return new TransportError(\n \"too_large\",\n \"The payload is too large.\",\n status,\n undefined,\n hints.maxBytes,\n );\n }\n\n if (status === HTTP_TOO_MANY_REQUESTS || status === HTTP_SERVICE_UNAVAILABLE) {\n const throttled = status === HTTP_TOO_MANY_REQUESTS;\n // Cap the server delay, otherwise a large Retry-After could stop delivery for hours.\n const retryAfterMs =\n hints.retryAfterMs === undefined\n ? undefined\n : Math.min(hints.retryAfterMs, this.config.delivery.retryMaxDelayMs);\n this.throttledUntil[kind] =\n Date.now() + (retryAfterMs ?? this.config.delivery.retryBaseDelayMs);\n\n if (throttled) {\n this.diagnostics.report(\"transport.throttled\", \"The server throttles the requests.\", {\n retryAfterMs,\n });\n }\n\n return new TransportError(\n \"throttled\",\n throttled ? \"The server throttles the requests.\" : \"The service is not available.\",\n status,\n retryAfterMs,\n );\n }\n\n if (status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR_MIN) {\n return new TransportError(\"transient\", `The server returned the error ${code}.`, status);\n }\n\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The server rejected the batch with ${code}. The library dropped it.`,\n { batchId, status },\n );\n return new TransportError(\"permanent\", `The server rejected the batch with ${code}.`, status);\n }\n}\n","// src/transport/custom-transport.ts\n//\n// Sends batches through the consumer's own transport function. Status codes mean the same as\n// on the HTTP path, and retry, storage and the exit flush work unchanged.\n\nimport { HTTP_STATUS_MAX, HTTP_STATUS_MIN, HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { DeadlineError, withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest, trackTransportCall } from \"../utils/library-request\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\nimport { StatusTransport } from \"./status-transport\";\n\n/**\n * Builds the request that a custom transport and its exit hook receive.\n * @param batch Batch to send.\n * @param serialized Serialized form of the batch.\n * @param kind Kind of the batch.\n * @returns The transport request.\n */\nexport function toTransportRequest(\n batch: LogBatch,\n serialized: SerializedBatch,\n kind: BatchKind,\n): TransportRequest {\n return {\n kind,\n body: serialized.body,\n contentType: serialized.contentType,\n batchId: batch.id,\n attempt: batch.attempts,\n records: batch.records,\n routingContextId: batch.routingContextId,\n };\n}\n\n/**\n * Checks whether a value is a usable transport response.\n * @param value Value that the transport resolved to.\n * @returns True if the value has an integer status from 100 to 599.\n */\nfunction isResponse(value: unknown): value is TransportResponse {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const status: unknown = Reflect.get(value, \"status\");\n return (\n typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= HTTP_STATUS_MIN &&\n status <= HTTP_STATUS_MAX\n );\n}\n\n/**\n * Cleans a numeric hint from the transport's response before the library's throttle and\n * batch split use it. A string, NaN or Infinity would break the throttle.\n * @param value Hint that the transport returned.\n * @returns The value, 0 or more, or undefined if it isn't a finite number.\n */\nfunction finiteHint(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : undefined;\n}\n\n/** Sends batches through the consumer's transport function. */\nexport class CustomTransport extends StatusTransport {\n /**\n * Sends one batch through the configured transport function.\n * @param batch Batch to send.\n * @returns Promise that resolves to the records lost in a send that ends without an error.\n * @throws TransportError when the batch is not accepted.\n */\n async send(batch: LogBatch): Promise<number> {\n this.assertContext(batch);\n const { transport } = this.config;\n\n // Without a transport the records have no destination. An empty batch loses nothing.\n if (!transport || batch.records.length === 0) {\n return batch.records.length;\n }\n\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return batch.records.length;\n }\n\n const kind = batchKind(batch, this.config);\n const request = toTransportRequest(batch, serialized, kind);\n request.signal = this.cancellation.signal;\n\n let response: unknown;\n\n try {\n // A transport that never settles would hold a dispatch slot forever. The deadline frees it.\n response = await withDeadline(\n // Inside these scopes the capture modules skip requests and console lines. A request\n // made after an await falls outside the scopes, and network capture warns about it.\n this.untilCancelled(\n trackTransportCall(() =>\n runAsLibraryRequest(() => runAsLibraryConsole(() => transport(request))),\n ),\n ),\n this.config.delivery.requestTimeoutMs,\n );\n } catch (error) {\n // The pipeline reports the thrown error. All we do here is classify it.\n const deadline = error instanceof DeadlineError ? error : undefined;\n const kind = deadline ? \"timeout\" : \"transient\";\n const message = deadline?.message ?? \"The custom transport failed.\";\n\n throw new TransportError(kind, message, undefined, undefined, undefined, error);\n }\n\n this.assertContext(batch);\n if (!isResponse(response)) {\n this.diagnostics.report(\n \"transport.http_error\",\n \"The custom transport returned no valid status. The library sends the batch again later.\",\n { batchId: batch.id },\n );\n throw new TransportError(\"transient\", \"The custom transport returned no valid status.\");\n }\n\n const { status } = response;\n\n if (status >= HTTP_SUCCESS_MIN && status < HTTP_SUCCESS_END) {\n this.accept(kind, response.sampling, response.date);\n return 0;\n }\n\n throw this.reject(status, batch.id, kind, {\n retryAfterMs: finiteHint(response.retryAfterMs),\n maxBytes: finiteHint(response.maxBytes),\n });\n }\n}\n","// src/transport/exit-flush.ts\n//\n// Flushes buffered batches on exit with sendBeacon, a keepalive fetch or emergency storage.\n// It runs during unload, so nothing in here awaits. A hidden document is still running, so it\n// gets a normal flush.\n\nimport {\n BEACON_LIMIT_BYTES,\n CONTENT_TYPE_TEXT_PLAIN,\n HEADER_BATCH_ID,\n HEADER_CONTENT_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ExitTransport, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { saveToEmergencyQueue } from \"../storage/emergency-queue\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { getFin } from \"../utils/openfin\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { toTransportRequest } from \"./custom-transport\";\nimport { batchKind, endpointFor, serializeBatch } from \"./serializers/select\";\n\n/**\n * Late flushes allowed in one page leave. An onDrop hook that logs would otherwise start a new one\n * for each loss it reports, a microtask loop that never lets the closing page yield.\n */\nconst LATE_FLUSH_LIMIT = 8;\n\n/** The lifecycle event or manual action that starts an exit flush. */\nexport type ExitReason = \"hidden\" | \"pagehide\" | \"freeze\" | \"openfin-close\" | \"shutdown\";\n\n/**\n * The browser's answer to a beacon. `refused` means the in-flight budget is full.\n * `unavailable` means the host has no usable sendBeacon.\n */\ntype BeaconOutcome = \"sent\" | \"refused\" | \"unavailable\";\n\n/** Lets us read navigator.sendBeacon without global DOM type assertions. */\ninterface BeaconGlobal {\n navigator?: { sendBeacon?: (url: string, data: Blob) => boolean };\n}\n\n/** Dependencies of ExitFlush. */\nexport interface ExitFlushDeps {\n /** The active configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Drains all buffered and unconfirmed records into one batch per kind. */\n drainForExit: () => LogBatch[];\n /**\n * Runs a normal flush with headers, gzip and retry. Used for a hidden document.\n * It doesn't touch an in-flight batch.\n */\n flushAlive: () => unknown;\n /**\n * Returns the headers that the HTTP transport sent last, or undefined. sendBeacon can't set\n * a header, so when there are headers the exit flush uses a keepalive fetch.\n */\n exitHeaders: () => Record<string, string> | undefined;\n /**\n * Returns the bytes of the HTTP transport's keepalive requests that haven't settled, or\n * undefined without an HTTP transport. A hidden page's sends use the exit sends' budget.\n */\n keepaliveInFlight: () => number | undefined;\n /** Receives the records that the exit flush loses. */\n onLoss?: LossReporter;\n /** Pushes the open metric interval's points into the buffers. */\n beforeExit?: () => void;\n}\n\n/**\n * Flushes pending telemetry on document unload, with sendBeacon, a keepalive fetch or\n * emergency storage.\n */\nexport class ExitFlush {\n /** True while we are listening for the unload events. */\n private installed = false;\n\n /**\n * True after a pagehide with no later pageshow. The batch timers won't fire in a closing\n * document, so a record that arrives now has to take the exit path.\n */\n private left = false;\n\n /** True while a late exit flush waits on its microtask, so one task's records go together. */\n private lateQueued = false;\n\n /** Late flushes in this page leave, up to LATE_FLUSH_LIMIT. */\n private lateFlushes = 0;\n\n /** True while beforeExit pushes the open metric points, which the running flush then takes. */\n private collecting = false;\n\n /**\n * Bytes in flight against the browser's one budget for beacons and keepalive fetches. It\n * starts at the transport's keepalive sends, and each batch of the current exit flush adds to it.\n */\n private keepaliveBytes = 0;\n\n /**\n * Bytes that the exit sends of this page leave put in flight. A late flush adds them, because\n * nothing tracks an exit send's completion and the browser rejects a send over its budget.\n */\n private leaveBytes = 0;\n\n /** Flushes on visibilitychange when the document becomes hidden. */\n private readonly onVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n this.flush(\"hidden\");\n }\n };\n\n /** Flushes on the window's pagehide event. */\n private readonly onPageHide = (): void => {\n this.left = true;\n this.leaveBytes = 0;\n this.lateFlushes = 0;\n this.flush(\"pagehide\");\n };\n\n /** Returns to the normal path when the back/forward cache restores the page. */\n private readonly onPageShow = (): void => {\n this.left = false;\n this.leaveBytes = 0;\n };\n\n /** Flushes on the document's freeze event. */\n private readonly onFreeze = (): void => {\n this.flush(\"freeze\");\n };\n\n /** Flushes on the OpenFin close-requested event. */\n private readonly onOpenFinClose = (): void => {\n this.flush(\"openfin-close\");\n };\n\n /**\n * @param deps Injected configuration, diagnostics, and drain callback.\n */\n constructor(private readonly deps: ExitFlushDeps) {}\n\n /** Attaches the unload listeners to the document, the window and OpenFin. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n if (typeof document !== \"undefined\") {\n // visibilitychange and freeze fire on the document. pagehide fires on the window.\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n document.addEventListener(\"freeze\", this.onFreeze);\n }\n\n addEventListener(\"pagehide\", this.onPageHide);\n addEventListener(\"pageshow\", this.onPageShow);\n\n const me = getFin()?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not subscribe to close-requested.\",\n () => {\n me?.on?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /** Removes all unload listeners and subscriptions. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n // Without the pageshow listener the flag can't clear, and a paused or stopped sender sends\n // nothing through this path.\n this.left = false;\n this.leaveBytes = 0;\n\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.onVisibility);\n document.removeEventListener(\"freeze\", this.onFreeze);\n }\n\n removeEventListener(\"pagehide\", this.onPageHide);\n removeEventListener(\"pageshow\", this.onPageShow);\n\n const me = getFin()?.me;\n this.deps.diagnostics.guard(\n \"openfin.unavailable\",\n \"The library could not unsubscribe from close-requested.\",\n () => {\n me?.removeListener?.(\"close-requested\", this.onOpenFinClose);\n },\n );\n }\n\n /**\n * Sends a record that reached the sender after pagehide with an exit send on a microtask, so\n * all records of one task go in one send. A web-vitals report arrives this late on a page leave.\n */\n flushLate(): void {\n if (!this.left || this.collecting || this.lateQueued) {\n return;\n }\n\n if (this.lateFlushes >= LATE_FLUSH_LIMIT) {\n return;\n }\n\n this.lateQueued = true;\n this.lateFlushes++;\n queueMicrotask(() => {\n this.lateQueued = false;\n\n // A pageshow or an uninstall in between means the page stays or the sender stopped.\n if (this.left) {\n this.flush(\"pagehide\");\n }\n });\n }\n\n /**\n * Drains pending records synchronously and sends them with a beacon, a keepalive fetch or\n * emergency storage. A hidden document gets a normal flush. Never awaits and never throws,\n * because the caller is an unload listener.\n * @param reason Reason code of the flush.\n */\n flush(reason: ExitReason): void {\n const { config, diagnostics } = this.deps;\n\n // Runs first, so that the drain below also takes the open metric interval's points.\n // The points it pushes go out with this flush, so they mustn't use up a late flush.\n this.collecting = true;\n diagnostics.guard(\"pipeline.crashed\", \"The metric points before the exit flush failed.\", () => {\n this.deps.beforeExit?.();\n });\n this.collecting = false;\n\n // hidden fires on every tab switch, and the document keeps running. A normal flush keeps\n // the headers, gzip and the retry, none of which a beacon has. The in-flight batches\n // complete on their own. Taking them here would send the records again under a new id.\n if (reason === \"hidden\") {\n this.flushAlive();\n return;\n }\n\n if (config.transport) {\n this.flushCustom(reason, config.transportOnExit);\n return;\n }\n\n const url = this.endpointUrl();\n if (url === null) {\n return;\n }\n\n // A hidden flush's keepalive sends can still be in flight, so start from the transport's count.\n // An earlier exit flush's sends aren't in it, so a late flush adds this leave's own sends.\n const inFlight = this.deps.keepaliveInFlight() ?? 0;\n this.keepaliveBytes = inFlight + (this.left ? this.leaveBytes : 0);\n\n for (const batch of this.deps.drainForExit()) {\n // resolveConfig keeps only a valid absolute metricsEndpoint and tracesEndpoint. A traces\n // batch without tracesEndpoint has no destination.\n const kind = batchKind(batch, config);\n const target = kind === \"logs\" ? url.href : endpointFor(kind, config);\n if (target) {\n this.flushBatch(batch, reason, new URL(target));\n } else {\n diagnostics.count(\"record.dropped_no_destination\");\n }\n }\n\n if (this.left) {\n this.leaveBytes = this.keepaliveBytes - inFlight;\n }\n }\n\n /**\n * Sends one exit batch with a beacon, a keepalive fetch or emergency storage.\n * @param batch Batch to send.\n * @param reason Reason code of the flush.\n * @param url Endpoint of the batch.\n */\n private flushBatch(batch: LogBatch, reason: ExitReason, url: URL): void {\n const { config } = this.deps;\n\n if (batch.records.length === 0) {\n return;\n }\n\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n return;\n }\n\n // An oversized payload goes to the synchronous localStorage queue, because localStorage\n // is the only storage that accepts a write without an await.\n const bytes = estimateBytes(serialized.body);\n if (bytes > BEACON_LIMIT_BYTES) {\n this.park(batch);\n return;\n }\n\n // The batch ID and the reason go in query parameters, because a beacon can't set a header and\n // a text/plain fetch with one would need a preflight.\n url.searchParams.set(QUERY_PARAM_BATCH_ID, batch.id);\n url.searchParams.set(QUERY_PARAM_EXIT_REASON, reason);\n\n const target = url.toString();\n\n const custom = this.deps.exitHeaders();\n const typedHeaders = (): Headers => {\n const headers = new Headers(custom);\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n return headers;\n };\n\n // sendBeacon can't set a header, and an ingest server that needs the authorization header\n // drops a beacon. Send the last headers with a keepalive fetch instead.\n if (custom) {\n this.keepaliveFetch(target, batch, serialized.body, bytes, reason, typedHeaders);\n return;\n }\n\n // A headers function has no cached result until it has been called once. The server refuses\n // a beacon without the headers, so let the next page load send the batch with them.\n if (config.headers) {\n this.park(batch);\n return;\n }\n\n // A same-origin request needs no preflight, so it can carry the serializer's content type.\n // A stock OpenTelemetry Collector answers 415 to text/plain and the batch is lost.\n if (this.isSameOrigin(url)) {\n this.keepaliveFetch(target, batch, serialized.body, bytes, reason, typedHeaders);\n return;\n }\n\n // text/plain and no other header keep the request \"simple\", so the browser sends no preflight.\n const plain = (): Headers => new Headers({ [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN });\n\n // sendBeacon always sends the cookies, whatever `credentials` says. Only an app that asked for\n // cookies gets a beacon, or a session cookie on a parent domain would reach the ingest server.\n const wantsCookies = config.credentials === \"include\";\n if (!wantsCookies) {\n this.keepaliveFetch(target, batch, serialized.body, bytes, reason, plain);\n return;\n }\n\n const outcome = this.beacon(target, serialized.body);\n if (outcome === \"sent\") {\n // Count the beacon, or a later same-origin fetch would go over the budget they share.\n this.keepaliveBytes += bytes;\n return;\n }\n\n // A refusal means the in-flight budget is full, and nothing retries a send while the document\n // closes. Mark the shared budget as used up, so a later keepalive fetch is parked, not lost.\n if (outcome === \"refused\") {\n this.keepaliveBytes = BEACON_LIMIT_BYTES;\n this.park(batch);\n return;\n }\n\n this.keepaliveFetch(target, batch, serialized.body, bytes, reason, plain);\n }\n\n /**\n * Checks whether the endpoint is on the page's origin, where a request needs no CORS preflight.\n * @param url Endpoint of the batch.\n * @returns False for another origin, for an opaque origin, and when the origin global and\n * location disagree or the host has no location.\n */\n private isSameOrigin(url: URL): boolean {\n if (typeof location === \"undefined\") {\n return false;\n }\n\n // Two opaque origins both read \"null\" but are never the same origin, for example a file:\n // page in Firefox.\n const isOpaque = url.origin === \"null\";\n\n // The origin global is \"null\" in a frame sandboxed without allow-same-origin, while location\n // still shows the URL's origin.\n const matchesGlobal = url.origin === globalThis.origin;\n\n // A page's script can replace the origin global with `var origin = \"...\"`, but it can't\n // replace location. Without this check, that page would send JSON to another origin.\n const matchesLocation = url.origin === location.origin;\n\n return !isOpaque && matchesGlobal && matchesLocation;\n }\n\n /** Runs a hidden document's normal flush, and reports it if it throws or rejects. */\n private flushAlive(): void {\n const { diagnostics } = this.deps;\n const message = \"The flush of the hidden document failed.\";\n\n diagnostics.guard(\"pipeline.crashed\", message, () => {\n void Promise.resolve(this.deps.flushAlive()).catch((error: unknown) => {\n diagnostics.report(\"pipeline.crashed\", message, undefined, error);\n });\n });\n }\n\n /**\n * Hands the pending records to a custom transport's exit hook, because a closing page can't\n * wait for the async transport. Without a hook, or when the hook refuses the batch, the\n * batch goes to the emergency queue and the next page load sends it.\n * @param reason Reason code of the flush.\n * @param onExit The custom transport's synchronous exit hook.\n */\n private flushCustom(reason: ExitReason, onExit: ExitTransport | undefined): void {\n const { config, diagnostics } = this.deps;\n\n for (const batch of this.deps.drainForExit()) {\n const serialized = this.serialize(batch, reason);\n if (!serialized) {\n continue;\n }\n\n const request = toTransportRequest(batch, serialized, batchKind(batch, config));\n const accepted =\n onExit !== undefined &&\n diagnostics.guard(\"transport.http_error\", \"The transportOnExit hook threw an error.\", () =>\n runAsLibraryRequest(() => onExit(request)),\n ) === true;\n\n if (!accepted) {\n this.park(batch);\n }\n }\n }\n\n /**\n * Parks a batch in the localStorage emergency queue for the next page load. With the storage\n * backend \"memory\" or \"none\" the app wants nothing kept on the device, so the batch is lost.\n * @param batch Batch that the exit flush can't send.\n */\n private park(batch: LogBatch): void {\n const { config, diagnostics, onLoss } = this.deps;\n\n const { backend } = config.storage;\n if (backend === \"memory\" || backend === \"none\") {\n onLoss?.(\"not_stored\", batch.records, [batch.id]);\n return;\n }\n\n saveToEmergencyQueue(batch, diagnostics, onLoss);\n }\n\n /**\n * Serializes the exit batch, and reports a serializer that throws.\n * @param batch Batch to serialize.\n * @param reason Reason code of the flush.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\n private serialize(batch: LogBatch, reason: ExitReason): SerializedBatch | undefined {\n const serialized = serializeBatch(\n this.deps.config,\n batch,\n this.deps.diagnostics,\n `The ${reason} exit flush could not serialize its batch.`,\n );\n\n if (!serialized) {\n this.deps.onLoss?.(\"unserializable\", batch.records, [batch.id]);\n }\n\n return serialized;\n }\n\n /**\n * Parses the configured endpoint URL.\n * @returns URL instance or null if missing or invalid.\n */\n private endpointUrl(): URL | null {\n const { endpoint } = this.deps.config;\n if (!endpoint) {\n return null;\n }\n\n const url = this.deps.diagnostics.guard(\n \"config.invalid\",\n `The exit flush cannot use the endpoint ${endpoint}.`,\n () => new URL(endpoint),\n );\n\n return url ?? null;\n }\n\n /**\n * Sends the payload as text/plain with navigator.sendBeacon.\n * @param url Target endpoint URL with query parameters.\n * @param body Serialized payload string.\n * @returns The browser's answer.\n */\n private beacon(url: string, body: string): BeaconOutcome {\n const outcome = this.deps.diagnostics.guard<BeaconOutcome>(\n \"transport.http_error\",\n \"The sendBeacon call failed.\",\n () => {\n // Call sendBeacon on navigator so that it keeps its receiver. A detached sendBeacon\n // throws when called.\n const nav = (globalThis as BeaconGlobal).navigator;\n if (!nav?.sendBeacon) {\n return \"unavailable\";\n }\n\n // Use text/plain to avoid a CORS preflight. During unload a preflight usually doesn't\n // complete, and the browser then drops the beacon without an error.\n const accepted = nav.sendBeacon(url, new Blob([body], { type: CONTENT_TYPE_TEXT_PLAIN }));\n return accepted ? \"sent\" : \"refused\";\n },\n );\n\n // A throw isn't a refusal. It means the method is there but unusable, and the keepalive\n // fetch can still succeed.\n return outcome ?? \"unavailable\";\n }\n\n /**\n * Sends the exit POST with fetch and `keepalive: true`. A keepalive request continues\n * after the document closes, whereas the browser cancels a plain fetch at page close.\n * A fetch that fails while the document is alive parks the batch in the emergency queue, and\n * the server drops a second copy by its batch id. A rejection after the close parks nothing.\n * @param url Target endpoint URL.\n * @param batch Batch in the payload.\n * @param body Serialized payload string.\n * @param bytes Size of the body, which flushBatch has measured already.\n * @param reason Reason code of the flush.\n * @param headers Builds the request headers. To another origin without `headers` that is only\n * a text/plain content type. A header value outside ISO-8859-1 makes the Headers constructor\n * throw.\n */\n private keepaliveFetch(\n url: string,\n batch: LogBatch,\n body: string,\n bytes: number,\n reason: ExitReason,\n headers: () => Headers,\n ): void {\n const { config, diagnostics } = this.deps;\n // A rejection only arrives while the document is alive, and the next page load then sends\n // the batch.\n const park = (): void => {\n this.park(batch);\n };\n\n // The browser rejects a fetch over the budget after the document closes. By then park()\n // doesn't run, and the batch is lost.\n if (this.keepaliveBytes + bytes > BEACON_LIMIT_BYTES) {\n park();\n return;\n }\n this.keepaliveBytes += bytes;\n\n const started = diagnostics.guard(\"transport.http_error\", \"The keepalive fetch failed.\", () => {\n // Network capture skips a request that starts in this scope. Its ignoreUrls entry misses\n // an endpoint such as http://LOCALHOST/, because new URL() rewrites the host in lower case.\n void runAsLibraryRequest(() =>\n fetch(url, {\n method: \"POST\",\n body,\n headers: headers(),\n credentials: config.credentials,\n keepalive: true,\n }),\n ).catch((error: unknown) => {\n diagnostics.report(\"transport.http_error\", \"The exit flush failed.\", { reason }, error);\n park();\n });\n return true;\n });\n\n if (started !== true) {\n park();\n }\n }\n}\n","import type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\n\n/** One HTTP transport's header cache. The worker path shares its fallback transport's cache. */\ninterface CachedHeaders {\n source: unknown;\n endpoint: string | null;\n metricsEndpoint: string | null;\n tracesEndpoint: string | null;\n headers: Record<string, string>;\n}\n\nconst caches = new WeakMap<object, CachedHeaders>();\n\n/** Returns the last headers, but only while their source and all destinations are unchanged. */\nexport function lastHeaders(\n owner: object,\n config: ResolvedConfig,\n): Record<string, string> | undefined {\n const { headers } = config;\n if (!headers) {\n return undefined;\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const cached = caches.get(owner);\n const current =\n cached?.source === headers &&\n cached.endpoint === config.endpoint &&\n cached.metricsEndpoint === config.metricsEndpoint &&\n cached.tracesEndpoint === config.tracesEndpoint;\n return current ? cached.headers : undefined;\n}\n\n/** Resolves a headers function on the main thread and keeps its result for the exit flush. */\nexport async function resolveHeaders(\n owner: object,\n config: ResolvedConfig,\n diagnostics: Diagnostics,\n): Promise<Record<string, string>> {\n const { headers } = config;\n if (!headers) {\n return {};\n }\n if (typeof headers !== \"function\") {\n return headers;\n }\n\n const { endpoint, metricsEndpoint, tracesEndpoint } = config;\n const resolved = await diagnostics.guardAsync(\n \"transport.http_error\",\n \"The headers() function threw an error.\",\n () => Promise.resolve(headers()),\n );\n if (resolved) {\n caches.set(owner, {\n source: headers,\n endpoint,\n metricsEndpoint,\n tracesEndpoint,\n headers: resolved,\n });\n }\n\n return resolved ?? {};\n}\n\n/** Forgets rejected credentials before the headers function is called again. */\nexport function resetHeaders(owner: object): void {\n caches.delete(owner);\n}\n","// src/transport/http-transport.ts\n//\n// Serializes, compresses and sends log batches over HTTP. Every failure is classified,\n// reported and thrown. The caller that owns storage decides what happens to a rejected batch.\n\nimport {\n BEACON_LIMIT_BYTES,\n COMPRESSION_THRESHOLD_BYTES,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_FORBIDDEN,\n HTTP_PAYLOAD_TOO_LARGE,\n HTTP_UNAUTHORIZED,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BatchKind } from \"../models/config\";\nimport type { SerializedBatch } from \"../models/serializer\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { isOnline } from \"../utils/platform\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { gzip } from \"./compression\";\nimport { lastHeaders, resetHeaders, resolveHeaders } from \"./headers\";\nimport { parseRetryAfter, TransportError } from \"./errors\";\nimport { isOtlpBatch, maxBytesOf, needsBody, readOptionalBody } from \"./response-body\";\nimport { batchKind, endpointFor } from \"./serializers/select\";\nimport { StatusTransport } from \"./status-transport\";\n\n/** Advice for an HTTP send answered with a 401 or a 403, on the main thread or in the worker. */\nexport const CREDENTIAL_ADVICE =\n \"In a cross-origin iframe, the session cookie is a third-party cookie. The browser \" +\n \"often blocks it. Forward the records to the platform document. As an alternative, \" +\n \"issue the cookie with the Partitioned attribute.\";\n\n/** Body of one request, either text or gzip bytes. */\ntype RequestBody = string | Uint8Array<ArrayBuffer>;\n\n/** A response, and the body text when the library uses it. */\ninterface Answer {\n response: Response;\n /** A 413's size hint or an OTLP 2xx's partialSuccess. Absent when not read or too large. */\n body?: string;\n}\n\n/** Lets us read document.visibilityState without global DOM type assertions. */\ninterface DocumentGlobal {\n document?: { visibilityState?: string };\n}\n\n/**\n * Sends serialized log batches over HTTP. Resolves headers, applies gzip compression and\n * classifies errors.\n */\nexport class HttpTransport extends StatusTransport {\n /** Body bytes of this transport's keepalive requests that haven't settled yet. */\n private keepaliveBytes = 0;\n\n /**\n * Sends one log batch over HTTP. A metrics batch goes to metricsEndpoint and a traces batch\n * to tracesEndpoint. A batch without an endpoint goes nowhere.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @returns Promise that resolves to the records lost in a send that ends without an error.\n * @throws TransportError on transient, throttled, 413, or permanent network failures.\n */\n async send(batch: LogBatch, onKeepalive?: () => void): Promise<number> {\n this.assertContext(batch);\n const { config } = this;\n const kind = batchKind(batch, config);\n const endpoint = endpointFor(kind, config);\n\n // A traces batch without tracesEndpoint has no destination. Count the drop.\n if (!endpoint) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n return batch.records.length;\n }\n\n if (batch.records.length === 0) {\n return 0;\n }\n\n return this.post(batch, kind, endpoint, onKeepalive);\n }\n\n /**\n * Returns the headers for the exit flush, because a closing document can't await headers().\n * @returns The static headers, the last result of the current headers function, or undefined.\n */\n lastHeaders(): Record<string, string> | undefined {\n return lastHeaders(this, this.config);\n }\n\n /**\n * Returns the body bytes of the keepalive requests that haven't settled. The browser has one\n * budget for them and the exit sends, so the exit flush starts its count from this number.\n * @returns Bytes in flight, or 0.\n */\n keepaliveInFlight(): number {\n return this.keepaliveBytes;\n }\n\n /**\n * Serializes, encodes and sends a batch. Throws a classified TransportError\n * on failure.\n * @param batch Batch to deliver.\n * @param kind Kind of the batch. The caller reads it together with the endpoint.\n * @param endpoint Ingest URL. The caller reads it once, so a reconfigure during the send\n * can't change it.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @returns The records lost in an accepted batch, or all of them when serializing fails.\n */\n private async post(\n batch: LogBatch,\n kind: BatchKind,\n endpoint: string,\n onKeepalive: (() => void) | undefined,\n ): Promise<number> {\n const serialized = this.serialize(batch);\n\n if (!serialized) {\n return batch.records.length;\n }\n\n const otlp = isOtlpBatch(kind, this.config.serializer);\n let answer = await this.attempt(batch, endpoint, serialized, otlp, onKeepalive);\n this.assertContext(batch);\n\n // A token can expire between two headers() calls, so send once more with fresh\n // headers. A second 401 or 403 drops the batch.\n if (\n this.rejectsCredentials(answer.response.status) &&\n typeof this.config.headers === \"function\"\n ) {\n resetHeaders(this);\n answer = await this.attempt(batch, endpoint, serialized, otlp, onKeepalive);\n this.assertContext(batch);\n }\n\n const { response, body } = answer;\n\n if (response.ok) {\n // The server must list each header in Access-Control-Expose-Headers, or it reads as null.\n const { headers } = response;\n this.accept(kind, headers.get(HEADER_SAMPLING), headers.get(HEADER_DATE));\n return body === undefined ? 0 : this.reportPartial(batch, kind, body);\n }\n\n const status = response.status;\n const retryAfterMs = parseRetryAfter(response.headers.get(HEADER_RETRY_AFTER));\n const maxBytes =\n status === HTTP_PAYLOAD_TOO_LARGE && body !== undefined ? this.readMaxBytes(body) : undefined;\n\n throw this.reject(status, batch.id, kind, {\n retryAfterMs,\n maxBytes,\n advice: CREDENTIAL_ADVICE,\n });\n }\n\n /**\n * Checks whether a status rejects the credentials.\n * @param status HTTP status code.\n * @returns True for 401 and 403.\n */\n private rejectsCredentials(status: number): boolean {\n return status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN;\n }\n\n /**\n * Resolves the headers, encodes the body and sends one request. One deadline covers all\n * three steps, otherwise a headers() that never settles holds a dispatch slot forever.\n * @param batch Batch to deliver.\n * @param endpoint Ingest URL.\n * @param serialized Serialized batch.\n * @param otlp True when the batch is in an OTLP format, so a 2xx can carry a partialSuccess.\n * @param onKeepalive Runs when the request starts with keepalive.\n * @returns Promise that resolves to the response and the body text its status needs.\n * @throws TransportError on timeout or network failure.\n */\n private async attempt(\n batch: LogBatch,\n endpoint: string,\n serialized: SerializedBatch,\n otlp: boolean,\n onKeepalive: (() => void) | undefined,\n ): Promise<Answer> {\n const deadline = Date.now() + this.config.delivery.requestTimeoutMs;\n\n // Headers ignores case in header names, so a config header can't duplicate one set below.\n const headers = new Headers(await this.before(this.resolveHeaders(), deadline, endpoint));\n headers.set(HEADER_CONTENT_TYPE, serialized.contentType);\n headers.set(HEADER_BATCH_ID, batch.id);\n headers.set(HEADER_ATTEMPT, String(batch.attempts));\n\n const body = await this.before(this.encodeBody(serialized.body), deadline, endpoint);\n this.assertContext(batch);\n if (typeof body !== \"string\") {\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n\n const bytes = typeof body === \"string\" ? estimateBytes(body) : body.byteLength;\n if (!this.keepalive(bytes)) {\n return this.dispatch(endpoint, headers, body, deadline, false, otlp);\n }\n\n // A keepalive request continues after unload, so the exit flush must not send the batch\n // again.\n onKeepalive?.();\n\n // Count the request until it settles either way, or a failure would leak its bytes and the\n // exit flush would park every later batch.\n this.keepaliveBytes += bytes;\n try {\n return await this.dispatch(endpoint, headers, body, deadline, true, otlp);\n } finally {\n this.keepaliveBytes -= bytes;\n }\n }\n\n /**\n * Waits for a step until the deadline.\n * @param work Step to wait for. It never rejects, so only the deadline rejects here.\n * @param deadline Epoch time in milliseconds at which the request times out.\n * @param endpoint Ingest URL of the request, for the timeout report.\n * @returns Promise that resolves to the step's value.\n * @throws TransportError of kind \"timeout\" at the deadline.\n */\n private async before<T>(work: Promise<T>, deadline: number, endpoint: string): Promise<T> {\n try {\n return await withDeadline(this.untilCancelled(work), Math.max(0, deadline - Date.now()));\n } catch {\n if (this.cancellation.signal.aborted) {\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n }\n throw this.timeout(endpoint);\n }\n }\n\n /**\n * Reports a timeout and builds its error.\n * @param endpoint Ingest URL of the request.\n * @returns TransportError of kind \"timeout\".\n */\n private timeout(endpoint: string): TransportError {\n const waited = String(this.config.delivery.requestTimeoutMs);\n const message = `The request took longer than ${waited} ms.`;\n\n this.diagnostics.report(\"transport.timeout\", message, { endpoint });\n return new TransportError(\"timeout\", message);\n }\n\n /**\n * Compresses the serialized payload when the config sets gzip and the payload is at or\n * above the threshold.\n * @param text Serialized payload string.\n * @returns Promise that resolves to the original string or the compressed byte array.\n */\n private async encodeBody(text: string): Promise<RequestBody> {\n const { config } = this;\n if (config.compression !== ENCODING_GZIP || estimateBytes(text) < COMPRESSION_THRESHOLD_BYTES) {\n return text;\n }\n\n const compressed = await this.diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not compress the payload.\",\n () => gzip(text),\n );\n\n return compressed ?? text;\n }\n\n /**\n * Sends the HTTP POST request with a timeout, and maps network errors to\n * TransportError.\n * @param endpoint Ingest URL.\n * @param headers HTTP request headers.\n * @param body Request body string or byte array.\n * @param deadline Epoch time in milliseconds at which the request times out.\n * @param keepalive True if the request continues after unload.\n * @param otlp True when the batch is in an OTLP format, so a 2xx can carry a partialSuccess.\n * @returns Promise that resolves to the response and the body text its status needs.\n * @throws TransportError on network failure, timeout, or offline status.\n */\n private async dispatch(\n endpoint: string,\n headers: Headers,\n body: RequestBody,\n deadline: number,\n keepalive: boolean,\n otlp: boolean,\n ): Promise<Answer> {\n const { config } = this;\n const controller = new AbortController();\n const cancel = (): void => {\n controller.abort();\n };\n this.cancellation.signal.addEventListener(\"abort\", cancel, { once: true });\n if (this.cancellation.signal.aborted) {\n controller.abort();\n }\n // The fetch gets whatever time is left after the headers and the encoding.\n const timer = setTimeout(\n () => {\n controller.abort();\n },\n Math.max(0, deadline - Date.now()),\n );\n unrefTimer(timer);\n\n try {\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n signal: controller.signal,\n cache: \"no-store\",\n keepalive,\n // The OS can stop a hidden page soon, so don't delay its keepalive send.\n priority: keepalive ? \"auto\" : config.delivery.priority,\n }),\n );\n\n if (!needsBody(response, otlp)) {\n return { response };\n }\n\n // Read the body before the finally below disarms the timer and the stop listener,\n // otherwise a body that stalls holds the dispatch slot past the deadline and after stop().\n return {\n response,\n body: await readOptionalBody(response, controller.signal, this.diagnostics),\n };\n } catch {\n if (this.cancellation.signal.aborted) {\n throw new TransportError(\"permanent\", \"The delivery context retired.\");\n }\n if (controller.signal.aborted) {\n throw this.timeout(endpoint);\n }\n throw new TransportError(isOnline() ? \"transient\" : \"offline\", \"A network error occurred.\");\n } finally {\n this.cancellation.signal.removeEventListener(\"abort\", cancel);\n clearTimeout(timer);\n }\n }\n\n /**\n * Checks whether a send uses keepalive. A mobile OS can stop a hidden page without a\n * pagehide, and a keepalive request continues after that. The browser limits the keepalive\n * bodies in flight, and rejects one over that budget after the page may already be gone.\n * @param bytes Size of the request body.\n * @returns True for a hidden document when the body fits next to the keepalive bytes in\n * flight, within BEACON_LIMIT_BYTES.\n */\n private keepalive(bytes: number): boolean {\n const hidden = (globalThis as DocumentGlobal).document?.visibilityState === \"hidden\";\n\n return hidden && this.keepaliveBytes + bytes <= BEACON_LIMIT_BYTES;\n }\n\n /**\n * Reads the optional maxBytes limit from a 413 response body.\n * @param body The 413 body text.\n * @returns The limit in bytes, or undefined.\n */\n private readMaxBytes(body: string): number | undefined {\n return this.diagnostics.guard(\n \"transport.http_error\",\n \"The library could not read the body of the 413 response.\",\n () => maxBytesOf(body),\n );\n }\n\n /**\n * Resolves the configured static or dynamic request headers, and keeps what headers()\n * returned for the exit flush.\n * @returns Promise that resolves to the header map.\n */\n private async resolveHeaders(): Promise<Record<string, string>> {\n return resolveHeaders(this, this.config, this.diagnostics);\n }\n}\n","// src/transport/retry-engine.ts\n//\n// Resends stored log batches in the background, with exponential backoff and jitter.\n// There is only ever one timer, never a chain of timers, because every scheduling path\n// clears the pending timer first.\n\nimport {\n BATCHES_PER_DRAIN,\n DRAIN_LOCK_NAME,\n RETRY_IDLE_DELAY_MS,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type LogBatch, splitBatch } from \"../models/batch\";\nimport type { BatchKind, ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport { type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { isOnline } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { TransportError } from \"./errors\";\nimport { batchKind } from \"./serializers/select\";\nimport type { BatchTransport } from \"./status-transport\";\n\n/**\n * Result of one delivery. \"split\" means storage holds the halves of a refused batch. A number is\n * the delay before a failed batch is tried again.\n */\ntype Outcome = \"next\" | \"split\" | \"stop\" | number;\n\n/**\n * What became of a batch whose live send failed. The pipeline picks its report from this, so\n * the report never promises a resend that can't happen.\n * - \"stored\": storage holds the whole batch, and the drain sends it again.\n * - \"split\": the server said the batch is too large, and storage holds its two halves.\n * - \"rejected\": no later send can succeed, so the engine dropped the batch.\n * - \"not_stored\": storage didn't keep the batch, or kept only one half of a split.\n */\nexport type StoreOutcome = \"stored\" | \"split\" | \"rejected\" | \"not_stored\";\n\n/** What storeFailed() did with a batch, and how many of its records storage holds now. */\nexport interface StoreReport {\n /** What became of the batch. */\n outcome: StoreOutcome;\n /** Records that storage holds after the call. Only one half of a split can be in storage. */\n stored: number;\n}\n\n/**\n * Resends persisted offline batches on a timer, with backoff, a cross-tab drain lock and\n * batch splitting.\n */\nexport class RetryEngine {\n /** The active retry timer handle, or null when no timer is running. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** True while the armed timer is the idle poll. A nudge may bring only that one forward. */\n private idle = false;\n\n /** Consecutive failed deliveries. Feeds the backoff calculation. */\n private attempt = 0;\n\n /** True while a storage drain is running. */\n private draining = false;\n\n /** True after stop(). */\n private stopped = false;\n\n /** Attempt limit for a stored batch. Retention can't change after the delivery stack loads. */\n private readonly maxAttempts: number;\n\n /** Runs on the online event. Resets the attempt count and starts a drain. */\n private readonly onOnline = (): void => {\n this.attempt = 0;\n this.schedule(0);\n };\n\n /**\n * @param storage Storage adapter holding undelivered batches.\n * @param transport HTTP transport for batch delivery.\n * @param diagnostics Diagnostics reporter.\n * @param config Active configuration instance.\n * @param batchesPerDrain Maximum batches processed per drain tick.\n * @param onLoss Receives the records of every batch that the engine drops.\n */\n constructor(\n private readonly storage: StorageAdapter,\n private readonly transport: BatchTransport,\n private readonly diagnostics: Diagnostics,\n private readonly config: ResolvedConfig,\n private readonly batchesPerDrain = BATCHES_PER_DRAIN,\n private readonly onLoss: LossReporter = () => undefined,\n ) {\n this.maxAttempts = storageLimits(config.retention).maxAttempts;\n }\n\n /** Starts the engine. Listens for online events and arms the first timer. */\n start(): void {\n this.stopped = false;\n\n if (typeof addEventListener !== \"undefined\") {\n addEventListener(\"online\", this.onOnline);\n }\n\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n }\n\n /**\n * Schedules an earlier retry when storage receives a new offline batch. It never cuts a\n * backoff or a Retry-After short, otherwise each failed live send would post to that server.\n */\n nudge(): void {\n if (!this.draining && (this.timer === null || this.idle)) {\n this.schedule(this.config.delivery.retryBaseDelayMs);\n }\n }\n\n /**\n * Stores a batch that failed outside the drain loop, under the same rules as the drain.\n * A refused batch is never stored whole, because that would cause another request with a\n * payload the server already refused.\n * @param batch Rejected batch, with its attempt already counted.\n * @param error Failure thrown by the transport.\n * @returns What became of the batch, and the records in storage. A storage call that throws\n * or runs past its deadline rejects instead, and the caller reports it.\n */\n async storeFailed(batch: LogBatch, error: unknown): Promise<StoreReport> {\n const parts = this.toStorable(batch, error);\n\n if (parts.length === 0) {\n return { outcome: \"rejected\", stored: 0 };\n }\n\n let written = 0;\n let stored = 0;\n\n for (const part of parts) {\n if (await this.bounded(this.storage.save(part))) {\n written++;\n stored += part.records.length;\n }\n }\n\n // Only bring the drain forward for a batch that is in storage. With `storage: \"none\"` an\n // early drain would find nothing to send.\n if (written > 0) {\n this.nudge();\n }\n\n if (written < parts.length) {\n return { outcome: \"not_stored\", stored };\n }\n\n return { outcome: parts.length > 1 ? \"split\" : \"stored\", stored };\n }\n\n /** Stops the engine. Removes the listener and clears the pending timer. */\n stop(): void {\n this.stopped = true;\n\n if (typeof removeEventListener !== \"undefined\") {\n removeEventListener(\"online\", this.onOnline);\n }\n\n this.clearTimer();\n }\n\n /**\n * Tries one delivery pass over the stored batches before a context change. The caller sets\n * the deadline.\n * @returns Promise that resolves when this pass stops.\n */\n async flush(): Promise<void> {\n this.stopped = false;\n try {\n await this.drain();\n } finally {\n this.stop();\n }\n }\n\n /**\n * Clears the pending timer, then schedules a drain after the delay.\n * @param delayMs Delay duration in milliseconds.\n * @param idle True for the idle poll, the one wait that a nudge may bring forward.\n */\n private schedule(delayMs: number, idle = false): void {\n if (this.stopped) {\n return;\n }\n\n this.clearTimer();\n this.idle = idle;\n\n const timer = setTimeout(() => {\n void this.drain();\n }, delayMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /**\n * Puts a deadline on a storage call. A call that never settles would keep\n * `draining` true, and this window would run no more drains.\n * @param work Storage promise to bound.\n * @returns The promise's value, or a rejection after the deadline.\n */\n private bounded<T>(work: Promise<T>): Promise<T> {\n return withDeadline(work, STORAGE_DEADLINE_MS);\n }\n\n /** Clears the pending timer if there is one. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Calculates the exponential backoff delay from consecutive failures. Uses full jitter\n * instead of a fixed offset, because with a fixed offset tabs that reconnect together send\n * their requests at the same time.\n * @returns Backoff duration in milliseconds.\n */\n private backoffMs(): number {\n const exponential = Math.min(\n this.config.delivery.retryBaseDelayMs * 2 ** this.attempt,\n this.config.delivery.retryMaxDelayMs,\n );\n\n return Math.random() * exponential;\n }\n\n /** Runs a drain under the origin-wide Web Lock. */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n const lock = lockName(DRAIN_LOCK_NAME, this.config.storage.namespace);\n const ran = await withDrainLock(lock, this.diagnostics, () => this.drainLocked());\n\n // The value is undefined when another window holds the lock. Without this reschedule,\n // one lost lock race would stop all drains in this window.\n if (ran !== true) {\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n }\n } finally {\n this.draining = false;\n }\n }\n\n /**\n * Processes batches while holding the Web Lock, and schedules the next tick.\n * It always resolves, because a throw would leave the engine idle with no armed timer.\n * @returns Promise that resolves to true on completion.\n */\n private async drainLocked(): Promise<true> {\n try {\n if (!isOnline()) {\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n return true;\n }\n\n const batches = await this.bounded(this.storage.take(this.batchesPerDrain));\n\n if (batches.length === 0) {\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n return true;\n }\n\n // A failure blocks only its own batch kind. The other endpoints can still accept batches.\n const blocked = new Set<BatchKind>();\n let delayMs = 0;\n let split = false;\n\n for (const batch of batches) {\n if (this.stopped) {\n return true;\n }\n\n const kind = batchKind(batch, this.config);\n if (blocked.has(kind)) {\n continue;\n }\n\n // A 429 or 503 still holds for this endpoint, so a send now would post through it.\n const throttledMs = this.transport.throttledForMs(batch);\n const outcome = throttledMs > 0 ? throttledMs : await this.deliver(batch);\n if (outcome === \"stop\") {\n return true;\n }\n\n if (outcome === \"split\") {\n split = true;\n } else if (outcome !== \"next\") {\n blocked.add(kind);\n // Keep the longest delay. A shorter one would send before another server's\n // Retry-After.\n delayMs = Math.max(delayMs, outcome);\n }\n }\n\n if (blocked.size > 0) {\n this.schedule(delayMs);\n } else if (batches.length === this.batchesPerDrain) {\n this.schedule(0);\n } else if (split) {\n // The halves are in storage now. Without this they'd wait out the idle poll.\n this.schedule(this.config.delivery.retryBaseDelayMs);\n } else {\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n }\n return true;\n } catch (error) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"The drain loop threw an error.\",\n undefined,\n error,\n );\n this.attempt++;\n this.schedule(this.backoffMs());\n return true;\n }\n }\n\n /**\n * Tries to deliver one batch. Removes it on success, and on failure applies the rule for\n * the failure kind.\n * @param batch Log batch to deliver.\n * @returns \"next\" to continue with the next batch, \"split\" when storage holds the halves of a\n * refused batch, \"stop\" to stop the current drain, or a delay in milliseconds that blocks the\n * batch's kind until the next drain.\n */\n private async deliver(batch: LogBatch): Promise<Outcome> {\n if (batch.attempts >= this.maxAttempts) {\n this.diagnostics.report(\n \"storage.dead_lettered\",\n `The library dropped a batch after ${batch.attempts.toString()} attempts.`,\n { batchId: batch.id, records: batch.records.length },\n );\n this.onLoss(\"max_attempts\", batch.records, [batch.id]);\n await this.bounded(this.storage.remove(batch.id));\n return \"next\";\n }\n\n try {\n await this.transport.send(batch);\n await this.bounded(this.storage.remove(batch.id));\n this.attempt = 0;\n return \"next\";\n } catch (error) {\n if (this.stopped) {\n return \"stop\";\n }\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\" || failure?.kind === \"too_large\") {\n return (await this.replaceStored(batch, error)) ? \"split\" : \"next\";\n }\n\n // Offline stops every kind, because the other endpoints aren't reachable either.\n if (failure?.kind === \"offline\") {\n this.schedule(RETRY_IDLE_DELAY_MS, true);\n return \"stop\";\n }\n\n // A throttle rejects no records. The server only asks for the batch later, so don't bump\n // the stored attempts here. A bump would dead-letter the batch after\n // `retention.maxAttempts` throttled responses.\n if (failure?.kind === \"throttled\") {\n this.attempt++;\n return failure.retryAfterMs ?? this.backoffMs();\n }\n\n await this.bounded(this.storage.bumpAttempts(batch.id, batch.attempts + 1));\n this.attempt++;\n return failure?.retryAfterMs ?? this.backoffMs();\n }\n }\n\n /**\n * Replaces a stored batch with whatever survives its failure. That is the split halves,\n * or nothing after a permanent refusal.\n * @param batch Rejected log batch, already held in storage.\n * @param error Failure thrown by the transport.\n * @returns True when storage kept at least one half.\n */\n private async replaceStored(batch: LogBatch, error: unknown): Promise<boolean> {\n const parts = this.toStorable(batch, error);\n await this.bounded(this.storage.remove(batch.id));\n let kept = false;\n\n for (const part of parts) {\n if (await this.bounded(this.storage.save(part))) {\n kept = true;\n }\n }\n\n return kept;\n }\n\n /**\n * Picks the batches to keep after a failure. A 413 response splits the batch in two, a\n * permanent refusal keeps nothing, and any other failure keeps the batch whole.\n * @param batch Rejected log batch.\n * @param error Failure thrown by the transport.\n * @returns Batches to persist. The array is empty when the engine drops the records.\n */\n private toStorable(batch: LogBatch, error: unknown): LogBatch[] {\n const failure = error instanceof TransportError ? error : undefined;\n\n if (failure?.kind === \"permanent\") {\n this.onLoss(\"rejected\", batch.records, [batch.id]);\n return [];\n }\n\n if (failure?.kind !== \"too_large\") {\n return [batch];\n }\n\n const halves = splitBatch(batch, this.diagnostics);\n\n if (!halves) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n \"One record is larger than the server limit. The library dropped it.\",\n {\n batchId: batch.id,\n bodies: batch.records.map((record) => record.body),\n },\n );\n this.onLoss(\"rejected\", batch.records, [batch.id]);\n return [];\n }\n\n this.diagnostics.report(\n \"transport.batch_split\",\n \"The server refused the batch because it is too large.\",\n {\n from: batch.records.length,\n to: halves[0].records.length,\n serverMaxBytes: failure.maxBytes,\n },\n );\n\n return halves;\n }\n}\n","// src/core/pipeline.ts\n//\n// Buffers the log, metric and trace streams, builds batches and delivers them.\n//\n// Every stream has its own buffer and flush timer, so the exit flush can take every record\n// that hasn't reached the transport yet.\n\nimport {\n ATTR_CLOCK_OFFSET_MS,\n ATTR_LOG_TYPE,\n LOG_TYPE_METRIC,\n LOG_TYPE_SPAN,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { FlushResult } from \"../models/health\";\nimport { estimateBytes } from \"../utils/sanitize\";\nimport type { LogBatch } from \"../models/batch\";\nimport { type LogRecord, nowUnixNano } from \"../models/log-record\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport type { BatchTransport } from \"../transport/status-transport\";\nimport type { RetryEngine, StoreOutcome, StoreReport } from \"../transport/retry-engine\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { ErrorCeiling } from \"./sampling\";\n\n/** Name of a pipeline stream. */\nexport type StreamName = \"logs\" | \"metrics\" | \"traces\";\n\n/** Streams in exit-batch order. The logs get the beacon budget before the spans. */\nconst STREAM_ORDER: readonly StreamName[] = [\"metrics\", \"logs\", \"traces\"];\n\n/**\n * Returns the stream for a record. Each stream builds batches of one kind.\n * @param record Record to evaluate.\n * @returns \"metrics\" for a metric, \"traces\" for a span, otherwise \"logs\".\n */\nfunction streamOf(record: LogRecord): StreamName {\n const type = record.attributes[ATTR_LOG_TYPE];\n\n if (type === LOG_TYPE_METRIC) {\n return \"metrics\";\n }\n\n return type === LOG_TYPE_SPAN ? \"traces\" : \"logs\";\n}\n\n/**\n * What a store call did with a failed batch. \"unknown\" is a call that threw or ran past its\n * deadline, so the batch can still reach storage after the report.\n */\ntype StoreResult = StoreOutcome | \"unknown\";\n\n/** The results the throttle path can get. Only a failed send splits or rejects a batch. */\ntype ThrottledResult = Exclude<StoreResult, \"split\" | \"rejected\">;\n\n/** What a flush counts in its snapshot of the pipeline. */\nexport type FlushCounts = Pick<FlushResult, \"accepted\" | \"stored\" | \"dropped\" | \"pending\">;\n\n/** What a dispatch did with a batch's records. */\ntype BatchEnd = Omit<FlushCounts, \"pending\">;\n\n/**\n * Builds the end of a batch that didn't go out. The records that storage doesn't hold are lost.\n * @param kept Records that storage holds.\n * @param records The batch's record count.\n * @returns The end.\n */\nfunction keptEnd(kept: number, records: number): BatchEnd {\n return { accepted: 0, stored: kept, dropped: records - kept };\n}\n\n/**\n * The text of the send-failure report for each store result. Each one says what happened to\n * the batch and what the library does next, so it never promises a resend that can't happen\n * and never reports a drop it can't be sure of.\n */\nconst SEND_FAILED_TEXT: Record<StoreResult, string> = {\n stored: \"The send failed. The library stored the batch and sends it again later.\",\n split: \"The send failed. The library stored the batch in two parts and sends them again later.\",\n rejected: \"The send failed, and another send would fail too. The library drops the batch.\",\n not_stored:\n \"The send failed, and storage did not keep the batch. \" +\n \"The library drops the records that are not in storage.\",\n unknown:\n \"The send failed. The library could not confirm that storage kept the batch. \" +\n \"The library sends again only the records that are in storage.\",\n};\n\n/** The text of the throttle report for each store result, under the same rule. */\nconst THROTTLED_TEXT: Record<ThrottledResult, string> = {\n stored: \"The server throttles requests. The pipeline stored the batch and did not send it.\",\n not_stored:\n \"The server throttles requests, and storage did not keep the batch. \" +\n \"The library drops the batch.\",\n unknown:\n \"The server throttles requests. The library could not confirm that storage kept the batch. \" +\n \"The library sends the batch later only if it is in storage.\",\n};\n\n/** Batching policy for one record stream. */\nexport interface StreamOptions {\n /** Maximum time in milliseconds a partial batch waits before the pipeline sends it. */\n flushIntervalMs: number;\n /** Maximum records in a batch. At this count the pipeline sends the batch early. */\n batchSize: number;\n}\n\n/** A closed batch in the queue or in flight. */\ninterface Pending {\n /** Batch to deliver. */\n batch: LogBatch;\n /** Resolves when the batch's dispatch ends, or on destroy. */\n done: Promise<void>;\n /** Resolves `done`. */\n resolve: () => void;\n /** What the dispatch did with the records. Unset while they have no final state. */\n end?: BatchEnd;\n}\n\n/** One stream's pending records and the timer that closes a partial batch. */\nclass RecordStream {\n /** Pending records in time order. */\n private pending: LogRecord[] = [];\n\n /** Handle of the armed flush timer, or null when none is pending. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Batching policy for this stream.\n * @param onFlush Called with this stream when a batch is ready to close.\n */\n constructor(\n readonly options: StreamOptions,\n private readonly onFlush: (stream: RecordStream) => void,\n ) {}\n\n /**\n * Adds a record to the buffer. At batchSize records it closes the batch, and below that\n * it starts the interval timer. Without the timer a small batch would wait for the next\n * record, which on a quiet page never comes.\n * @param record Record to enqueue.\n */\n add(record: LogRecord): void {\n this.pending.push(record);\n\n if (this.pending.length >= this.options.batchSize) {\n this.onFlush(this);\n return;\n }\n\n this.arm();\n }\n\n /**\n * Removes and returns all buffered records, and stops the flush timer.\n * @returns Array of buffered records.\n */\n take(): LogRecord[] {\n this.clearTimer();\n\n const records = this.pending;\n this.pending = [];\n\n return records;\n }\n\n /** Number of buffered records. */\n get size(): number {\n return this.pending.length;\n }\n\n /** Buffered records in time order. */\n get records(): readonly LogRecord[] {\n return this.pending;\n }\n\n /** Stops the flush timer. The buffered records stay in place. */\n stop(): void {\n this.clearTimer();\n }\n\n /** Arms the flush timer unless one is already pending. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n this.onFlush(this);\n }, this.options.flushIntervalMs);\n\n this.timer = timer;\n unrefTimer(timer);\n }\n\n /** Clears the pending timer handle if armed. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n\n/** Buffers the log, metric and trace streams, builds batches and sends them over HTTP. */\nexport class LogPipeline {\n /** Buffer instances for the logs, metrics and traces streams. */\n private readonly streams: Record<StreamName, RecordStream>;\n\n /** In-flight batches with no delivery confirmation yet. The exit flush sends them again. */\n private readonly unconfirmed = new Map<string, LogBatch>();\n\n /**\n * In-flight batches whose request went out with keepalive. The exit flush skips them, because\n * that request outlives the page. A retire aborts the request, so it takes them back.\n */\n private readonly keptAlive = new Map<string, LogBatch>();\n\n /** Closed batches waiting for a free dispatch slot. */\n private readonly queue: Pending[] = [];\n\n /** Every batch in the queue or in flight. flushPending waits on them, destroy() resolves them. */\n private readonly open = new Set<Pending>();\n\n /** Ceiling on the ERROR and FATAL records that bypass sampling. */\n private readonly ceiling = new ErrorCeiling();\n\n /** Requests that haven't completed. Capped by delivery.maxConcurrentRequests. */\n private inFlight = 0;\n\n /** True while a pump is queued, so one microtask drains a whole burst. */\n private pumpScheduled = false;\n\n /** True after destroy() stops the pipeline. */\n private stopped = false;\n /** True while `enabled` is false. The records stay in the buffers and in the queue. */\n private paused = false;\n /**\n * Ends the wait of each flushPending() call in progress. hold(true) calls them, so a flush\n * that waits on a queued batch doesn't wait out the pause.\n */\n private readonly waiters = new Set<() => void>();\n /** Encoded byte count of every record in the buffers or in requests. */\n private readonly held = new Map<LogRecord, number>();\n /** Total encoded bytes of the held records. */\n private heldBytes = 0;\n /** True while the overflow storage operation is still running. */\n private persisting = false;\n\n /**\n * Removes completed or dropped records from the buffer counts.\n * @param records Records to remove from the counts.\n */\n private release(records: readonly LogRecord[]): void {\n for (const record of records) {\n this.heldBytes -= this.held.get(record) ?? 0;\n this.held.delete(record);\n }\n }\n\n /**\n * Removes records that haven't reached the transport. A request that was already sent can't\n * be removed.\n * @returns True if a batch or a buffered group was removed.\n */\n private evict(): boolean {\n const pending = this.queue.shift();\n if (pending) {\n this.open.delete(pending);\n this.unconfirmed.delete(pending.batch.id);\n this.release(pending.batch.records);\n pending.end = { accepted: 0, stored: 0, dropped: pending.batch.records.length };\n pending.resolve();\n this.onLoss(\"buffer_full\", pending.batch.records, [pending.batch.id]);\n return true;\n }\n for (const stream of Object.values(this.streams)) {\n const records = stream.take();\n if (records.length) {\n this.release(records);\n this.onLoss(\"buffer_full\", records);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks the buffer limits and applies the overflow rule.\n * @param record New record to add.\n * @returns True if the record can enter the live buffer.\n */\n private admit(record: LogRecord): boolean {\n if (!this.policy) {\n return true;\n }\n const { maxPendingRecords, maxPendingBytes, overflow } = this.policy.buffering;\n // Encode every record, even without a byte budget. A record JSON can't encode is dropped\n // here on its own. Otherwise the transport would drop its whole batch.\n let bytes: number;\n try {\n bytes = estimateBytes(JSON.stringify(record));\n } catch {\n this.onLoss(\"unserializable\", [record]);\n return false;\n }\n const full = (): boolean =>\n (maxPendingRecords !== null && this.held.size >= maxPendingRecords) ||\n (maxPendingBytes !== null && this.heldBytes + bytes > maxPendingBytes);\n // A record larger than the byte budget never fits, so don't evict other records for it.\n const fits = maxPendingBytes === null || bytes <= maxPendingBytes;\n while (fits && full() && overflow === \"drop-oldest\" && this.evict()) {\n /* Remove complete groups until the new record fits or no group remains. */\n }\n if (full()) {\n if (overflow === \"persist\" && !this.persisting) {\n this.persisting = true;\n const batch = this.toBatch([record]);\n void this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not persist an overflow record.\",\n async () => {\n try {\n // Only bring the drain forward for a record that is in storage.\n if (await this.storage.save(batch)) {\n this.retry.nudge();\n }\n } finally {\n this.persisting = false;\n }\n },\n );\n } else {\n this.onLoss(\"buffer_full\", [record]);\n }\n return false;\n }\n this.held.set(record, bytes);\n this.heldBytes += bytes;\n return true;\n }\n\n /**\n * @param transport HTTP transport for live batch delivery.\n * @param storage Storage adapter for offline batch persistence.\n * @param retry Retry engine for redelivering persisted batches.\n * @param diagnostics Diagnostics reporter.\n * @param streamOptions Batching policy per stream, from the batching config.\n * @param routingContextId Returns the delivery context id for a new batch.\n * @param policy Active configuration instance.\n * @param onLoss Receives the records the pipeline loses.\n * @param clockOffset Returns the clock offset for a new log or span record, if known.\n */\n constructor(\n private readonly transport: BatchTransport,\n private readonly storage: StorageAdapter,\n private readonly retry: RetryEngine,\n private readonly diagnostics: Diagnostics,\n streamOptions: Record<StreamName, StreamOptions>,\n private readonly routingContextId?: () => string | undefined,\n private readonly policy?: ResolvedConfig,\n private readonly onLoss: LossReporter = () => undefined,\n private readonly clockOffset: () => number | undefined = () => undefined,\n ) {\n const flush = (stream: RecordStream): void => {\n this.claim(stream);\n };\n\n this.streams = {\n logs: new RecordStream(streamOptions.logs, flush),\n metrics: new RecordStream(streamOptions.metrics, flush),\n traces: new RecordStream(streamOptions.traces, flush),\n };\n }\n\n /**\n * Sets the observed timestamp and adds a record to the pipeline.\n * @param record Record to push.\n */\n push(record: LogRecord): void {\n if (this.stopped) {\n return;\n }\n\n record.observedTimeUnixNano = nowUnixNano();\n const queued = { ...record };\n if (!this.admit(queued)) {\n return;\n }\n this.route(queued);\n }\n\n /**\n * Drains all buffered and unconfirmed in-flight records into exit batches in one step.\n * Records already handed to fetch go out again under a new batch ID, and the server can't\n * deduplicate them. So the exit flush can deliver duplicates. That is intentional: a\n * closing document can't confirm delivery.\n * @returns One batch per stream, metrics first. A stream with no records gets no batch.\n * A mixed batch would send a metric to the logs endpoint.\n */\n drainForExit(): LogBatch[] {\n const inFlight = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n this.unconfirmed.clear();\n this.held.clear();\n this.heldBytes = 0;\n\n return STREAM_ORDER.map((name) =>\n this.toBatch([\n ...inFlight.filter((record) => streamOf(record) === name),\n ...this.streams[name].take(),\n ]),\n ).filter((batch) => batch !== null);\n }\n\n /**\n * Drains like drainForExit(), and adds the batches of the open keepalive requests. A retire\n * calls it after the transport stop aborted those requests, otherwise their records are lost.\n * @returns The keepalive batches first, because they're older, then the exit batches.\n */\n drainForRetire(): LogBatch[] {\n const keptAlive = [...this.keptAlive.values()];\n this.keptAlive.clear();\n\n return [...keptAlive, ...this.drainForExit()];\n }\n\n /**\n * Sends the buffered records through the normal dispatch path, then waits for every batch\n * in the queue and in flight. The throttle check and the concurrency limit apply. A direct\n * send would bypass both.\n * @param expired Resolves at the caller's deadline, if it has one.\n * @returns Promise that resolves to the batches the wait covered, once each one is sent or\n * stored, or on a hold, a destroy or the deadline.\n */\n async flushPending(expired?: Promise<void>): Promise<Pending[]> {\n // A held pipeline sends nothing, and its queued batches can't finish, so don't wait.\n if (this.paused) {\n return [];\n }\n\n // One batch per stream, because a mixed batch would send a metric to the logs endpoint.\n // The claim leaves in-flight batches alone. A second copy under a new ID would be a\n // duplicate the server can't remove.\n if (!this.stopped) {\n for (const name of STREAM_ORDER) {\n this.claim(this.streams[name]);\n }\n }\n\n // Queued batches count too. Otherwise the exit flush would send them again under a new id.\n // A hold stops the queue, so the wait ends there and doesn't last the whole pause. Each\n // waiter goes once its flush settles, otherwise each call would keep memory until a hold.\n const snapshot = [...this.open];\n let stop!: () => void;\n const held = new Promise<void>((resolve) => {\n stop = resolve;\n });\n this.waiters.add(stop);\n try {\n const all = Promise.all(snapshot.map((pending) => pending.done));\n await Promise.race(expired ? [all, held, expired] : [all, held]);\n } finally {\n this.waiters.delete(stop);\n }\n\n return snapshot;\n }\n\n /**\n * Claims the buffered records like flushPending(), then waits for the batches of this call\n * until each one ends, a hold stops the queue or the deadline passes.\n * @param expired Resolves at the caller's deadline.\n * @returns The records of the call's batches by their state when the wait ends. A batch that\n * ends later doesn't change them.\n */\n async flushUntil(expired: Promise<void>): Promise<FlushCounts> {\n const snapshot = await this.flushPending(expired);\n const counts: FlushCounts = { accepted: 0, stored: 0, dropped: 0, pending: 0 };\n\n for (const { batch, end } of snapshot) {\n if (end) {\n counts.accepted += end.accepted;\n counts.stored += end.stored;\n counts.dropped += end.dropped;\n } else {\n counts.pending += batch.records.length;\n }\n }\n\n return counts;\n }\n\n /**\n * Counts the waiting records and the records in requests.\n * @returns Records in the buffers and the queue, and records in dispatch.\n */\n counts(): { pending: number; inFlight: number } {\n const records = (items: Iterable<Pending>): number => {\n let total = 0;\n for (const item of items) {\n total += item.batch.records.length;\n }\n return total;\n };\n\n // Every batch in the queue is also in the open set.\n const queued = records(this.queue);\n\n const buffered = STREAM_ORDER.reduce((total, name) => total + this.streams[name].size, 0);\n\n return { pending: buffered + queued, inFlight: records(this.open) - queued };\n }\n\n /**\n * Stops or starts the dispatch while `enabled` is false. The records stay where they are, and\n * a start sends them right away.\n * @param on True to stop.\n */\n hold(on: boolean): void {\n this.paused = on;\n\n // A flush timer that fires during the hold claims nothing, so the timers can stay.\n if (on) {\n for (const stop of this.waiters) {\n stop();\n }\n return;\n }\n\n for (const name of STREAM_ORDER) {\n this.claim(this.streams[name]);\n }\n this.schedulePump();\n }\n\n /**\n * Checks whether hold(true) is in force.\n * @returns True while the pipeline sends nothing.\n */\n isHeld(): boolean {\n return this.paused;\n }\n\n /**\n * Lists the records that only memory holds.\n * @returns The records in requests and in the queue, then the buffered records.\n */\n records(): LogRecord[] {\n const unconfirmed = [...this.unconfirmed.values()].flatMap((batch) => batch.records);\n return [...unconfirmed, ...STREAM_ORDER.flatMap((name) => this.streams[name].records)];\n }\n\n /**\n * Stops the pipeline without a send, for a discard at shutdown. A request in flight can still\n * reach the server, so its records aren't returned.\n * @returns The records in the queue and in the buffers.\n */\n discard(): LogRecord[] {\n // A queued batch is lost now, and a flush that waits for it must count it so.\n for (const pending of this.queue) {\n pending.end = keptEnd(0, pending.batch.records.length);\n }\n const queued = this.queue.flatMap((pending) => pending.batch.records);\n const buffered = STREAM_ORDER.flatMap((name) => this.streams[name].take());\n this.destroy();\n return [...queued, ...buffered];\n }\n\n /** Stops the flush timers and refuses further records. */\n destroy(): void {\n this.stopped = true;\n this.held.clear();\n this.heldBytes = 0;\n for (const name of STREAM_ORDER) {\n this.streams[name].stop();\n }\n this.queue.length = 0;\n\n // destroy() drops every queued batch, so release any flushPending waiting on one.\n for (const pending of this.open) {\n pending.resolve();\n }\n this.open.clear();\n }\n\n /**\n * Wraps drained records in a batch.\n * @param records Records taken from the buffers, in delivery order.\n * @returns New LogBatch, or null when the drain takes nothing.\n */\n private toBatch(records: [LogRecord, ...LogRecord[]]): LogBatch;\n private toBatch(records: LogRecord[]): LogBatch | null;\n private toBatch(records: LogRecord[]): LogBatch | null {\n if (records.length === 0) {\n return null;\n }\n\n return {\n id: newId(this.diagnostics),\n records,\n createdAt: Date.now(),\n attempts: 0,\n routingContextId: this.routingContextId?.(),\n persistenceNamespace: this.policy?.storage.namespace,\n };\n }\n\n /**\n * Sorts a record into its stream. Sampling has already run: RecordBuilder samples a local\n * record and the runtime samples a forwarded one. Every fault is caught here. A record\n * without `attributes` makes streamOf throw, and an uncaught throw would land in the\n * caller's log call.\n * @param record Record to sort.\n */\n private route(record: LogRecord): void {\n try {\n const name = streamOf(record);\n const stream = this.streams[name];\n\n // Records at or above alwaysSampleFrom bypass sampling upstream, so this ceiling is\n // their only limit. Metric points and spans have level INFO, and a lost point gives a\n // false sum.\n if (\n name === \"logs\" &&\n !this.ceiling.allow(\n record,\n this.policy?.sampling.errorCeiling,\n this.policy?.sampling.errorCeilingWindowMs,\n this.policy?.sampling.alwaysSampleFrom,\n )\n ) {\n this.release([record]);\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n\n // A changing value on a metric point would start a new series, so only logs and spans\n // get it.\n const offset = this.clockOffset();\n if (offset !== undefined && name !== \"metrics\") {\n record.attributes = { ...record.attributes, [ATTR_CLOCK_OFFSET_MS]: offset };\n }\n\n stream.add(record);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The pipeline dropped a record before it reached a stream.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Drains a stream buffer into a new batch and queues it for dispatch. Called by a timer\n * or a flush. An empty buffer produces no batch. Every `take` stops the timer that calls\n * this method.\n * @param stream Stream buffer to drain.\n */\n private claim(stream: RecordStream): void {\n // A held stream keeps its records until hold(false) claims them.\n if (this.paused) {\n return;\n }\n\n this.enqueue(this.toBatch(stream.take()));\n }\n\n /**\n * Queues a batch and schedules the pump on a microtask. Dispatching inline would start\n * a fetch inside the application's log call.\n * @param batch Batch ready for delivery, or null when the drain found no records.\n */\n private enqueue(batch: LogBatch | null): void {\n if (!batch) {\n return;\n }\n\n let resolve!: () => void;\n const done = new Promise<void>((settle) => {\n resolve = settle;\n });\n const pending: Pending = { batch, done, resolve };\n\n this.unconfirmed.set(batch.id, batch);\n this.open.add(pending);\n this.queue.push(pending);\n this.schedulePump();\n }\n\n /** Runs the pump on a microtask. Dispatching inline would start a fetch inside an app call. */\n private schedulePump(): void {\n if (this.pumpScheduled) {\n return;\n }\n\n this.pumpScheduled = true;\n queueMicrotask(() => {\n this.pumpScheduled = false;\n this.pump();\n });\n }\n\n /** Starts queued dispatches up to the concurrency limit. */\n private pump(): void {\n if (this.stopped || this.paused) {\n return;\n }\n while (this.inFlight < (this.policy?.delivery.maxConcurrentRequests ?? 2)) {\n const pending = this.queue.shift();\n if (!pending) {\n return;\n }\n\n this.inFlight++;\n void this.run(pending);\n }\n }\n\n /**\n * Delivers one batch, then frees the concurrency slot and resolves the batch's promise.\n * @param pending Batch to deliver.\n */\n private async run(pending: Pending): Promise<void> {\n const { batch } = pending;\n\n try {\n pending.end = await this.dispatch(batch);\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"A dispatch rejected its promise. This must not occur.\",\n { batchId: batch.id },\n error,\n );\n } finally {\n this.release(batch.records);\n this.inFlight--;\n this.open.delete(pending);\n pending.resolve();\n this.pump();\n }\n }\n\n /**\n * Sends a batch over the HTTP transport. Stores the batch if the transport is throttled\n * or fails.\n * @param batch Batch to deliver.\n * @returns What became of the records, or undefined when that isn't known yet.\n */\n private async dispatch(batch: LogBatch): Promise<BatchEnd | undefined> {\n const total = batch.records.length;\n try {\n // Store the batch while the transport is throttled. Sending here would post a batch\n // through the throttle every flush interval. Leave the attempt count alone, because\n // nothing was sent.\n const throttledMs = this.transport.throttledForMs(batch);\n if (throttledMs > 0) {\n const result = await this.store(batch);\n this.diagnostics.report(\"transport.throttled\", THROTTLED_TEXT[result], {\n batchId: batch.id,\n records: total,\n throttledMs,\n });\n return result === \"unknown\" ? undefined : keptEnd(result === \"stored\" ? total : 0, total);\n }\n\n try {\n // A keepalive request carries on after unload, so the exit flush must not send it\n // again. A failed send still reaches the retry engine through this batch reference.\n const lost = await this.transport.send(batch, () => {\n this.unconfirmed.delete(batch.id);\n this.keptAlive.set(batch.id, batch);\n });\n return { accepted: total - lost, stored: 0, dropped: lost };\n } catch (error) {\n if (this.stopped) {\n return undefined;\n }\n // Increment the attempt count before storing. Left at 0, the batch would exceed\n // STORAGE_LIMITS.maxAttempts by one and the attempt headers would report one too few.\n const report = await this.storeFailed({ ...batch, attempts: batch.attempts + 1 }, error);\n this.diagnostics.report(\n \"transport.http_error\",\n SEND_FAILED_TEXT[report?.outcome ?? \"unknown\"],\n { batchId: batch.id, records: total },\n error,\n );\n // An unknown store has no final state, because a late save can still finish.\n return report ? keptEnd(report.stored, total) : undefined;\n }\n } finally {\n this.unconfirmed.delete(batch.id);\n this.keptAlive.delete(batch.id);\n }\n }\n\n /**\n * Stores a batch that the transport refused. The retry engine splits a 413 and drops a\n * batch the server won't accept.\n * @param batch Batch to persist, with its attempt already counted.\n * @param error Failure thrown by the transport.\n * @returns What became of the batch and the records that storage holds, or undefined when\n * a storage call threw or ran past its deadline. A late save can still finish, so the caller\n * reports no drop then.\n */\n private storeFailed(batch: LogBatch, error: unknown): Promise<StoreReport | undefined> {\n return this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n () => this.retry.storeFailed(batch, error),\n );\n }\n\n /**\n * Stores an undelivered batch, then starts the retry engine. A deadline caps the wait,\n * because a storage call that never settles holds this dispatch slot, and two of them\n * stop the pipeline.\n * @param batch Batch to persist.\n * @returns What became of the batch, for the throttle report.\n */\n private async store(batch: LogBatch): Promise<ThrottledResult> {\n const kept = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store an undelivered batch.\",\n async () => {\n const written = await withDeadline(this.storage.save(batch), STORAGE_DEADLINE_MS);\n\n // Only bring the drain forward for a batch that is in storage. With `storage: \"none\"`\n // an early drain would find nothing to send.\n if (written) {\n this.retry.nudge();\n }\n\n return written;\n },\n );\n\n // The guard returns undefined when the save threw or ran past its deadline. A late save\n // can still finish and the engine then sends the batch, so don't report a drop.\n if (kept === undefined) {\n return \"unknown\";\n }\n\n return kept ? \"stored\" : \"not_stored\";\n }\n}\n","// src/core/sender.ts\n//\n// Builds the delivery stack for the sender role: storage, transport, retry, pipeline and\n// exit flush.\n// The runtime imports this module dynamically, and only when the config sets an endpoint,\n// so console-only mode never downloads it.\n\nimport { STORAGE_NAME_INDEXEDDB, STORAGE_NAME_LOCAL } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { DeliveryHealth } from \"../models/health\";\nimport type { LogRecord } from \"../models/log-record\";\nimport {\n type GapReporter,\n type StorageAdapter,\n type StoragePersistence,\n storageLimits,\n} from \"../models/storage\";\nimport { clearEmergencyContext, drainEmergencyQueue } from \"../storage/emergency-queue\";\nimport { createStorage, storageName } from \"../storage/factory\";\nimport { ContextStorage } from \"../storage/context-storage\";\nimport { requestPersistence } from \"../storage/persistence\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { ExitFlush } from \"../transport/exit-flush\";\nimport { CustomTransport } from \"../transport/custom-transport\";\nimport { HttpTransport } from \"../transport/http-transport\";\nimport { RetryEngine } from \"../transport/retry-engine\";\nimport type { BatchTransport, StatusTransport } from \"../transport/status-transport\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { type FlushCounts, LogPipeline } from \"./pipeline\";\nimport { applyRemote, parseRemoteRules } from \"./remote-rules\";\nimport type { RemoteSlot } from \"./remote-sampling\";\n\n/** Inputs to build the delivery stack. */\nexport interface SenderDeps {\n /** Memory store that this runtime keeps when the security context changes. */\n storage?: StorageAdapter;\n onStorage?: (storage: StorageAdapter) => void;\n /** Receives the state of the persistent-storage request. */\n onPersistence?: (state: StoragePersistence) => void;\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** Receives a report when storage drops batches before delivery. */\n onGap: GapReporter;\n /** Receives the records lost by the transport, the retry engine and the exit flush. */\n onLoss: LossReporter;\n /** The runtime's slot for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Sends the open metric interval's points before the exit flush drains the buffers. */\n beforeExit?: () => void;\n /**\n * Receives the time of the last accepted batch after a send. The runtime keeps it across a\n * rotation, which builds a new sender.\n */\n onSent?: (at: number) => void;\n}\n\n/** What the sender adds to getHealth().delivery. The runtime adds the rest. */\nexport type SenderStats = Pick<\n DeliveryHealth,\n \"pending\" | \"inFlight\" | \"lastFailureAt\" | \"consecutiveFailures\" | \"throttledUntil\"\n>;\n\n/**\n * Counts the failed sends of the pipeline and the retry engine for getHealth(). The exit flush\n * can't learn its result, so it doesn't count.\n */\nclass SendOutcomes implements BatchTransport {\n /** Failed sends since the server last accepted a batch. */\n private failures = 0;\n\n /** Epoch time in milliseconds of the last failed send, or null. */\n private failedAt: number | null = null;\n\n /**\n * @param transport The transport that sends the batches.\n * @param onSent Receives the time of the last accepted batch after a send.\n */\n constructor(\n private readonly transport: StatusTransport,\n private readonly onSent: (at: number) => void = () => undefined,\n ) {}\n\n /**\n * Sends one batch and counts the result.\n * @param batch Batch to send.\n * @param onKeepalive Runs when one of the batch's requests starts with keepalive.\n * @returns Promise that resolves to the records lost in a send that ends without an error.\n * @throws TransportError when the batch isn't accepted.\n */\n async send(batch: LogBatch, onKeepalive?: () => void): Promise<number> {\n const before = this.transport.lastSendAt();\n let lost: number;\n try {\n lost = await this.transport.send(batch, onKeepalive);\n } catch (error) {\n this.failures++;\n this.failedAt = Date.now();\n throw error;\n }\n\n // A batch with no request, for example a traces batch with no tracesEndpoint, ends without\n // an error but proves nothing, so only an accept during this send resets the count.\n const at = this.transport.lastSendAt();\n if (at !== null && at !== before) {\n this.failures = 0;\n this.onSent(at);\n }\n\n return lost;\n }\n\n /**\n * Returns the remaining throttle delay for a batch's endpoint.\n * @param batch Batch to send.\n * @returns Milliseconds until the throttle ends, or 0.\n */\n throttledForMs(batch: LogBatch): number {\n return this.transport.throttledForMs(batch);\n }\n\n /**\n * Reads the failure counts.\n * @returns The failures in a row and the time of the last one.\n */\n stats(): Pick<SenderStats, \"lastFailureAt\" | \"consecutiveFailures\"> {\n return { lastFailureAt: this.failedAt, consecutiveFailures: this.failures };\n }\n}\n\n/** Delivery stack for one sender runtime. */\nexport class Sender {\n /** True after retire(), so a late emergency import doesn't wake the retry engine. */\n private retired = false;\n /** Emergency queue import. retire() waits for it before reading storage. */\n private emergencyImport: Promise<void> = Promise.resolve();\n\n /**\n * @param storage Storage adapter for undelivered batches.\n * @param retry Retry engine for stored batches.\n * @param pipeline Pipeline that batches records.\n * @param exitFlush Handler that sends pending records on unload.\n * @param diagnostics Diagnostics reporter.\n * @param transport The transport that the pipeline and the retry engine use.\n * @param outcomes Counts the failed sends of the pipeline and the retry engine.\n */\n private constructor(\n private readonly storage: ContextStorage,\n private readonly retry: RetryEngine,\n private readonly pipeline: LogPipeline,\n private readonly exitFlush: ExitFlush,\n private readonly diagnostics: Diagnostics,\n private readonly transport: StatusTransport,\n private readonly outcomes: SendOutcomes,\n ) {}\n\n /**\n * Builds the delivery stack and starts the retry loop. The emergency queue import runs\n * after the start, so a slow IndexedDB open doesn't hold up the boot buffer.\n * @param deps Configuration, diagnostics and gap reporter.\n * @returns Promise that resolves to the started sender.\n */\n static async create(deps: SenderDeps): Promise<Sender> {\n const { config, diagnostics } = deps;\n\n const backing =\n deps.storage ??\n (await createStorage(\n config.storage.backend,\n storageName(config.storage.namespace),\n storageLimits(config.retention),\n diagnostics,\n deps.onGap,\n config.storage.namespace,\n ));\n deps.onStorage?.(backing);\n\n // Ask only for a store that outlives the page.\n if (\n config.storage.requestPersistent &&\n (backing.name === STORAGE_NAME_INDEXEDDB || backing.name === STORAGE_NAME_LOCAL)\n ) {\n deps.onPersistence?.(\"pending\");\n void requestPersistence(diagnostics).then(deps.onPersistence);\n }\n\n const storage = new ContextStorage(backing, config.securityContext, config.storage.namespace);\n const onSampling = (raw: unknown): void => {\n const update = parseRemoteRules(raw, diagnostics);\n\n if (update) {\n applyRemote(deps.remote, config, update);\n }\n };\n\n // The clock offset from the last accepted response. The pipeline adds it to new records.\n let clockOffsetMs: number | undefined;\n const onClock = (offsetMs: number): void => {\n clockOffsetMs = offsetMs;\n };\n\n // The stack keeps one transport for its whole life, and the runtime refuses a later change.\n // The exit flush reads the last headers and the keepalive bytes in flight from the HTTP\n // transport.\n const { onLoss } = deps;\n const worker =\n !config.transport && config.transportWorker\n ? await diagnostics.guardAsync(\n \"transport.http_error\",\n \"The transport worker module did not load. The library uses HTTP.\",\n async () =>\n (await import(\"../transport/worker-transport\")).createWorkerTransport(\n config,\n diagnostics,\n onSampling,\n onLoss,\n onClock,\n ),\n )\n : undefined;\n const http =\n config.transport !== undefined || worker !== undefined\n ? undefined\n : new HttpTransport(config, diagnostics, onSampling, onLoss, onClock);\n const transport: StatusTransport =\n worker?.transport ??\n http ??\n new CustomTransport(config, diagnostics, onSampling, onLoss, onClock);\n const outcomes = new SendOutcomes(transport, deps.onSent);\n const retry = new RetryEngine(storage, outcomes, diagnostics, config, undefined, onLoss);\n const { batching } = config;\n const pipeline = new LogPipeline(\n outcomes,\n storage,\n retry,\n diagnostics,\n {\n logs: { flushIntervalMs: batching.logFlushIntervalMs, batchSize: batching.logBatchSize },\n metrics: {\n // Read on each batch, so a later metrics.intervalMs applies here as it does to the meter.\n get flushIntervalMs() {\n return config.metrics.intervalMs;\n },\n batchSize: batching.metricBatchSize,\n },\n // A span is the size of a log record, so the traces stream uses the log batching.\n traces: { flushIntervalMs: batching.logFlushIntervalMs, batchSize: batching.logBatchSize },\n },\n () => config.securityContext.id || undefined,\n config,\n onLoss,\n () => (config.metadata.clockOffset ? clockOffsetMs : undefined),\n );\n\n const exitFlush = new ExitFlush({\n config,\n diagnostics,\n drainForExit: () => pipeline.drainForExit(),\n flushAlive: () => pipeline.flushPending(),\n exitHeaders: () => (worker ? worker.exitHeaders() : http?.lastHeaders()),\n keepaliveInFlight: () => (worker ? worker.keepaliveInFlight() : http?.keepaliveInFlight()),\n onLoss,\n beforeExit: deps.beforeExit,\n });\n\n // If one step fails, stop both. A retry loop with no owner would keep sending after the\n // load reports failure.\n let started = false;\n\n try {\n exitFlush.install();\n retry.start();\n started = true;\n } finally {\n if (!started) {\n exitFlush.uninstall();\n retry.stop();\n }\n }\n\n const sender = new Sender(\n storage,\n retry,\n pipeline,\n exitFlush,\n diagnostics,\n transport,\n outcomes,\n );\n sender.emergencyImport = sender.importEmergency();\n return sender;\n }\n\n /**\n * Adds a record to the pipeline. After a pagehide the exit flush sends it, because the batch\n * timer won't fire in a closing document.\n * @param record Record to deliver.\n */\n push(record: LogRecord): void {\n this.pipeline.push(record);\n this.exitFlush.flushLate();\n }\n\n /**\n * Stops every send while `enabled` is false, or starts again. The records stay in memory and\n * the stored batches stay in storage, so they go out after the pause.\n * @param on True to stop.\n */\n hold(on: boolean): void {\n this.pipeline.hold(on);\n\n if (on) {\n this.exitFlush.uninstall();\n this.retry.stop();\n return;\n }\n\n this.exitFlush.install();\n this.retry.start();\n }\n\n /**\n * Lists the records that only memory holds. Nothing sends them during a pause.\n * @returns The pipeline's records.\n */\n records(): LogRecord[] {\n return this.pipeline.records();\n }\n\n /**\n * Sends the records in the stream buffers, then waits for every batch in flight.\n * @returns Promise that resolves once the pipeline has sent or stored every batch.\n */\n async flush(): Promise<void> {\n await this.pipeline.flushPending();\n }\n\n /**\n * Sends the records in the stream buffers, then waits for this call's batches until each one\n * ends or the deadline passes.\n * @param expired Resolves at the caller's deadline.\n * @returns The records of the call's batches by their state when the wait ends.\n */\n flushUntil(expired: Promise<void>): Promise<FlushCounts> {\n return this.pipeline.flushUntil(expired);\n }\n\n /**\n * Counts the batches held in storage.\n * @returns Promise that resolves to the batch count, or 0 if storage fails.\n */\n async queueDepth(): Promise<number> {\n const count = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the batches in storage.\",\n () => this.storage.count(),\n );\n\n return count ?? 0;\n }\n\n /**\n * Reads the delivery state of the pipeline and the transport.\n * @returns Waiting records, records in requests, the failures and the throttle end.\n */\n stats(): SenderStats {\n return {\n ...this.pipeline.counts(),\n ...this.outcomes.stats(),\n throttledUntil: this.transport.throttleEnd(),\n };\n }\n\n /**\n * Sends pending records with a normal flush, then with the exit flush, then stops all\n * timers and listeners and closes storage. The normal flush keeps the headers, gzip and\n * the retry. The exit flush picks up the records the normal flush didn't confirm.\n * @returns Promise that resolves when storage closes.\n */\n async destroy(): Promise<void> {\n await this.diagnostics.guardAsync(\"pipeline.crashed\", \"The flush before shutdown failed.\", () =>\n this.flush(),\n );\n\n // A held sender sends nothing, not even at shutdown.\n if (!this.pipeline.isHeld()) {\n this.exitFlush.flush(\"shutdown\");\n }\n this.exitFlush.uninstall();\n this.retry.stop();\n this.transport.stop();\n this.pipeline.destroy();\n\n await this.storage.close();\n }\n\n /**\n * Stops every send without a flush or an exit flush, for a discard at shutdown. A request in\n * flight can still reach the server, but its result writes nothing and schedules no retry,\n * because the store accepts no write after this.\n * @returns Promise that resolves to the records in the buffers and the queue, once the\n * emergency import is done and the store is closed.\n */\n async discard(): Promise<LogRecord[]> {\n this.retired = true;\n this.exitFlush.uninstall();\n this.retry.stop();\n this.transport.stop();\n const records = this.pipeline.discard();\n // The import moves the previous page's batches into the store, so let it end before the\n // store stops writes. Otherwise a batch it claimed would be lost.\n await this.emergencyImport;\n await this.storage.retire(false);\n return records;\n }\n\n /**\n * Stops every send after a rotation fails, and stores the records from memory under the old\n * id. The store stays open, so the next rotation that succeeds can apply its rule to them.\n * @param contextId Identity of the closed delivery context.\n * @returns Promise that resolves once the records are stored.\n */\n async pause(contextId: string): Promise<void> {\n this.retired = true;\n this.exitFlush.uninstall();\n this.retry.stop();\n this.transport.stop();\n const drained = this.pipeline.drainForRetire();\n this.pipeline.destroy();\n await this.emergencyImport;\n await this.keep(drained, contextId);\n }\n\n /**\n * Stores whole batches under a context id. One batch per record would fill\n * retention.maxBatches.\n * @param batches Batches from the pipeline.\n * @param contextId Identity of their delivery context.\n * @returns Promise that resolves once each batch is stored.\n */\n private async keep(batches: readonly LogBatch[], contextId: string): Promise<void> {\n for (const batch of batches) {\n await this.storage.save({\n ...batch,\n routingContextId: contextId,\n persistenceNamespace: this.storage.namespace,\n });\n }\n }\n\n /**\n * Stops this sender before a new delivery identity takes effect. Does not run exit delivery.\n * @param policy Rule for the old records.\n * @param timeoutMs Maximum wait for a flush, in milliseconds.\n * @param contextId Identity of the old delivery context.\n * @returns The records that were in memory and the batches that were stored, after the\n * delivery attempt. A discard or a flush adds the context's emergency entries it removed.\n */\n async retire(\n policy: \"discard\" | \"flush\" | \"retain\" | \"carry\",\n timeoutMs: number,\n contextId: string,\n ): Promise<{ buffered: LogRecord[]; stored: LogBatch[] }> {\n this.retired = true;\n this.exitFlush.uninstall();\n this.retry.stop();\n // A held sender sends nothing, so \"flush\" acts as \"discard\" during a pause.\n if (policy === \"flush\" && !this.pipeline.isHeld()) {\n try {\n await withDeadline(Promise.all([this.flush(), this.retry.flush()]), timeoutMs);\n } catch (error) {\n // The remaining records follow the selected rule.\n this.diagnostics.report(\n \"transport.timeout\",\n \"The flush of the old security context did not complete before its time limit.\",\n undefined,\n error,\n );\n }\n }\n this.retry.stop();\n this.transport.stop();\n const drained = this.pipeline.drainForRetire();\n const buffered = drained.flatMap((batch) => batch.records);\n this.pipeline.destroy();\n await this.emergencyImport;\n const stored = await this.storage.take(Number.MAX_SAFE_INTEGER);\n if (policy === \"retain\") {\n await this.keep(drained, contextId);\n }\n // \"carry\" keeps the stored batches until adopt() stores each one again under the new id.\n // If the tab closes during the carry, the rest are parked, not lost.\n const discard = policy === \"discard\" || policy === \"flush\";\n await this.storage.retire(discard);\n // Another tab can park an exit batch of this context after this tab's startup import. It goes\n // with the stored batches, so the rotation reports its records instead of losing them silently.\n if (discard) {\n stored.push(...clearEmergencyContext(contextId, this.diagnostics, this.storage.namespace));\n }\n return { buffered, stored };\n }\n\n /**\n * Stores an earlier context's batches under this context, and the retry engine then sends\n * them. They don't go through the live buffer, because a large backlog would exceed its\n * budget.\n * @param batches The earlier context's stored batches.\n * @param contextId Identity of this delivery context.\n * @returns Promise that resolves when the batches are stored.\n */\n async adopt(batches: readonly LogBatch[], contextId: string): Promise<void> {\n for (const batch of batches) {\n // The same id replaces the old copy. Attempts against the old destination don't count here.\n await this.storage.save({\n ...batch,\n attempts: 0,\n routingContextId: contextId,\n persistenceNamespace: this.storage.namespace,\n });\n }\n\n if (batches.length > 0) {\n this.retry.nudge();\n }\n }\n\n /**\n * Moves the emergency queue's batches into storage, then wakes the retry engine.\n * The previous page load parked them during its unload.\n */\n private async importEmergency(): Promise<void> {\n const moved = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The emergency import failed.\",\n () =>\n drainEmergencyQueue(\n this.storage,\n this.diagnostics,\n (batch) => this.storage.accepts(batch),\n this.storage.namespace,\n ),\n );\n\n if (!this.retired && moved !== undefined && moved > 0) {\n this.retry.nudge();\n }\n }\n}\n"],"mappings":"A,spBAiBA,eAAsByF,EAAmB,EAAuD,CAC9F,IAAMC,EAAW,WAA6B,WAAW,QAYzD,OAVI,OAAOA,GAAS,SAAY,WAUzB,MANeC,EAAY,WAChC,sBACA,+DACMD,EAAQ,QAAQ,CACxB,IAEmB,GAAO,UAAY,SAT7B,aAUX,CCDA,SAASE,EAAY,EAAmC,CACtD,IAAMC,EAAW,OAAOC,GAAS,SAAW,KAAK,MAAMA,CAAI,EAAI,IAE/D,OAAO,OAAO,MAAMD,CAAQ,EACxB,IAAA,GACA,KAAK,MAAMA,EAAA,IAAsC,KAAK,IAAI,CAAC,CACjE,CAgCA,IAAsBE,EAAtB,KAAgE,CAI9D,MAAa,CACX,KAAK,aAAa,MAAM,CAC1B,CAOA,cAAwB,EAAuB,CAC7C,GACE,KAAK,aAAa,OAAO,SACxB,KAAK,OAAO,gBAAgB,WAC3B,KAAK,OAAO,gBAAgB,IAC5BC,EAAM,mBAAqB,KAAK,OAAO,gBAAgB,GAGzD,MADA,KAAK,YAAY,MAAM,2BAA2B,EAC5C,IAAIhG,EAAAA,EACR,YACA,+DACF,CAEJ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ue(storage: StorageAdapter, diagnostics
|
|
|
23
23
|
* @param diagnostics Diagnostics reporter.
|
|
24
24
|
* @param namespace The application's storage namespace.
|
|
25
25
|
* @param all True to remove the entries of every context in this namespace.
|
|
26
|
+
* @returns The context's batches that it removed, so the caller can report their records. With
|
|
27
|
+
* `all` it returns none, because it removes the entries without reading them.
|
|
26
28
|
*/
|
|
27
|
-
export declare function clearEmergencyContext(id: string, diagnostics: Diagnostics, namespace?: string, all?: boolean):
|
|
29
|
+
export declare function clearEmergencyContext(id: string, diagnostics: Diagnostics, namespace?: string, all?: boolean): LogBatch[];
|
|
@@ -23,5 +23,7 @@ export declare function drainEmergencyQueue(storage: StorageAdapter, diagnostics
|
|
|
23
23
|
* @param diagnostics Diagnostics reporter.
|
|
24
24
|
* @param namespace The application's storage namespace.
|
|
25
25
|
* @param all True to remove the entries of every context in this namespace.
|
|
26
|
+
* @returns The context's batches that it removed, so the caller can report their records. With
|
|
27
|
+
* `all` it returns none, because it removes the entries without reading them.
|
|
26
28
|
*/
|
|
27
|
-
export declare function clearEmergencyContext(id: string, diagnostics: Diagnostics, namespace?: string, all?: boolean):
|
|
29
|
+
export declare function clearEmergencyContext(id: string, diagnostics: Diagnostics, namespace?: string, all?: boolean): LogBatch[];
|
|
@@ -20,9 +20,10 @@ export interface StoreAccess {
|
|
|
20
20
|
* @param scope Whose stored records to remove: the context's or the namespace's.
|
|
21
21
|
* @param ids More batches to remove by id, for example the ones a carry left under an older id.
|
|
22
22
|
* @param forgetIds True to also remove the stored session id, tab id and journey.
|
|
23
|
-
* @returns Promise that resolves
|
|
23
|
+
* @returns Promise that resolves to the context's removed batches and emergency entries, so a
|
|
24
|
+
* discard rotation can report their records. The `ids` batches and a namespace clear add none.
|
|
24
25
|
*/
|
|
25
|
-
export declare function clearStored(access: StoreAccess, scope: "context" | "namespace", ids: readonly string[], forgetIds?: boolean): Promise<
|
|
26
|
+
export declare function clearStored(access: StoreAccess, scope: "context" | "namespace", ids: readonly string[], forgetIds?: boolean): Promise<LogBatch[]>;
|
|
26
27
|
/**
|
|
27
28
|
* Stores records and batches under the active context, as a retain rotation does with a sender.
|
|
28
29
|
* The records go in one batch. A batch keeps its id, so its older copy is replaced.
|
|
@@ -20,9 +20,10 @@ export interface StoreAccess {
|
|
|
20
20
|
* @param scope Whose stored records to remove: the context's or the namespace's.
|
|
21
21
|
* @param ids More batches to remove by id, for example the ones a carry left under an older id.
|
|
22
22
|
* @param forgetIds True to also remove the stored session id, tab id and journey.
|
|
23
|
-
* @returns Promise that resolves
|
|
23
|
+
* @returns Promise that resolves to the context's removed batches and emergency entries, so a
|
|
24
|
+
* discard rotation can report their records. The `ids` batches and a namespace clear add none.
|
|
24
25
|
*/
|
|
25
|
-
export declare function clearStored(access: StoreAccess, scope: "context" | "namespace", ids: readonly string[], forgetIds?: boolean): Promise<
|
|
26
|
+
export declare function clearStored(access: StoreAccess, scope: "context" | "namespace", ids: readonly string[], forgetIds?: boolean): Promise<LogBatch[]>;
|
|
26
27
|
/**
|
|
27
28
|
* Stores records and batches under the active context, as a retain rotation does with a sender.
|
|
28
29
|
* The records go in one batch. A batch keeps its id, so its older copy is replaced.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-NtiQDWL_.cjs"),t=require("./factory-DsaNdcXp.cjs"),n=require("./identity-BzAzdQyv.cjs");var r=[[`local`,e.Un],[`session`,e.tr],[`session`,e.Dt]];async function i(e,n){let{config:r,diagnostics:i,memory:a}=e,{backend:o,namespace:s}=r.storage,c=a??await t.t(o,t.n(s),t.p(r.retention),i,void 0,s),l=new t.f(c,r.securityContext,s);try{return await n(l)}finally{c!==a&&await l.close()}}function a(e,a,o,s=!1){if(s)for(let[t,i]of r)e.diagnostics.guard(`storage.unavailable`,`The library could not remove ${i} from ${t}Storage.`,()=>{n.t[t]().removeItem(i)});return i(e,async n=>{for(let e of o)await n.remove(e);let{diagnostics:r,config:i}=e,s=i.securityContext.id;if(a===`namespace`)return await n.clearNamespace(),t.s(s,r,n.namespace,!0),[];let c=await n.take(2**53-1);for(let e of c)await n.remove(e.id);return[...c,...t.s(s,r,n.namespace)]})}function o(e,t,r){return i(e,async i=>{let a=[...r];if(t.length>0){let r=n.i(e.diagnostics);a.push({id:r,records:[...t],createdAt:Date.now(),attempts:0})}for(let t of a)await i.save({...t,attempts:0,routingContextId:e.config.securityContext.id,persistenceNamespace:i.namespace})})}exports.clearStored=a,exports.keepStored=o;
|
|
2
|
+
//# sourceMappingURL=stored-context-CPLlzgpm.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stored-context-CPLlzgpm.cjs","names":["SESSION_ID_KEY","TAB_ID_KEY","JOURNEY_STORAGE_KEY","createStorage","storageName","storageLimits","ContextStorage","clearEmergencyContext","newId","require_constants","require_factory","require_identity","STORED_IDS","withStore","access","config","backing","memory","backend","namespace","diagnostics","store","work","clearStored","forgetIds","key","id","ids","contextId","scope","removed","batch","keepStored","all","batches","records"],"sources":["../src/storage/stored-context.ts"],"sourcesContent":["// src/storage/stored-context.ts\n//\n// Reaches the configured store when no delivery stack runs. shutdown() with clearStorage and a\n// rotation with no old sender need it, because otherwise only a sender opens the store.\n\nimport { JOURNEY_STORAGE_KEY, SESSION_ID_KEY, TAB_ID_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { BROWSER_STORES, newId } from \"../utils/identity\";\nimport { ContextStorage } from \"./context-storage\";\nimport { clearEmergencyContext } from \"./emergency-queue\";\nimport { createStorage, storageName } from \"./factory\";\n\n/** The stored ids that a shutdown with clearStorage removes: the session, the tab and the journey. */\nconst STORED_IDS = [\n [\"local\", SESSION_ID_KEY],\n [\"session\", TAB_ID_KEY],\n [\"session\", JOURNEY_STORAGE_KEY],\n] as const;\n\n/** What opening the store needs. The active context is the one in `config.securityContext`. */\nexport interface StoreAccess {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** The memory store the runtime keeps across context changes, if it has one. */\n memory: StorageAdapter | undefined;\n}\n\n/**\n * Opens the store for the active context, runs the work, then closes the store again. The\n * memory store stays open, because it holds other contexts' records too.\n * @param access The config, the reporter and the kept memory store.\n * @param work What to do with the store.\n * @returns Promise that resolves to the work's result once the store is closed.\n */\nasync function withStore<T>(\n access: StoreAccess,\n work: (store: ContextStorage) => Promise<T>,\n): Promise<T> {\n const { config, diagnostics, memory } = access;\n const { backend, namespace } = config.storage;\n const backing =\n memory ??\n (await createStorage(\n backend,\n storageName(namespace),\n storageLimits(config.retention),\n diagnostics,\n undefined,\n namespace,\n ));\n const store = new ContextStorage(backing, config.securityContext, namespace);\n try {\n return await work(store);\n } finally {\n if (backing !== memory) {\n await store.close();\n }\n }\n}\n\n/**\n * Removes the active context's stored batches and its emergency entries, or the whole\n * namespace's. A discard rotation with no sender uses it, as Sender.retire() would, and so does\n * shutdown() with clearStorage.\n * @param access The config, the reporter and the kept memory store.\n * @param scope Whose stored records to remove: the context's or the namespace's.\n * @param ids More batches to remove by id, for example the ones a carry left under an older id.\n * @param forgetIds True to also remove the stored session id, tab id and journey.\n * @returns Promise that resolves to the context's removed batches and emergency entries, so a\n * discard rotation can report their records. The `ids` batches and a namespace clear add none.\n */\nexport function clearStored(\n access: StoreAccess,\n scope: \"context\" | \"namespace\",\n ids: readonly string[],\n forgetIds = false,\n): Promise<LogBatch[]> {\n // The ids go first, so a store that won't open still leaves no session for the next user.\n if (forgetIds) {\n for (const [store, key] of STORED_IDS) {\n access.diagnostics.guard(\n \"storage.unavailable\",\n `The library could not remove ${key} from ${store}Storage.`,\n () => {\n BROWSER_STORES[store]().removeItem(key);\n },\n );\n }\n }\n\n return withStore(access, async (store) => {\n for (const id of ids) {\n await store.remove(id);\n }\n\n const { diagnostics, config } = access;\n const contextId = config.securityContext.id;\n if (scope === \"namespace\") {\n await store.clearNamespace();\n clearEmergencyContext(contextId, diagnostics, store.namespace, true);\n return [];\n }\n\n // Remove only what was read, so a batch saved in between isn't removed without a report.\n const removed = await store.take(Number.MAX_SAFE_INTEGER);\n for (const batch of removed) {\n await store.remove(batch.id);\n }\n\n return [...removed, ...clearEmergencyContext(contextId, diagnostics, store.namespace)];\n });\n}\n\n/**\n * Stores records and batches under the active context, as a retain rotation does with a sender.\n * The records go in one batch. A batch keeps its id, so its older copy is replaced.\n * @param access The config, the reporter and the kept memory store.\n * @param records Records that waited in memory.\n * @param batches Stored batches of an earlier context, for example the ones a carry left.\n * @returns Promise that resolves once each batch is stored.\n */\nexport function keepStored(\n access: StoreAccess,\n records: readonly LogRecord[],\n batches: readonly LogBatch[],\n): Promise<void> {\n return withStore(access, async (store) => {\n const all = [...batches];\n if (records.length > 0) {\n const id = newId(access.diagnostics);\n all.push({ id, records: [...records], createdAt: Date.now(), attempts: 0 });\n }\n\n for (const batch of all) {\n await store.save({\n ...batch,\n attempts: 0,\n routingContextId: access.config.securityContext.id,\n persistenceNamespace: store.namespace,\n });\n }\n });\n}\n"],"mappings":"A,qHAiBA,IAAMY,EAAa,CACjB,CAAC,QAASZ,EAAAA,EAAc,EACxB,CAAC,UAAWC,EAAAA,EAAU,EACtB,CAAC,UAAWC,EAAAA,EAAmB,CACjC,EAmBA,eAAeW,EACb,EACA,EACY,CACZ,GAAM,CAAE,SAAQ,cAAa,UAAWC,EAClC,CAAE,UAAS,aAAcC,EAAO,QAChCC,EACJC,GACC,MAAMd,EAAAA,EACLe,EACAd,EAAAA,EAAYe,CAAS,EACrBd,EAAAA,EAAcU,EAAO,SAAS,EAC9BK,EACA,IAAA,GACAD,CACF,EACIE,EAAQ,IAAIf,EAAAA,EAAeU,EAASD,EAAO,gBAAiBI,CAAS,EAC3E,GAAI,CACF,OAAO,MAAMG,EAAKD,CAAK,CACzB,QAAU,CACJL,IAAYC,GACd,MAAMI,EAAM,MAAM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1,6 @@
|
|
|
1
|
-
import { Dt as e,
|
|
2
|
-
import { f as r, n as i, p as a, s as o, t as s } from "./factory-
|
|
3
|
-
import { i as c, t as l } from "./identity-
|
|
1
|
+
import { Dt as e, Un as t, tr as n } from "./constants-CEHN6KuY.js";
|
|
2
|
+
import { f as r, n as i, p as a, s as o, t as s } from "./factory-BHYrcSaU.js";
|
|
3
|
+
import { i as c, t as l } from "./identity-Byh3gCdT.js";
|
|
4
4
|
// src/storage/stored-context.ts
|
|
5
5
|
var u = [
|
|
6
6
|
["local", t],
|
|
@@ -10,7 +10,7 @@ var u = [
|
|
|
10
10
|
async function d(e, t) {
|
|
11
11
|
let { config: n, diagnostics: o, memory: c } = e, { backend: l, namespace: u } = n.storage, d = c ?? await s(l, i(u), a(n.retention), o, void 0, u), f = new r(d, n.securityContext, u);
|
|
12
12
|
try {
|
|
13
|
-
await t(f);
|
|
13
|
+
return await t(f);
|
|
14
14
|
} finally {
|
|
15
15
|
d !== c && await f.close();
|
|
16
16
|
}
|
|
@@ -21,9 +21,11 @@ function f(e, t, n, r = !1) {
|
|
|
21
21
|
});
|
|
22
22
|
return d(e, async (r) => {
|
|
23
23
|
for (let e of n) await r.remove(e);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
let { diagnostics: i, config: a } = e, s = a.securityContext.id;
|
|
25
|
+
if (t === "namespace") return await r.clearNamespace(), o(s, i, r.namespace, !0), [];
|
|
26
|
+
let c = await r.take(2 ** 53 - 1);
|
|
27
|
+
for (let e of c) await r.remove(e.id);
|
|
28
|
+
return [...c, ...o(s, i, r.namespace)];
|
|
27
29
|
});
|
|
28
30
|
}
|
|
29
31
|
function p(e, t, n) {
|
|
@@ -48,4 +50,4 @@ function p(e, t, n) {
|
|
|
48
50
|
}
|
|
49
51
|
export { f as clearStored, p as keepStored };
|
|
50
52
|
|
|
51
|
-
//# sourceMappingURL=stored-context-
|
|
53
|
+
//# sourceMappingURL=stored-context-df1dEnht.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stored-context-df1dEnht.js","names":["JOURNEY_STORAGE_KEY","SESSION_ID_KEY","TAB_ID_KEY","ContextStorage","storageName","storageLimits","clearEmergencyContext","createStorage","newId","BROWSER_STORES","STORED_IDS","withStore","access","config","backing","memory","backend","namespace","diagnostics","store","work","clearStored","forgetIds","key","id","ids","contextId","scope","removed","batch","keepStored","all","batches","records"],"sources":["../src/storage/stored-context.ts"],"sourcesContent":["// src/storage/stored-context.ts\n//\n// Reaches the configured store when no delivery stack runs. shutdown() with clearStorage and a\n// rotation with no old sender need it, because otherwise only a sender opens the store.\n\nimport { JOURNEY_STORAGE_KEY, SESSION_ID_KEY, TAB_ID_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { type StorageAdapter, storageLimits } from \"../models/storage\";\nimport { BROWSER_STORES, newId } from \"../utils/identity\";\nimport { ContextStorage } from \"./context-storage\";\nimport { clearEmergencyContext } from \"./emergency-queue\";\nimport { createStorage, storageName } from \"./factory\";\n\n/** The stored ids that a shutdown with clearStorage removes: the session, the tab and the journey. */\nconst STORED_IDS = [\n [\"local\", SESSION_ID_KEY],\n [\"session\", TAB_ID_KEY],\n [\"session\", JOURNEY_STORAGE_KEY],\n] as const;\n\n/** What opening the store needs. The active context is the one in `config.securityContext`. */\nexport interface StoreAccess {\n /** Active configuration instance. */\n config: ResolvedConfig;\n /** Diagnostics reporter. */\n diagnostics: Diagnostics;\n /** The memory store the runtime keeps across context changes, if it has one. */\n memory: StorageAdapter | undefined;\n}\n\n/**\n * Opens the store for the active context, runs the work, then closes the store again. The\n * memory store stays open, because it holds other contexts' records too.\n * @param access The config, the reporter and the kept memory store.\n * @param work What to do with the store.\n * @returns Promise that resolves to the work's result once the store is closed.\n */\nasync function withStore<T>(\n access: StoreAccess,\n work: (store: ContextStorage) => Promise<T>,\n): Promise<T> {\n const { config, diagnostics, memory } = access;\n const { backend, namespace } = config.storage;\n const backing =\n memory ??\n (await createStorage(\n backend,\n storageName(namespace),\n storageLimits(config.retention),\n diagnostics,\n undefined,\n namespace,\n ));\n const store = new ContextStorage(backing, config.securityContext, namespace);\n try {\n return await work(store);\n } finally {\n if (backing !== memory) {\n await store.close();\n }\n }\n}\n\n/**\n * Removes the active context's stored batches and its emergency entries, or the whole\n * namespace's. A discard rotation with no sender uses it, as Sender.retire() would, and so does\n * shutdown() with clearStorage.\n * @param access The config, the reporter and the kept memory store.\n * @param scope Whose stored records to remove: the context's or the namespace's.\n * @param ids More batches to remove by id, for example the ones a carry left under an older id.\n * @param forgetIds True to also remove the stored session id, tab id and journey.\n * @returns Promise that resolves to the context's removed batches and emergency entries, so a\n * discard rotation can report their records. The `ids` batches and a namespace clear add none.\n */\nexport function clearStored(\n access: StoreAccess,\n scope: \"context\" | \"namespace\",\n ids: readonly string[],\n forgetIds = false,\n): Promise<LogBatch[]> {\n // The ids go first, so a store that won't open still leaves no session for the next user.\n if (forgetIds) {\n for (const [store, key] of STORED_IDS) {\n access.diagnostics.guard(\n \"storage.unavailable\",\n `The library could not remove ${key} from ${store}Storage.`,\n () => {\n BROWSER_STORES[store]().removeItem(key);\n },\n );\n }\n }\n\n return withStore(access, async (store) => {\n for (const id of ids) {\n await store.remove(id);\n }\n\n const { diagnostics, config } = access;\n const contextId = config.securityContext.id;\n if (scope === \"namespace\") {\n await store.clearNamespace();\n clearEmergencyContext(contextId, diagnostics, store.namespace, true);\n return [];\n }\n\n // Remove only what was read, so a batch saved in between isn't removed without a report.\n const removed = await store.take(Number.MAX_SAFE_INTEGER);\n for (const batch of removed) {\n await store.remove(batch.id);\n }\n\n return [...removed, ...clearEmergencyContext(contextId, diagnostics, store.namespace)];\n });\n}\n\n/**\n * Stores records and batches under the active context, as a retain rotation does with a sender.\n * The records go in one batch. A batch keeps its id, so its older copy is replaced.\n * @param access The config, the reporter and the kept memory store.\n * @param records Records that waited in memory.\n * @param batches Stored batches of an earlier context, for example the ones a carry left.\n * @returns Promise that resolves once each batch is stored.\n */\nexport function keepStored(\n access: StoreAccess,\n records: readonly LogRecord[],\n batches: readonly LogBatch[],\n): Promise<void> {\n return withStore(access, async (store) => {\n const all = [...batches];\n if (records.length > 0) {\n const id = newId(access.diagnostics);\n all.push({ id, records: [...records], createdAt: Date.now(), attempts: 0 });\n }\n\n for (const batch of all) {\n await store.save({\n ...batch,\n attempts: 0,\n routingContextId: access.config.securityContext.id,\n persistenceNamespace: store.namespace,\n });\n }\n });\n}\n"],"mappings":";;;;AAiBA,IAAMU,IAAa;CACjB,CAAC,SAAST,CAAc;CACxB,CAAC,WAAWC,CAAU;CACtB,CAAC,WAAWF,CAAmB;AACjC;AAmBA,eAAeW,EACb,GACA,GACY;CACZ,IAAM,EAAE,WAAQ,gBAAa,cAAWC,GAClC,EAAE,YAAS,iBAAcC,EAAO,SAChCC,IACJC,KACC,MAAMR,EACLS,GACAZ,EAAYa,CAAS,GACrBZ,EAAcQ,EAAO,SAAS,GAC9BK,GACA,KAAA,GACAD,CACF,GACIE,IAAQ,IAAIhB,EAAeW,GAASD,EAAO,iBAAiBI,CAAS;CAC3E,IAAI;EACF,OAAO,MAAMG,EAAKD,CAAK;CACzB,UAAU;EACR,AAAIL,MAAYC,KACd,MAAMI,EAAM,MAAM;CAEtB;AACF;AAaA,SAAgBE,EACd,GACA,GACA,GACA,IAAY,IACS;CAErB,IAAIC,GACF,KAAK,IAAM,CAACH,GAAOI,MAAQb,GACzB,EAAO,YAAY,MACjB,uBACA,gCAAgCa,EAAI,QAAQJ,EAAM,iBAC5C;EACJ,EAAeA,EAAM,CAAC,CAAC,CAAC,WAAWI,CAAG;CACxC,CACF;CAIJ,OAAOZ,EAAUC,GAAQ,OAAO,MAAU;EACxC,KAAK,IAAMY,KAAMC,GACf,MAAMN,EAAM,OAAOK,CAAE;EAGvB,IAAM,EAAE,gBAAa,cAAWZ,GAC1Bc,IAAYb,EAAO,gBAAgB;EACzC,IAAIc,MAAU,aAGZ,OAFA,MAAMR,EAAM,eAAe,GAC3Bb,EAAsBoB,GAAWR,GAAaC,EAAM,WAAW,EAAI,GAC5D,CAAC;EAIV,IAAMS,IAAU,MAAMT,EAAM,gBAA4B;EACxD,KAAK,IAAMU,KAASD,GAClB,MAAMT,EAAM,OAAOU,EAAM,EAAE;EAG7B,OAAO,CAAC,GAAGD,GAAS,GAAGtB,EAAsBoB,GAAWR,GAAaC,EAAM,SAAS,CAAC;CACvF,CAAC;AACH;AAUA,SAAgBW,EACd,GACA,GACA,GACe;CACf,OAAOnB,EAAUC,GAAQ,OAAO,MAAU;EACxC,IAAMmB,IAAM,CAAC,GAAGC,CAAO;EACvB,IAAIC,EAAQ,SAAS,GAAG;GACtB,IAAMT,IAAKhB,EAAMI,EAAO,WAAW;GACnC,EAAI,KAAK;IAAE;IAAI,SAAS,CAAC,GAAGqB,CAAO;IAAG,WAAW,KAAK,IAAI;IAAG,UAAU;GAAE,CAAC;EAC5E;EAEA,KAAK,IAAMJ,KAASE,GAClB,MAAMZ,EAAM,KAAK;GACf,GAAGU;GACH,UAAU;GACV,kBAAkBjB,EAAO,OAAO,gBAAgB;GAChD,sBAAsBO,EAAM;EAC9B,CAAC;CAEL,CAAC;AACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { rt as e } from "./constants-
|
|
1
|
+
import { rt as e } from "./constants-CEHN6KuY.js";
|
|
2
2
|
import { t } from "./fixed-window-Dq3MLUUv.js";
|
|
3
3
|
// src/capture/storm.ts
|
|
4
4
|
function n(n, r, i, a, o = e) {
|
|
@@ -6,4 +6,4 @@ function n(n, r, i, a, o = e) {
|
|
|
6
6
|
}
|
|
7
7
|
export { n as t };
|
|
8
8
|
|
|
9
|
-
//# sourceMappingURL=storm-
|
|
9
|
+
//# sourceMappingURL=storm-U3_ek1nA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storm-
|
|
1
|
+
{"version":3,"file":"storm-U3_ek1nA.js","names":["ERROR_STORM_WINDOW_MS","allowInWindow","limit","countInWindow","window","windowMs","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// produces thousands of events a second, and sending them all would flood the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window and reports every event over the limit.\n * @param window Window state to update.\n * @param limit Maximum events per window. 0 allows none, and null means no limit.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number | null,\n diagnostics: Diagnostics,\n what: string,\n windowMs = ERROR_STORM_WINDOW_MS,\n): boolean {\n if (limit === null || countInWindow(window, limit, windowMs)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(windowMs)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":";;;AAoBA,SAAgBC,EACd,GACA,GACA,GACA,GACA,IAAWD,GACF;CAST,OARIE,MAAU,QAAQC,EAAcC,GAAQF,GAAOG,CAAQ,IAClD,MAGTC,EAAY,OACV,wBACA,aAAa,OAAOJ,CAAK,EAAE,GAAGK,EAAK,eAAe,OAAOF,CAAQ,EAAE,qCAAqCE,EAAK,iBAC/G,GACO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=storm-
|
|
1
|
+
const e=require("./constants-NtiQDWL_.cjs"),t=require("./fixed-window-CvESpFYV.cjs");function n(n,r,i,a,o=e.rt){return r===null||t.t(n,r,o)?!0:(i.report(`capture.rate_limited`,`More than ${String(r)} ${a} occurred in ${String(o)} ms. The library ignores the other ${a} in this window.`),!1)}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
+
//# sourceMappingURL=storm-qiE_AMC7.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storm-
|
|
1
|
+
{"version":3,"file":"storm-qiE_AMC7.cjs","names":["ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","allowInWindow","limit","window","windowMs","diagnostics","what"],"sources":["../src/capture/storm.ts"],"sourcesContent":["// src/capture/storm.ts\n//\n// Fixed-window rate limit for the capture modules. A render loop that throws or freezes\n// produces thousands of events a second, and sending them all would flood the ingest endpoint.\n\nimport { ERROR_STORM_WINDOW_MS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\n\nexport type { StormWindow } from \"../utils/fixed-window\";\n\n/**\n * Counts one event in a fixed window and reports every event over the limit.\n * @param window Window state to update.\n * @param limit Maximum events per window. 0 allows none, and null means no limit.\n * @param diagnostics Diagnostics reporter.\n * @param what Plural name of the events, for the diagnostic message.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function allowInWindow(\n window: StormWindow,\n limit: number | null,\n diagnostics: Diagnostics,\n what: string,\n windowMs = ERROR_STORM_WINDOW_MS,\n): boolean {\n if (limit === null || countInWindow(window, limit, windowMs)) {\n return true;\n }\n\n diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(limit)} ${what} occurred in ${String(windowMs)} ms. The library ignores the other ${what} in this window.`,\n );\n return false;\n}\n"],"mappings":"A,qFAoBA,SAAgBI,EACd,EACA,EACA,EACA,EACA,EAAWJ,EAAAA,GACF,CAST,OARIK,IAAU,MAAQJ,EAAAA,EAAcK,EAAQD,EAAOE,CAAQ,EAClD,IAGTC,EAAY,OACV,uBACA,aAAa,OAAOH,CAAK,EAAE,GAAGI,EAAK,eAAe,OAAOF,CAAQ,EAAE,qCAAqCE,EAAK,iBAC/G,EACO,GACT,C"}
|