@utk09/ui-observability 1.0.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 +111 -219
- package/README.md +24 -26
- package/dist/{batch-CXmPmTse.js → batch-120Kc9jr.js} +3 -3
- package/dist/{batch-CXmPmTse.js.map → batch-120Kc9jr.js.map} +1 -1
- package/dist/{batch-mmPigCpi.cjs → batch-C3uNp5kU.cjs} +2 -2
- package/dist/{batch-mmPigCpi.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
- package/dist/bus/bus.d.cts +31 -2
- package/dist/bus/bus.d.ts +31 -2
- package/dist/bus-Dj8IEVcC.cjs +2 -0
- package/dist/bus-Dj8IEVcC.cjs.map +1 -0
- package/dist/{bus-C39wspFV.js → bus-DyNafxZN.js} +127 -104
- 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/interactions.d.cts +35 -3
- package/dist/capture/interactions.d.ts +35 -3
- package/dist/capture/observed-windows.d.cts +51 -0
- package/dist/capture/observed-windows.d.ts +51 -0
- package/dist/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-tVtXwVjX.js → compression-BWkDWY3v.js} +2 -2
- package/dist/{compression-tVtXwVjX.js.map → compression-BWkDWY3v.js.map} +1 -1
- package/dist/{compression-CvED_Jel.cjs → compression-CEVe7NPX.cjs} +2 -2
- package/dist/{compression-CvED_Jel.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-DK1Zf7jn.js +556 -0
- package/dist/config-DK1Zf7jn.js.map +1 -0
- package/dist/{console-BGgGnjSi.js → console-CAyCQOpm.js} +5 -5
- package/dist/{console-BGgGnjSi.js.map → console-CAyCQOpm.js.map} +1 -1
- package/dist/{console-CSZ5_Vx5.cjs → console-Dk6GH4yj.cjs} +2 -2
- package/dist/{console-CSZ5_Vx5.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
- package/dist/{constants-CUyd9cTZ.js → constants-CEHN6KuY.js} +46 -25
- 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 +23 -0
- package/dist/constants.d.ts +23 -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/rotation.d.cts +26 -2
- package/dist/core/rotation.d.ts +26 -2
- package/dist/core/runtime.d.cts +9 -0
- package/dist/core/runtime.d.ts +9 -0
- package/dist/core/sender.d.cts +3 -2
- package/dist/core/sender.d.ts +3 -2
- package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
- package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
- package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-w78W46zr.js} +4 -4
- package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-w78W46zr.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.js +36 -36
- 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-BE_EZV7Q.js → errors-C-LYbqyB.js} +27 -24
- package/dist/errors-C-LYbqyB.js.map +1 -0
- package/dist/{factory-CTi0Is3F.js → factory-BHYrcSaU.js} +39 -28
- 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-DdhKgrpk.js → identity-Byh3gCdT.js} +35 -24
- package/dist/identity-Byh3gCdT.js.map +1 -0
- package/dist/identity-BzAzdQyv.cjs +2 -0
- package/dist/identity-BzAzdQyv.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +453 -417
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-BYywz-v6.js} +17 -17
- package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
- package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
- package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
- package/dist/interactions-BXzEel4F.cjs +2 -0
- package/dist/interactions-BXzEel4F.cjs.map +1 -0
- package/dist/interactions-DdKPMWIN.js +207 -0
- package/dist/interactions-DdKPMWIN.js.map +1 -0
- package/dist/{journey-B4Adltjm.cjs → journey-BUmsrgaw.cjs} +2 -2
- package/dist/{journey-B4Adltjm.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
- package/dist/{journey-D2_sia57.js → journey-Nu655gEO.js} +14 -14
- package/dist/{journey-D2_sia57.js.map → journey-Nu655gEO.js.map} +1 -1
- package/dist/{library-console-CPW6bvZH.cjs → library-console-DdIlzzph.cjs} +2 -2
- package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
- package/dist/{library-console-Btrzt814.js → library-console-amePMnP8.js} +2 -2
- package/dist/{library-console-Btrzt814.js.map → library-console-amePMnP8.js.map} +1 -1
- package/dist/{library-request-BJ9PLRaD.js → library-request-Cv7C05jf.js} +2 -2
- package/dist/{library-request-BJ9PLRaD.js.map → library-request-Cv7C05jf.js.map} +1 -1
- package/dist/{library-request-D7OvTxZV.cjs → library-request-DO3Ec7KE.cjs} +2 -2
- package/dist/{library-request-D7OvTxZV.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
- package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-B5yfH5is.cjs} +2 -2
- package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
- package/dist/{lifecycle-22CUCrc9.js → lifecycle-CMHz2Zbs.js} +2 -2
- package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
- package/dist/{log-record-BNiLfqtL.js → log-record-B_nSqxoe.js} +2 -2
- package/dist/{log-record-BNiLfqtL.js.map → log-record-B_nSqxoe.js.map} +1 -1
- package/dist/{log-record-CkivuiEl.cjs → log-record-Bdywwg0k.cjs} +2 -2
- package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
- package/dist/{long-frames-DNFaRnC3.js → long-frames-6NGl1-uN.js} +3 -3
- package/dist/{long-frames-DNFaRnC3.js.map → long-frames-6NGl1-uN.js.map} +1 -1
- package/dist/{long-frames-BUUbXd-B.cjs → long-frames-D9DfSWqv.cjs} +2 -2
- package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
- package/dist/models/bus.d.cts +6 -1
- package/dist/models/bus.d.ts +6 -1
- package/dist/models/config.d.cts +27 -11
- package/dist/models/config.d.ts +27 -11
- package/dist/models/serializer.d.cts +3 -1
- package/dist/models/serializer.d.ts +3 -1
- package/dist/{network-CGMLQ-mA.cjs → network-BNHBI0Fc.cjs} +2 -2
- package/dist/{network-CGMLQ-mA.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
- package/dist/{network-on2zZT6H.js → network-Cc3tSB7e.js} +5 -5
- package/dist/{network-on2zZT6H.js.map → network-Cc3tSB7e.js.map} +1 -1
- package/dist/observed-windows-8JtCsIr1.js +64 -0
- package/dist/observed-windows-8JtCsIr1.js.map +1 -0
- package/dist/observed-windows-BlE25nrn.cjs +2 -0
- package/dist/observed-windows-BlE25nrn.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{otlp-DimfrRor.js → otlp-Btix3EBa.js} +7 -7
- package/dist/{otlp-DimfrRor.js.map → otlp-Btix3EBa.js.map} +1 -1
- package/dist/{otlp-BENHf3g9.cjs → otlp-CFSW-Dno.cjs} +2 -2
- package/dist/{otlp-BENHf3g9.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-Dba6R3Hp.js +75 -0
- package/dist/platform-Dba6R3Hp.js.map +1 -0
- package/dist/{profiler-BAZoh7A4.js → profiler-DNKcqu09.js} +60 -60
- package/dist/{profiler-BAZoh7A4.js.map → profiler-DNKcqu09.js.map} +1 -1
- package/dist/{profiler-D4tJpDRc.cjs → profiler-DpoPi1hH.cjs} +2 -2
- package/dist/{profiler-D4tJpDRc.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
- package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
- package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
- package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-CGXZeZ_3.js} +16 -16
- package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
- package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-DNK96vLa.js} +25 -25
- package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-DNK96vLa.js.map} +1 -1
- package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-DuMFRlit.cjs} +2 -2
- package/dist/{remote-rules-_tY0zj5o.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-Ds-ANH34.js → replay-Dy6OiaOZ.js} +104 -77
- package/dist/replay-Dy6OiaOZ.js.map +1 -0
- package/dist/{reports-BDSe4dFH.cjs → reports-CGK9YQch.cjs} +2 -2
- package/dist/{reports-BDSe4dFH.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
- package/dist/{reports-C-thq-bk.js → reports-CX57-S9s.js} +3 -3
- package/dist/{reports-C-thq-bk.js.map → reports-CX57-S9s.js.map} +1 -1
- package/dist/{resource-timing-eUl2dNgC.js → resource-timing-CWVDCbrY.js} +4 -4
- package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
- package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-DalulXiR.cjs} +2 -2
- package/dist/{resource-timing-C576gFIQ.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-eoSQpLiH.js → response-body-yi92Rpvo.js} +109 -109
- package/dist/response-body-yi92Rpvo.js.map +1 -0
- package/dist/{rotation-Cwct4ckk.js → rotation-ChBbNDE2.js} +27 -28
- 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-BlrI8jor.js → sampling-DZTOD28D.js} +16 -16
- package/dist/{sampling-BlrI8jor.js.map → sampling-DZTOD28D.js.map} +1 -1
- package/dist/{sampling-mXt4dstx.cjs → sampling-wAVJIZXp.cjs} +2 -2
- package/dist/{sampling-mXt4dstx.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
- package/dist/{sanitize-Ba0KqU06.js → sanitize-B2GKlSFp.js} +2 -2
- package/dist/{sanitize-Ba0KqU06.js.map → sanitize-B2GKlSFp.js.map} +1 -1
- package/dist/{sanitize-DQyiI_KY.cjs → sanitize-BZdhoghq.cjs} +2 -2
- package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
- package/dist/{sender-Dv8rAmpV.js → sender-BRSpc7R8.js} +192 -178
- 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-B2EzVuYm.js → stored-context-df1dEnht.js} +12 -10
- package/dist/stored-context-df1dEnht.js.map +1 -0
- package/dist/{storm-DjKetLKZ.js → storm-U3_ek1nA.js} +2 -2
- package/dist/{storm-DjKetLKZ.js.map → storm-U3_ek1nA.js.map} +1 -1
- package/dist/{storm-C-zYSdDX.cjs → storm-qiE_AMC7.cjs} +2 -2
- package/dist/{storm-C-zYSdDX.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-DQD1cT7c.js → unclean-exit-Bj6gYHeL.js} +2 -2
- package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
- package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
- package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
- package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
- package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
- package/dist/{user-timing-BePqb1uN.js → user-timing-Duz0d-OA.js} +2 -2
- package/dist/{user-timing-BePqb1uN.js.map → user-timing-Duz0d-OA.js.map} +1 -1
- package/dist/utils/identity.d.cts +5 -0
- package/dist/utils/identity.d.ts +5 -0
- 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-DSHgDiZ6.js → web-socket-CE_9Q22z.js} +5 -5
- package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-CE_9Q22z.js.map} +1 -1
- package/dist/{web-socket-CoIUBM3C.cjs → web-socket-sm3rD-A_.cjs} +2 -2
- package/dist/{web-socket-CoIUBM3C.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-QbvqNazn.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
- package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
- package/dist/{worker-protocol-x074Rpet.js → worker-protocol-h4-tRWqy.js} +6 -6
- package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
- package/dist/{worker-server-CFe4nvos.cjs → worker-server-CF1yatXq.cjs} +2 -2
- package/dist/{worker-server-CFe4nvos.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
- package/dist/worker-server-FYfKHQhJ.js +94 -0
- package/dist/{worker-server-iUVSjH8L.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
- package/dist/worker-transport-COgY4RX8.cjs +2 -0
- package/dist/worker-transport-COgY4RX8.cjs.map +1 -0
- package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-jzX1IusG.js} +49 -45
- package/dist/worker-transport-jzX1IusG.js.map +1 -0
- package/llms.txt +14 -12
- package/package.json +13 -5
- package/dist/bus-C39wspFV.js.map +0 -1
- package/dist/bus-_EaOVPGq.cjs +0 -2
- package/dist/bus-_EaOVPGq.cjs.map +0 -1
- package/dist/config-DUs7uHHt.cjs +0 -2
- package/dist/config-DUs7uHHt.cjs.map +0 -1
- package/dist/config-SgQcCP1_.js +0 -560
- package/dist/config-SgQcCP1_.js.map +0 -1
- package/dist/constants-CUyd9cTZ.js.map +0 -1
- package/dist/constants-CqdJhTxH.cjs +0 -2
- package/dist/constants-CqdJhTxH.cjs.map +0 -1
- package/dist/errors-BE_EZV7Q.js.map +0 -1
- package/dist/errors-CNPbesMs.cjs +0 -3
- package/dist/errors-CNPbesMs.cjs.map +0 -1
- package/dist/factory-CTi0Is3F.js.map +0 -1
- package/dist/factory-hRrH32v5.cjs +0 -2
- package/dist/factory-hRrH32v5.cjs.map +0 -1
- package/dist/identity-DdhKgrpk.js.map +0 -1
- package/dist/identity-DlWRIuwy.cjs +0 -2
- package/dist/identity-DlWRIuwy.cjs.map +0 -1
- package/dist/interactions-CUkzK8sR.cjs +0 -2
- package/dist/interactions-CUkzK8sR.cjs.map +0 -1
- package/dist/interactions-DiFvCosX.js +0 -111
- package/dist/interactions-DiFvCosX.js.map +0 -1
- package/dist/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-BaaFIPCU.js +0 -62
- package/dist/platform-BaaFIPCU.js.map +0 -1
- package/dist/platform-CfA3-7sJ.cjs +0 -2
- package/dist/platform-CfA3-7sJ.cjs.map +0 -1
- package/dist/replay-B3gFXIZd.cjs +0 -2
- package/dist/replay-B3gFXIZd.cjs.map +0 -1
- package/dist/replay-Ds-ANH34.js.map +0 -1
- package/dist/response-body-YdNl-HkR.cjs +0 -3
- package/dist/response-body-YdNl-HkR.cjs.map +0 -1
- package/dist/response-body-eoSQpLiH.js.map +0 -1
- package/dist/rotation-Cwct4ckk.js.map +0 -1
- package/dist/rotation-D4qUAHAu.cjs +0 -2
- package/dist/rotation-D4qUAHAu.cjs.map +0 -1
- package/dist/sender-BdRuNVhF.cjs +0 -2
- package/dist/sender-BdRuNVhF.cjs.map +0 -1
- package/dist/sender-Dv8rAmpV.js.map +0 -1
- package/dist/stored-context-B2EzVuYm.js.map +0 -1
- package/dist/stored-context-CXt7eHZL.cjs +0 -2
- package/dist/stored-context-CXt7eHZL.cjs.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-iUVSjH8L.js +0 -94
- package/dist/worker-transport-CRAX-09c.cjs +0 -2
- package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
- package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as r } from "./batch-
|
|
3
|
-
import { a as i, i as a, o, r as s } from "./factory-
|
|
1
|
+
import { Xn as e, bt as t, xt as n } from "./constants-CEHN6KuY.js";
|
|
2
|
+
import { n as r } from "./batch-120Kc9jr.js";
|
|
3
|
+
import { a as i, i as a, o, r as s } from "./factory-BHYrcSaU.js";
|
|
4
4
|
import { t as c } from "./defineProperty-s2S8BXUc.js";
|
|
5
5
|
// src/storage/idb-driver.ts
|
|
6
6
|
function l(e) {
|
|
@@ -30,22 +30,22 @@ var d = class {
|
|
|
30
30
|
return u((await this.store("readonly")).index("routingContext").count(IDBKeyRange.bound([e, 0], [e, 2 ** 53 - 1])));
|
|
31
31
|
}
|
|
32
32
|
async takeOldest(e) {
|
|
33
|
-
return u((await this.store("readonly")).index(
|
|
33
|
+
return u((await this.store("readonly")).index(t).getAll(null, e));
|
|
34
34
|
}
|
|
35
35
|
async walkOldest(e) {
|
|
36
|
-
let
|
|
37
|
-
await new Promise((
|
|
38
|
-
|
|
39
|
-
let r =
|
|
40
|
-
r === null || !e(r.value) ?
|
|
41
|
-
},
|
|
42
|
-
r(l(
|
|
36
|
+
let n = (await this.store("readonly")).index(t).openCursor();
|
|
37
|
+
await new Promise((t, r) => {
|
|
38
|
+
n.onsuccess = () => {
|
|
39
|
+
let r = n.result;
|
|
40
|
+
r === null || !e(r.value) ? t() : r.continue();
|
|
41
|
+
}, n.onerror = () => {
|
|
42
|
+
r(l(n));
|
|
43
43
|
};
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
async takeBefore(e) {
|
|
47
|
-
let
|
|
48
|
-
return u(
|
|
47
|
+
let n = await this.store("readonly"), r = IDBKeyRange.upperBound(e, !0);
|
|
48
|
+
return u(n.index(t).getAll(r));
|
|
49
49
|
}
|
|
50
50
|
async delete(e) {
|
|
51
51
|
await u((await this.store("readwrite")).delete(e));
|
|
@@ -75,7 +75,7 @@ var d = class {
|
|
|
75
75
|
e !== null && (this.connection = null, (await e).close());
|
|
76
76
|
}
|
|
77
77
|
async store(e) {
|
|
78
|
-
return (await this.open()).transaction(
|
|
78
|
+
return (await this.open()).transaction(n, e).objectStore(n);
|
|
79
79
|
}
|
|
80
80
|
open() {
|
|
81
81
|
let e = this.connection;
|
|
@@ -84,8 +84,8 @@ var d = class {
|
|
|
84
84
|
let i = indexedDB.open(this.name, 12), a = !1;
|
|
85
85
|
i.onupgradeneeded = () => {
|
|
86
86
|
let e = i.result;
|
|
87
|
-
e.objectStoreNames.contains("batches") || e.createObjectStore(
|
|
88
|
-
let r = i.transaction.objectStore(
|
|
87
|
+
e.objectStoreNames.contains("batches") || e.createObjectStore(n, { keyPath: "id" }).createIndex(t, t);
|
|
88
|
+
let r = i.transaction.objectStore(n);
|
|
89
89
|
r.indexNames.contains("routingContext") || r.createIndex("routingContext", ["routingContextId", "createdAt"]);
|
|
90
90
|
}, i.onsuccess = () => {
|
|
91
91
|
let t = i.result;
|
|
@@ -204,4 +204,4 @@ var d = class {
|
|
|
204
204
|
};
|
|
205
205
|
export { f as IndexedDbStorage };
|
|
206
206
|
|
|
207
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
207
|
+
//# sourceMappingURL=indexeddb-storage-BYywz-v6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-GHdl0t8A.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","countRecords","EvictionPick","reportEviction","addDrop","_defineProperty","failureOf","request","promisify","IdbDriver","name","batch","store","range","id","limit","cursor","visit","resolve","cutoff","ids","connection","mode","existing","opening","abandoned","db","reject","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","removed","gone","evicted","records","gap","stored","attempts","result","expired","total","reason","dropped","pick","howMany","hasAction","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// The raw IndexedDB code for the batch store. Opens the database, wraps requests in promises\n// and reads in createdAt order. Code above this file only deals in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts leave the request's error\n * empty, so fall back to a replacement Error. Rejecting with null would fail the\n * instanceof Error test in save(), which would then report a full disk as an ordinary write\n * failure.\n * @param request The request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with the request's error. The\n * request is read as IDBRequest<any>, so every caller has to name the type it expects.\n * @param request The request to await.\n * @returns The request's result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** Wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** The pending or completed open. Reused for every call on this database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any stored batch with the same id.\n * @param batch The batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns The batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first, without removing them. A cursor reads one\n * batch at a time, so the walk can stop before it has read the whole store.\n * @param visit Receives each batch. Return false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads every batch whose createdAt is before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns The batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that isn't stored resolves without an error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. If any delete fails, none of them are deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets a stored batch's attempt count, ignoring an id that isn't stored. A batch we already\n * delivered and deleted must not come back, so the get and the put share one transaction.\n * With two transactions, a prune in another window could delete the batch in between and\n * the put would restore it.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails here, which\n * lets the factory pick a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if there is one. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is only valid until control\n * returns to the event loop, so every call takes a fresh one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call. A failed\n * open isn't kept, so the next call tries again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already has the store. Creating it again would\n // throw ConstraintError and abort the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\")) {\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected, so nothing references this connection.\n // Close it, because an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window is upgrading the schema, and its upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window still holds the previous schema version. This open won't settle\n // until that window closes, and every storage call would wait on it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Stores batches in IndexedDB, indexed by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** What one prune did. save() reads `removed` to see whether its own batch survived. */\ninterface Sweep {\n /** The prune summary across all rules. */\n result: PruneResult;\n /** The batches the prune deleted. */\n removed: LogBatch[];\n}\n\n/** StorageAdapter that keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded, because the factory needs the rejection to pick the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB, then prunes the storage.\n * @param batch The batch to store.\n * @returns True if the batch is in the database after the prune, false if the write failed\n * or the prune removed the batch.\n */\n async save(batch: LogBatch): Promise<boolean> {\n try {\n await this.db.put(batch);\n const { removed } = await this.sweep();\n\n // The prune can remove the batch it just wrote, for example when every older batch holds\n // an action. A true here would promise a resend for a batch that onGap reported as lost.\n return !removed.some((gone) => gone.id === batch.id);\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return stored === true;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report would count it twice.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return false;\n }\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns The retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. Anything larger throws and the read is empty.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const { result } = await this.sweep();\n\n return result;\n }\n\n /**\n * Runs the prune and keeps the batches it deleted. A failed prune reports to diagnostics and\n * returns what it deleted before the failure.\n * @returns The prune summary and the deleted batches.\n */\n private async sweep(): Promise<Sweep> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const removed: LogBatch[] = [];\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n removed.push(...expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n removed.push(...evicted);\n }\n },\n );\n\n return { result, removed };\n }\n\n /**\n * Returns the number of stored batches.\n * @returns The total batch count, or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes every stored batch from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first, because an action is an audit fact. Not guarded, because both callers guard it. A\n * guard here would hide the failure and report an eviction that never happened.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records say whether a batch holds an action. Stop at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":";;;;;AAoBA,SAASQ,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,+BAA+B;AACnE;AAQA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA,EAAQ,gBAAgB;GACtB,EAAOD,EAAUC,CAAO,CAAC;EAC3B;CACF,CAAC;AACH;AAGA,IAAaE,IAAb,MAAuB;CAOrB,YAAY,GAA+B;EAAd,AAAAJ,EAAA,MAAA,QAAA,KAAA,CAAA,GAL7BA,EAAA,MAAA,cAAkD,IAAA,GAKrB,KAAA,OAAAK;CAAe;CAM5C,MAAM,IAAI,GAAgC;EAExC,MAAMF,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIG,CAAK,CAAC;CAClC;CAQA,MAAM,YAAY,GAAY,GAAoC;EAChE,IAAMC,IAAQ,MAAM,KAAK,MAAM,UAAU,GACnCC,IAAQ,YAAY,MAAM,CAACC,GAAI,CAAC,GAAG,CAACA,cAA2B,CAAC;EACtE,OAAON,EAAsBI,EAAM,MAAM,gBAAgB,CAAC,CAAC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AAQG,GAAQC,EAAQ,QAAQ5C,EAAa4C,CAAO,CAAC;EACzE,EAAe,KAAK,aAAa,KAAK,OAAOP,GAAKO,CAAO;CAC3D;CASA,MAAc,YAAY,GAAsC;EAE9D,IAAMC,IAAO,IAAI5C,EAAa6C,GAASC,CAAS;EAChD,MAAM,KAAK,GAAG,YAAY,MAAUF,EAAK,IAAInC,CAAK,CAAC;EAEnD,IAAMsC,IAASH,EAAK,OAAO;EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWG,EAAO,KAAK,MAAUtC,EAAM,EAAE,CAAC,GAEjDsC;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-BYywz-v6.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","countRecords","EvictionPick","reportEviction","addDrop","_defineProperty","failureOf","request","promisify","IdbDriver","name","batch","store","range","id","limit","cursor","visit","resolve","cutoff","ids","connection","mode","existing","opening","abandoned","db","reject","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","removed","gone","evicted","records","gap","stored","attempts","result","expired","total","reason","dropped","pick","howMany","hasAction","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// The raw IndexedDB code for the batch store. Opens the database, wraps requests in promises\n// and reads in createdAt order. Code above this file only deals in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts leave the request's error\n * empty, so fall back to a replacement Error. Rejecting with null would fail the\n * instanceof Error test in save(), which would then report a full disk as an ordinary write\n * failure.\n * @param request The request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with the request's error. The\n * request is read as IDBRequest<any>, so every caller has to name the type it expects.\n * @param request The request to await.\n * @returns The request's result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** Wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** The pending or completed open. Reused for every call on this database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any stored batch with the same id.\n * @param batch The batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns The batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first, without removing them. A cursor reads one\n * batch at a time, so the walk can stop before it has read the whole store.\n * @param visit Receives each batch. Return false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads every batch whose createdAt is before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns The batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that isn't stored resolves without an error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. If any delete fails, none of them are deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets a stored batch's attempt count, ignoring an id that isn't stored. A batch we already\n * delivered and deleted must not come back, so the get and the put share one transaction.\n * With two transactions, a prune in another window could delete the batch in between and\n * the put would restore it.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails here, which\n * lets the factory pick a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if there is one. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is only valid until control\n * returns to the event loop, so every call takes a fresh one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call. A failed\n * open isn't kept, so the next call tries again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already has the store. Creating it again would\n // throw ConstraintError and abort the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\")) {\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected, so nothing references this connection.\n // Close it, because an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window is upgrading the schema, and its upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window still holds the previous schema version. This open won't settle\n // until that window closes, and every storage call would wait on it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Stores batches in IndexedDB, indexed by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** What one prune did. save() reads `removed` to see whether its own batch survived. */\ninterface Sweep {\n /** The prune summary across all rules. */\n result: PruneResult;\n /** The batches the prune deleted. */\n removed: LogBatch[];\n}\n\n/** StorageAdapter that keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded, because the factory needs the rejection to pick the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB, then prunes the storage.\n * @param batch The batch to store.\n * @returns True if the batch is in the database after the prune, false if the write failed\n * or the prune removed the batch.\n */\n async save(batch: LogBatch): Promise<boolean> {\n try {\n await this.db.put(batch);\n const { removed } = await this.sweep();\n\n // The prune can remove the batch it just wrote, for example when every older batch holds\n // an action. A true here would promise a resend for a batch that onGap reported as lost.\n return !removed.some((gone) => gone.id === batch.id);\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return stored === true;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report would count it twice.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return false;\n }\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns The retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. Anything larger throws and the read is empty.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const { result } = await this.sweep();\n\n return result;\n }\n\n /**\n * Runs the prune and keeps the batches it deleted. A failed prune reports to diagnostics and\n * returns what it deleted before the failure.\n * @returns The prune summary and the deleted batches.\n */\n private async sweep(): Promise<Sweep> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const removed: LogBatch[] = [];\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n removed.push(...expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n removed.push(...evicted);\n }\n },\n );\n\n return { result, removed };\n }\n\n /**\n * Returns the number of stored batches.\n * @returns The total batch count, or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes every stored batch from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first, because an action is an audit fact. Not guarded, because both callers guard it. A\n * guard here would hide the failure and report an eviction that never happened.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records say whether a batch holds an action. Stop at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) =>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@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
1
|
+
const e=require("./constants-NtiQDWL_.cjs"),t=require("./batch-C3uNp5kU.cjs"),n=require("./factory-DsaNdcXp.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");function i(e){return e.error??Error(`The IndexedDB request failed.`)}function a(e){return new Promise((t,n)=>{e.onsuccess=()=>{t(e.result)},e.onerror=()=>{n(i(e))}})}var o=class{constructor(e){r.t(this,`name`,void 0),r.t(this,`connection`,null),this.name=e}async put(e){await a((await this.store(`readwrite`)).put(e))}async takeContext(e,t){let n=await this.store(`readonly`),r=IDBKeyRange.bound([e,0],[e,2**53-1]);return a(n.index(`routingContext`).getAll(r,t))}async countContext(e){return a((await this.store(`readonly`)).index(`routingContext`).count(IDBKeyRange.bound([e,0],[e,2**53-1])))}async takeOldest(t){return a((await this.store(`readonly`)).index(e.bt).getAll(null,t))}async walkOldest(t){let n=(await this.store(`readonly`)).index(e.bt).openCursor();await new Promise((e,r)=>{n.onsuccess=()=>{let r=n.result;r===null||!t(r.value)?e():r.continue()},n.onerror=()=>{r(i(n))}})}async takeBefore(t){let n=await this.store(`readonly`),r=IDBKeyRange.upperBound(t,!0);return a(n.index(e.bt).getAll(r))}async delete(e){await a((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>a(t.delete(e))))}async bumpAttempts(e,t){let n=await this.store(`readwrite`),r=await a(n.get(e));r!==void 0&&await a(n.put({...r,attempts:t}))}async count(){return a((await this.store(`readonly`)).count())}async clear(){await a((await this.store(`readwrite`)).clear())}async ready(){await this.open()}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.xt,t).objectStore(e.xt)}open(){let t=this.connection;if(t!==null)return t;let n=new Promise((t,n)=>{let r=indexedDB.open(this.name,12),a=!1;r.onupgradeneeded=()=>{let t=r.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.xt,{keyPath:`id`}).createIndex(e.bt,e.bt);let n=r.transaction.objectStore(e.xt);n.indexNames.contains(`routingContext`)||n.createIndex(`routingContext`,[`routingContextId`,`createdAt`])},r.onsuccess=()=>{let e=r.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},t(e))},r.onerror=()=>{n(i(r))},r.onblocked=()=>{a=!0,n(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=n.catch(e=>{throw this.connection=null,e}),this.connection}},s=class{constructor(t,n,i,a){r.t(this,`limits`,void 0),r.t(this,`diagnostics`,void 0),r.t(this,`onGap`,void 0),r.t(this,`name`,e.Xn),r.t(this,`db`,void 0),this.limits=n,this.diagnostics=i,this.onGap=a,this.db=new o(t)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e);let{removed:t}=await this.sweep();return!t.some(t=>t.id===e.id)}catch(r){if(r instanceof Error&&r.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full. The library removes the oldest batches.`);let r=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove old batches after a full disk.`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));if(r){let e=t.n(r),i={batches:r.length,records:e,reason:`quota`};n.i(this.diagnostics,this.onGap,i,r)}let i=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not write the batch after it removed old batches.`,async()=>(await this.db.put(e),!0));if(i!==!0){let t={batches:1,records:e.records.length,reason:`quota`};n.i(this.diagnostics,this.onGap,t,[e])}return i===!0}return this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},r),this.onGap?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),!1}}async takeContext(e,t){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not query the context partition.`,()=>this.db.takeContext(e,Math.min(t,4294967295)))??[]}async countContext(e){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not count the context partition.`,()=>this.db.countContext(e))??0}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(Math.min(e,4294967295)))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not delete a batch.`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not update the attempt count.`,()=>this.db.bumpAttempts(e,t))}async prune(){let{result:e}=await this.sweep();return e}async sweep(){let e={batches:0,records:0,reason:`expired`},t=[];return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,async()=>{let n=Date.now()-this.limits.maxAgeMs,r=await this.db.takeBefore(n);r.length>0&&(await this.db.deleteMany(r.map(e=>e.id)),this.addGap(e,`expired`,r),t.push(...r));let i=await this.db.count();if(i>this.limits.maxBatches){let n=await this.evictOldest(i-this.limits.maxBatches);this.addGap(e,`over_capacity`,n),t.push(...n)}}),{result:e,removed:t}}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the stored batches.`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not clear the stored batches.`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not close the database.`,()=>this.db.close())}addGap(e,r,i){let a=n.r(e,r,i.length,t.n(i));n.i(this.diagnostics,this.onGap,a,i)}async evictOldest(e){let t=new n.a(e,n.o);await this.db.walkOldest(e=>t.add(e));let r=t.picked();return await this.db.deleteMany(r.map(e=>e.id)),r}};exports.IndexedDbStorage=s;
|
|
2
|
+
//# sourceMappingURL=indexeddb-storage-BfqGkLFe.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-CL9uqBCy.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","require_defineProperty","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","store","range","id","limit","cursor","visit","cutoff","ids","connection","mode","existing","opening","abandoned","db","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","removed","gone","evicted","records","gap","stored","attempts","result","expired","total","reason","dropped","pick","howMany","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// The raw IndexedDB code for the batch store. Opens the database, wraps requests in promises\n// and reads in createdAt order. Code above this file only deals in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts leave the request's error\n * empty, so fall back to a replacement Error. Rejecting with null would fail the\n * instanceof Error test in save(), which would then report a full disk as an ordinary write\n * failure.\n * @param request The request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with the request's error. The\n * request is read as IDBRequest<any>, so every caller has to name the type it expects.\n * @param request The request to await.\n * @returns The request's result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** Wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** The pending or completed open. Reused for every call on this database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any stored batch with the same id.\n * @param batch The batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns The batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first, without removing them. A cursor reads one\n * batch at a time, so the walk can stop before it has read the whole store.\n * @param visit Receives each batch. Return false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads every batch whose createdAt is before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns The batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that isn't stored resolves without an error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. If any delete fails, none of them are deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets a stored batch's attempt count, ignoring an id that isn't stored. A batch we already\n * delivered and deleted must not come back, so the get and the put share one transaction.\n * With two transactions, a prune in another window could delete the batch in between and\n * the put would restore it.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails here, which\n * lets the factory pick a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if there is one. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is only valid until control\n * returns to the event loop, so every call takes a fresh one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call. A failed\n * open isn't kept, so the next call tries again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already has the store. Creating it again would\n // throw ConstraintError and abort the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\")) {\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected, so nothing references this connection.\n // Close it, because an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window is upgrading the schema, and its upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window still holds the previous schema version. This open won't settle\n // until that window closes, and every storage call would wait on it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Stores batches in IndexedDB, indexed by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** What one prune did. save() reads `removed` to see whether its own batch survived. */\ninterface Sweep {\n /** The prune summary across all rules. */\n result: PruneResult;\n /** The batches the prune deleted. */\n removed: LogBatch[];\n}\n\n/** StorageAdapter that keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded, because the factory needs the rejection to pick the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB, then prunes the storage.\n * @param batch The batch to store.\n * @returns True if the batch is in the database after the prune, false if the write failed\n * or the prune removed the batch.\n */\n async save(batch: LogBatch): Promise<boolean> {\n try {\n await this.db.put(batch);\n const { removed } = await this.sweep();\n\n // The prune can remove the batch it just wrote, for example when every older batch holds\n // an action. A true here would promise a resend for a batch that onGap reported as lost.\n return !removed.some((gone) => gone.id === batch.id);\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return stored === true;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report would count it twice.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return false;\n }\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns The retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. Anything larger throws and the read is empty.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const { result } = await this.sweep();\n\n return result;\n }\n\n /**\n * Runs the prune and keeps the batches it deleted. A failed prune reports to diagnostics and\n * returns what it deleted before the failure.\n * @returns The prune summary and the deleted batches.\n */\n private async sweep(): Promise<Sweep> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const removed: LogBatch[] = [];\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n removed.push(...expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n removed.push(...evicted);\n }\n },\n );\n\n return { result, removed };\n }\n\n /**\n * Returns the number of stored batches.\n * @returns The total batch count, or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes every stored batch from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first, because an action is an audit fact. Not guarded, because both callers guard it. A\n * guard here would hide the failure and report an eviction that never happened.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records say whether a batch holds an action. Stop at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":"A,6JAoBA,SAASW,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CAQA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOrB,YAAY,EAA+B,CAAdN,EAAA,EAAA,KAAA,OAAA,IAAA,EAAA,EAL7BA,EAAA,EAAA,KAAA,aAAkD,IAAA,EAKrB,KAAA,KAAAO,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,C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,MAAM,CACtB,GACgB,CAClB,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,gDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAQA,OAAe,EAAqB,EAA+B,EAA2B,CAC5F,IAAME,EAAMvC,EAAAA,EAAQ0C,EAAQG,EAAQC,EAAQ,OAAQ/C,EAAAA,EAAa+C,CAAO,CAAC,EACzEzC,EAAA,EAAe,KAAK,YAAa,KAAK,MAAOkC,EAAKO,CAAO,CAC3D,CASA,MAAc,YAAY,EAAsC,CAE9D,IAAMC,EAAO,IAAI9C,EAAAA,EAAa+C,EAAS9C,EAAAA,CAAS,EAChD,MAAM,KAAK,GAAG,WAAY,GAAU6C,EAAK,IAAIjC,CAAK,CAAC,EAEnD,IAAMmC,EAASF,EAAK,OAAO,EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWE,EAAO,IAAK,GAAUnC,EAAM,EAAE,CAAC,EAEjDmC,CACT,CACF,E"}
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-BfqGkLFe.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","require_defineProperty","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","store","range","id","limit","cursor","visit","cutoff","ids","connection","mode","existing","opening","abandoned","db","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","removed","gone","evicted","records","gap","stored","attempts","result","expired","total","reason","dropped","pick","howMany","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// The raw IndexedDB code for the batch store. Opens the database, wraps requests in promises\n// and reads in createdAt order. Code above this file only deals in batches and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts leave the request's error\n * empty, so fall back to a replacement Error. Rejecting with null would fail the\n * instanceof Error test in save(), which would then report a full disk as an ordinary write\n * failure.\n * @param request The request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds and rejects with the request's error. The\n * request is read as IDBRequest<any>, so every caller has to name the type it expects.\n * @param request The request to await.\n * @returns The request's result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** Wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** The pending or completed open. Reused for every call on this database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch, replacing any stored batch with the same id.\n * @param batch The batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt without removing them.\n * @param limit Maximum number of batches to return.\n * @returns The batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first, without removing them. A cursor reads one\n * batch at a time, so the walk can stop before it has read the whole store.\n * @param visit Receives each batch. Return false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads every batch whose createdAt is before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns The batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that isn't stored resolves without an error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. If any delete fails, none of them are deleted.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets a stored batch's attempt count, ignoring an id that isn't stored. A batch we already\n * delivered and deleted must not come back, so the get and the put share one transaction.\n * With two transactions, a prune in another window could delete the batch in between and\n * the put would restore it.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** Deletes every stored batch. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails here, which\n * lets the factory pick a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** Closes the connection, if there is one. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is only valid until control\n * returns to the event loop, so every call takes a fresh one.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database once and hands the same connection to every later call. A failed\n * open isn't kept, so the next call tries again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already has the store. Creating it again would\n // throw ConstraintError and abort the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\")) {\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n }\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected, so nothing references this connection.\n // Close it, because an open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window is upgrading the schema, and its upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window still holds the previous schema version. This open won't settle\n // until that window closes, and every storage call would wait on it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// Stores batches in IndexedDB, indexed by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** What one prune did. save() reads `removed` to see whether its own batch survived. */\ninterface Sweep {\n /** The prune summary across all rules. */\n result: PruneResult;\n /** The batches the prune deleted. */\n removed: LogBatch[];\n}\n\n/** StorageAdapter that keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** Holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. Not guarded, because the factory needs the rejection to pick the\n * next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB, then prunes the storage.\n * @param batch The batch to store.\n * @returns True if the batch is in the database after the prune, false if the write failed\n * or the prune removed the batch.\n */\n async save(batch: LogBatch): Promise<boolean> {\n try {\n await this.db.put(batch);\n const { removed } = await this.sweep();\n\n // The prune can remove the batch it just wrote, for example when every older batch holds\n // an action. A true here would promise a resend for a batch that onGap reported as lost.\n return !removed.some((gone) => gone.id === batch.id);\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return stored === true;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report would count it twice.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return false;\n }\n }\n\n /**\n * Reads one context's batches in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to return.\n * @returns This context's batches, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns The number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns The retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. Anything larger throws and the read is empty.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const { result } = await this.sweep();\n\n return result;\n }\n\n /**\n * Runs the prune and keeps the batches it deleted. A failed prune reports to diagnostics and\n * returns what it deleted before the failure.\n * @returns The prune summary and the deleted batches.\n */\n private async sweep(): Promise<Sweep> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const removed: LogBatch[] = [];\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n removed.push(...expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n removed.push(...evicted);\n }\n },\n );\n\n return { result, removed };\n }\n\n /**\n * Returns the number of stored batches.\n * @returns The total batch count, or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** Deletes every stored batch from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** Closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first, because an action is an audit fact. Not guarded, because both callers guard it. A\n * guard here would hide the failure and report an eviction that never happened.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records say whether a batch holds an action. Stop at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":"A,6JAoBA,SAASW,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CAQA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOrB,YAAY,EAA+B,CAAdN,EAAA,EAAA,KAAA,OAAA,IAAA,EAAA,EAL7BA,EAAA,EAAA,KAAA,aAAkD,IAAA,EAKrB,KAAA,KAAAO,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIK,CAAK,CAAC,CAClC,CAQA,MAAM,YAAY,EAAY,EAAoC,CAChE,IAAMC,EAAQ,MAAM,KAAK,MAAM,UAAU,EACnCC,EAAQ,YAAY,MAAM,CAACC,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,EACtE,OAAOR,EAAsBM,EAAM,MAAM,gBAAgB,CAAC,CAAC,OAAOC,EAAOE,CAAK,CAAC,CACjF,CAOA,MAAM,aAAa,EAA6B,CAE9C,OAAO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,OAAQ/C,EAAAA,EAAa+C,CAAO,CAAC,EACzEzC,EAAA,EAAe,KAAK,YAAa,KAAK,MAAOkC,EAAKO,CAAO,CAC3D,CASA,MAAc,YAAY,EAAsC,CAE9D,IAAMC,EAAO,IAAI9C,EAAAA,EAAa+C,EAAS9C,EAAAA,CAAS,EAChD,MAAM,KAAK,GAAG,WAAY,GAAU6C,EAAK,IAAIjC,CAAK,CAAC,EAEnD,IAAMmC,EAASF,EAAK,OAAO,EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWE,EAAO,IAAK,GAAUnC,EAAM,EAAE,CAAC,EAEjDmC,CACT,CACF,E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-NtiQDWL_.cjs"),t=require("./patch-DlcKzIi-.cjs"),n=require("./platform-BZjp9wp1.cjs"),r=require("./observed-windows-BlE25nrn.cjs"),i=require("./defineProperty-X1c4tIPD.cjs");var a=`a[target="_blank"], a[download]`,o=1;function s(e){return e?.nodeType===o}var c=`about:blank`;function l(e,t){return t?!!(s(e)?e:e?.parentElement??null)?.closest(t):!1}function u(e){if(e.type===`characterData`)return e.target.data!==e.oldValue;let{attributeName:t,attributeNamespace:n,oldValue:r}=e;return e.target.getAttributeNS(n,t)!==r}function d(t,n){let r=new Map;for(let i of t){if(l(i.target,n))continue;let t=r.get(i.target);if(t||(t={checked:new Set,added:!1,removed:!1},r.set(i.target,t)),i.type===`childList`){if(![...i.addedNodes,...i.removedNodes].every(e=>s(e)&&l(e,n)))return!0;t.added||=i.addedNodes.length>0,t.removed||=i.removedNodes.length>0;continue}if(i.type===`attributes`){let{attributeName:t}=i;if(!e.Kt.includes(t)){if(u(i))return!0;continue}}let a=JSON.stringify([i.attributeNamespace,i.attributeName]);if(!t.checked.has(a)&&(t.checked.add(a),u(i)))return!0}return[...r.values()].some(e=>e.added!==e.removed)}function f(e){try{return e.document.URL===c&&!e.closed}catch{return!1}}function p(e){try{return e.location.href}catch{return``}}function m(e,t,n,r=!1){try{e.removeEventListener(t,n,r)}catch{}}function h(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function g(){return history}var _=class{constructor(e){i.t(this,`ctx`,void 0),i.t(this,`name`,`interactions`),i.t(this,`installed`,!1),i.t(this,`restores`,[]),i.t(this,`lastUrl`,``),i.t(this,`burst`,{target:null,times:[],reported:!1}),i.t(this,`stopDeadCheck`,void 0),i.t(this,`unobserve`,void 0),i.t(this,`onClick`,e=>{this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record a click. It skips that click.`,()=>{this.recordClick(e)})}),i.t(this,`onViewHide`,e=>{let t=e.currentTarget;f(t)||r.n(t)}),i.t(this,`onNavigate`,()=>{let e=this.lastUrl,t=location.href;if(e===t||(this.lastUrl=t,this.ctx.isActive?.()===!1))return;let r=this.ctx.config.capture.fullUrls,{urlTransform:i}=this.ctx.config.capture,a=n.a(e,r,i,this.ctx.diagnostics),o=n.a(t,r,i,this.ctx.diagnostics);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${a} -> ${o}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":a})}),this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&(addEventListener(`click`,this.onClick,!0),this.unobserve=r.t({attach:e=>this.attachView(e),detach:e=>{this.detachView(e)}})),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){if(this.installed){this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate);for(let e of this.restores.splice(0))e();this.unobserve?.(),this.unobserve=void 0,this.stopDeadCheck?.(),this.burst={target:null,times:[],reported:!1}}}recordClick(t){if(this.ctx.isActive?.()===!1)return;let n=t.target;if(!s(n))return;let r=this.ctx.config.capture.interactions,i=typeof r==`object`?r:{},o=i.ignoreSelector,c=o===void 0||o===``?e.yt:o;if(c&&n.closest(c))return;let l=i.actionAttribute??`data-observability-action`,u=((n.closest(`[${l}]`)?.getAttribute(l)??``)||`unknown-click`).slice(0,this.ctx.config.limits.maxBodyChars),d={};i.selector&&(d.selector=h(n)),i.text&&(d.text=n.textContent.trim().slice(0,i.maxTextChars??50)),this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:u,data:Object.keys(d).length>0?d:void 0}),i.rageClicks&&this.countRage(n,u,i),i.deadClicks&&n.closest(`a, button, summary, input[type="button"], input[type="submit"], input[type="reset"], [role="button"], [role="link"], [role="menuitem"], [role="tab"], [${l}]`)&&!n.closest(a)&&this.watchDead(u,i,t.currentTarget)}countRage(e,t,n){let r=Date.now(),i=n.rageClickWindowMs??1e3,a=n.rageClickCount??3,o=this.burst.target===e?this.burst.times.filter(e=>r-e<i):[],s=o.length>0&&this.burst.reported;o.push(r);let c=o.length>=a;this.burst={target:e,times:o,reported:s||c},c&&!s&&this.ctx.logger.logEvent(`ui.rage_click`,{"click.action":t,"click.count":a})}watchDead(e,t,n){if(this.stopDeadCheck||typeof MutationObserver>`u`)return;let i=location.href,a=p(n),o=t.deadClickIgnoreSelector??`[data-observability-live]`,s=!1,c=new MutationObserver(e=>{s||=this.answers(()=>d(e,o))}),u=e=>{s||=this.answers(()=>!l(e.target,o))},f=[];for(let e of[window,...r.i()])try{c.observe(e.document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0}),e.addEventListener(`scroll`,u,{capture:!0,passive:!0}),f.push(e)}catch{r.n(e)}let h=()=>{clearTimeout(g),c.disconnect();for(let e of f)m(e,`scroll`,u,!0);this.stopDeadCheck=void 0},g=setTimeout(()=>{h();let t=location.href!==i||p(n)!==a;!s&&!t&&this.ctx.isActive?.()!==!1&&this.ctx.logger.logEvent(`ui.dead_click`,{"click.action":e})},t.deadClickMs??1e3);this.stopDeadCheck=h}answers(e){return this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not check a page change for a dead click. It counts the change as a response.`,e)??!0}attachView(e){try{return e.document,e.addEventListener(`click`,this.onClick,!0),e.addEventListener(`pagehide`,this.onViewHide),!0}catch{return this.ctx.diagnostics.report(`capture.install_failed`,`The library cannot observe a window from another origin. It captures no clicks there.`),!1}}detachView(e){this.stopDeadCheck?.(),m(e,`click`,this.onClick,!0),m(e,`pagehide`,this.onViewHide)}installHistory(){if(typeof history>`u`)return;let e=g(),n=this.onNavigate,r=!0,i=t.t(e,`pushState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)}),a=t.t(e,`replaceState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)});this.restores.push(()=>{r=!1,i(),a()})}};exports.InteractionCapture=_;
|
|
2
|
+
//# sourceMappingURL=interactions-BXzEel4F.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-BXzEel4F.cjs","names":["NET_CHANGE_ATTRIBUTES","recordedUrl","addWindowObserver","IGNORE_SELECTOR","observedWindows","patch","require_constants","require_patch","require_platform","require_observed_windows","require_defineProperty","LEAVING_LINKS","ELEMENT_NODE","isElement","value","INITIAL_DOCUMENT_URL","insideLive","live","target","writeAnswers","record","attributeNamespace","attributeName","oldValue","batchAnswers","changes","records","node","each","key","onInitialBlank","win","urlOf","unlisten","type","listener","capture","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","event","from","to","full","fromUrl","urlTransform","toUrl","ctx","restore","settings","options","custom","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","pageUrl","viewUrl","view","responded","observer","onScroll","views","stop","timer","moved","test","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. Also detects\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_IGNORE_SELECTOR,\n DEAD_CLICK_MS,\n IGNORE_SELECTOR,\n NET_CHANGE_ATTRIBUTES,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { addWindowObserver, forgetWindow, observedWindows } from \"./observed-windows\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page shows no response, but the click isn't dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/** An element's nodeType. Node.ELEMENT_NODE won't do, because another window has its own Node. */\nconst ELEMENT_NODE = 1;\n\n/**\n * Checks whether a value is an element of any window. instanceof fails for a popout's element,\n * because each window has its own Element class.\n * @param value An event or mutation target.\n * @returns True for an element.\n */\nfunction isElement(value: unknown): value is Element {\n return (value as Partial<Node> | null)?.nodeType === ELEMENT_NODE;\n}\n\n/** The page's initial document in a window that window.open() just made. */\nconst INITIAL_DOCUMENT_URL = \"about:blank\";\n\n/**\n * Checks whether a node or a scroll target sits inside a live region. A removed node is detached\n * by the time the observer runs, so for it closest() can only test the node itself.\n * @param target The node, or the scroll's target.\n * @param live Selector of the live regions. \"\" marks nothing.\n * @returns True if the target is inside a live region.\n * @throws SyntaxError for a selector the browser can't parse. Call it inside a diagnostics guard.\n */\nfunction insideLive(target: EventTarget | null, live: string): boolean {\n if (!live) {\n return false;\n }\n\n // A text change targets a Text node, and the document and the window have no closest().\n const element = isElement(target)\n ? target\n : ((target as Partial<Node> | null)?.parentElement ?? null);\n return Boolean(element?.closest(live));\n}\n\n/**\n * Checks whether an attribute or a text node now differs from a record's old value.\n * @param record An attributes or characterData change.\n * @returns True if the current value differs from the record's old value.\n */\nfunction writeAnswers(record: MutationRecord): boolean {\n if (record.type === \"characterData\") {\n return (record.target as CharacterData).data !== record.oldValue;\n }\n\n // An attributes record always names its attribute.\n const { attributeName, attributeNamespace, oldValue } = record as MutationRecord & {\n attributeName: string;\n };\n return (record.target as Element).getAttributeNS(attributeNamespace, attributeName) !== oldValue;\n}\n\n/** What one observer batch did to one node. */\ninterface NodeChanges {\n /** The net-change attributes and the text data whose first record the batch has checked. */\n checked: Set<string>;\n /** True if a live element was added under this node. */\n added: boolean;\n /** True if a live element was removed from under this node. */\n removed: boolean;\n}\n\n/**\n * Checks whether one observer batch answers a click. A change inside a live region doesn't, and\n * neither does a write that keeps the old value. A batch that sets `name` or `type`, or a text's\n * data, and then puts the old value back doesn't either, because React rewrites an input that\n * way. Any other attribute answers at each write with a new value, even if a later write puts\n * the old one back, because a class or style change around a forced layout restarts an\n * animation, which the user sees. A grid that swaps a live element for a new one under the same\n * parent doesn't answer. A live element that only appears or only goes away does, because a\n * click can show or hide it.\n * @param records The batch.\n * @param live Selector of the live regions.\n * @returns True if a change in the batch answers the click.\n * @throws SyntaxError for a selector the browser can't parse. Call it inside a diagnostics guard.\n */\nfunction batchAnswers(records: readonly MutationRecord[], live: string): boolean {\n const changes = new Map<Node, NodeChanges>();\n for (const record of records) {\n if (insideLive(record.target, live)) {\n continue;\n }\n\n let node = changes.get(record.target);\n if (!node) {\n node = { checked: new Set(), added: false, removed: false };\n changes.set(record.target, node);\n }\n\n if (record.type === \"childList\") {\n const nodes = [...record.addedNodes, ...record.removedNodes];\n if (!nodes.every((each) => isElement(each) && insideLive(each, live))) {\n return true;\n }\n // A browser can report one swap as one record or as two, so count the sides per parent.\n node.added ||= record.addedNodes.length > 0;\n node.removed ||= record.removedNodes.length > 0;\n continue;\n }\n\n if (record.type === \"attributes\") {\n // An attributes record always names its attribute.\n const { attributeName } = record as MutationRecord & { attributeName: string };\n if (!NET_CHANGE_ATTRIBUTES.includes(attributeName)) {\n if (writeAnswers(record)) {\n return true;\n }\n continue;\n }\n }\n\n // Only the first record's old value is the value before the batch. The namespace keeps an\n // SVG type apart from xlink:type, and a text's data has a null name, unlike any attribute.\n const key = JSON.stringify([record.attributeNamespace, record.attributeName]);\n if (node.checked.has(key)) {\n continue;\n }\n node.checked.add(key);\n if (writeAnswers(record)) {\n return true;\n }\n }\n\n return [...changes.values()].some((node) => node.added !== node.removed);\n}\n\n/**\n * Checks whether an open window still shows the about:blank that window.open() starts with. A\n * window that turned cross-origin throws, and that's the expected answer. The fallback is false,\n * so the caller forgets the window and no throw reaches the page from its pagehide.\n * @param win The window.\n * @returns True for an open window on its initial about:blank.\n */\nfunction onInitialBlank(win: Window): boolean {\n try {\n return win.document.URL === INITIAL_DOCUMENT_URL && !win.closed;\n } catch {\n return false;\n }\n}\n\n/**\n * Reads a window's URL. A window that turned cross-origin throws, and that's the expected answer.\n * The fallback is \"\", so the URL counts as changed.\n * @param win The window.\n * @returns The URL, or \"\" when the window can't be read.\n */\nfunction urlOf(win: Window): string {\n try {\n return win.location.href;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Removes one listener from a window. A window that turned cross-origin throws, and that's the\n * expected answer. It holds no listener of ours, so the fallback is to remove nothing.\n * @param win The window.\n * @param type The event type.\n * @param listener The listener.\n * @param capture True for a capture-phase listener.\n */\nfunction unlisten(win: Window, type: string, listener: EventListener, capture = false): void {\n try {\n win.removeEventListener(type, listener, capture);\n } catch {\n // Nothing to remove. The listener went with the document the window left.\n }\n}\n\n/**\n * Builds a short CSS selector for an element. Prefers the test ID, then the ID, then the\n * aria-label, then the class names.\n * @param element Target DOM element.\n * @returns The selector.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and slicing it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members this module replaces. They are declared as properties, not\n * methods, so the original functions stay unbound. With a bound copy, uninstall would\n * restore a different function from the one it replaced, and every install cycle would\n * stack one more bind on top of the last.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object, typed so that its methods stay unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user clicks and single-page navigations. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions for the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** The URL before the latest navigation. */\n private lastUrl = \"\";\n\n /** The element of the current click burst, and when each of its clicks happened. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that is running now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /** Detaches the observed windows. Set while clicks are captured. */\n private unobserve: (() => void) | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger, breadcrumbs and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // In the capture phase we see the click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n // The app's observed windows outlive this capture, so one observed before the install\n // gets attached here.\n this.unobserve = addWindowObserver({\n attach: (win) => this.attachView(win),\n detach: (win) => {\n this.detachView(win);\n },\n });\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes the interaction listeners and restores every history method that still holds our\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n // Restore history first. An observed window is another document, and a fault there mustn't\n // leave this page patched.\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n this.unobserve?.();\n this.unobserve = undefined;\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Records a click. The browser calls this directly, so a throw would be a page error. */\n private readonly onClick = (event: Event): void => {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a click. It skips that click.\",\n () => {\n this.recordClick(event);\n },\n );\n };\n\n /**\n * Rotates the trace context, records a click breadcrumb and runs the rage and dead click checks.\n * @param event The click.\n */\n private recordClick(event: Event): void {\n if (this.ctx.isActive?.() === false) {\n return;\n }\n const target = event.target;\n if (!isElement(target)) {\n return;\n }\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n // \"\" means the default, because undefined in a later configure() keeps a custom selector.\n const custom = options.ignoreSelector;\n const ignore = custom === undefined || custom === \"\" ? IGNORE_SELECTOR : custom;\n if (ignore && target.closest(ignore)) {\n return;\n }\n // A missing or empty attribute gives \"\", and the message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) {\n data.selector = describeElement(target);\n }\n if (options.text) {\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n }\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n // The listener sits on the window that got the click, the page's own or an observed one.\n this.watchDead(message, options, event.currentTarget as Window);\n }\n }\n\n /**\n * Counts the clicks on one element and records `ui.rage_click` once per burst.\n * @param target Clicked element.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst only ends once no click is left in the window, so clicks that keep sliding\n // through it don't fire a second event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page and each observed window after a click on a control. If there's no DOM\n * change, URL change or scroll within `deadClickMs`, it records `ui.dead_click`. Only one\n * check runs at a time.\n * @param action The click's action name.\n * @param options Interaction options.\n * @param view The window that got the click. Its URL change answers the click too.\n */\n private watchDead(action: string, options: InteractionOptions, view: Window): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const pageUrl = location.href;\n const viewUrl = urlOf(view);\n const live = options.deadClickIgnoreSelector ?? DEAD_CLICK_IGNORE_SELECTOR;\n let responded = false;\n const observer = new MutationObserver((records) => {\n responded ||= this.answers(() => batchAnswers(records, live));\n });\n const onScroll = (event: Event): void => {\n responded ||= this.answers(() => !insideLive(event.target, live));\n };\n // A click in a popout can change this page, and a click here can change a popout.\n const views: Window[] = [];\n for (const each of [window, ...observedWindows()]) {\n try {\n // The old values let a same-value write count as no change.\n observer.observe(each.document, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n });\n each.addEventListener(\"scroll\", onScroll, { capture: true, passive: true });\n views.push(each);\n } catch {\n // A window that turned cross-origin throws, and that's the expected answer. The fallback\n // skips it and forgets it, because the library can't watch it anymore.\n forgetWindow(each);\n }\n }\n\n const stop = (): void => {\n // timer is declared after stop, but stop can only run once that line has executed.\n clearTimeout(timer);\n observer.disconnect();\n for (const each of views) {\n unlisten(each, \"scroll\", onScroll, true);\n }\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n const moved = location.href !== pageUrl || urlOf(view) !== viewUrl;\n if (!responded && !moved && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /**\n * Runs one dead click test in a guard. A failed test counts as an answer, so a fault can't make\n * up a dead click. The browser calls the observer and the listener directly, so a throw would\n * be a page error.\n * @param test Returns true if a change answers the click.\n * @returns The test's result, or true if it threw.\n */\n private answers(test: () => boolean): boolean {\n return (\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not check a page change for a dead click. It counts the change as a response.\",\n test,\n ) ?? true\n );\n }\n\n /**\n * Starts listening for clicks in an observed window.\n * @param win The window.\n * @returns False for a window from another origin, after it reports the window.\n */\n private attachView(win: Window): boolean {\n try {\n // Only a window of this origin has a readable document. Reading it first means a window\n // from another origin throws before it gets a listener.\n const _sameOrigin = win.document;\n win.addEventListener(\"click\", this.onClick, true);\n win.addEventListener(\"pagehide\", this.onViewHide);\n return true;\n } catch {\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The library cannot observe a window from another origin. It captures no clicks there.\",\n );\n return false;\n }\n }\n\n /**\n * Stops listening in an observed window. A running dead click check stops too, without a\n * record, because it holds a listener in this window. A window that leaves during the check\n * has most often answered the click, for example a popout that docks back into the page.\n * @param win The window.\n */\n private detachView(win: Window): void {\n this.stopDeadCheck?.();\n unlisten(win, \"click\", this.onClick, true);\n unlisten(win, \"pagehide\", this.onViewHide);\n }\n\n /** Forgets an observed window when its page goes away, so the library doesn't hold it. */\n private readonly onViewHide = (event: Event): void => {\n const win = event.currentTarget as Window;\n // window.open(url) starts on about:blank and fires pagehide there. Then it loads a page of\n // this origin into the same window, which keeps our listeners, so forgetting it would lose it.\n if (onInitialBlank(win)) {\n return;\n }\n\n forgetWindow(win);\n };\n\n /** On a URL change, rotates the trace context and records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) {\n return;\n }\n\n // The comparison above uses the full URL, so a query-only change still counts as a\n // navigation. The record doesn't keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL, and the record builder adds the current one as\n // `page.url`. Putting the new URL in `url.full` would make a navigation look like an HTTP\n // request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. Reading from the prototype would skip a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser only updates location.href after the call returns,\n // so a synchronous read would report the previous URL as the new one.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"A,2MAyBA,IAAMW,EAAgB,kCAGhBC,EAAe,EAQrB,SAASC,EAAU,EAAkC,CACnD,OAAQC,GAAgC,WAAaF,CACvD,CAGA,IAAMG,EAAuB,cAU7B,SAASC,EAAW,EAA4B,EAAuB,CASrE,OARKC,EAQE,GAHSJ,EAAUK,CAAM,EAC5BA,EACEA,GAAiC,eAAiB,KACzC,EAAS,QAAQD,CAAI,EAP3B,EAQX,CAOA,SAASE,EAAa,EAAiC,CACrD,GAAIC,EAAO,OAAS,gBAClB,OAAQA,EAAO,OAAyB,OAASA,EAAO,SAI1D,GAAM,CAAE,gBAAe,qBAAoB,YAAaA,EAGxD,OAAQA,EAAO,OAAmB,eAAeC,EAAoBC,CAAa,IAAMC,CAC1F,CA0BA,SAASC,EAAa,EAAoC,EAAuB,CAC/E,IAAMC,EAAU,IAAI,IACpB,IAAK,IAAML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