@utk09/ui-observability 0.11.0 → 0.12.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 +61 -0
- package/README.md +273 -102
- package/bin/uiobs.mjs +1 -1
- package/dist/{batch-CL9uWYY3.js → batch-BjQUwjA6.js} +4 -4
- package/dist/batch-BjQUwjA6.js.map +1 -0
- package/dist/{batch-C8OcWR2L.cjs → batch-D5LlU4Q9.cjs} +2 -2
- package/dist/batch-D5LlU4Q9.cjs.map +1 -0
- package/dist/bus/bus.d.ts +48 -47
- package/dist/bus/links.d.ts +4 -4
- package/dist/bus/validation.d.ts +1 -1
- package/dist/bus-D_7pd7RN.cjs +2 -0
- package/dist/bus-D_7pd7RN.cjs.map +1 -0
- package/dist/{bus-BZ0GldpT.js → bus-ecxUNTja.js} +91 -91
- package/dist/bus-ecxUNTja.js.map +1 -0
- package/dist/capture/console.d.ts +10 -10
- package/dist/capture/errors.d.ts +6 -6
- package/dist/capture/interactions.d.ts +14 -14
- package/dist/capture/lifecycle.d.ts +3 -3
- package/dist/capture/long-frames.d.ts +6 -6
- package/dist/capture/network.d.ts +17 -17
- package/dist/capture/profiler-frames.d.ts +44 -0
- package/dist/capture/replay-buffer.d.ts +46 -0
- package/dist/capture/replay-upload.d.ts +74 -0
- package/dist/capture/replay.d.ts +114 -0
- package/dist/capture/reports.d.ts +2 -2
- package/dist/capture/resource-timing.d.ts +1 -1
- package/dist/capture/server-timing.d.ts +3 -3
- package/dist/capture/storm.d.ts +3 -3
- package/dist/capture/types.d.ts +45 -33
- package/dist/capture/unclean-exit.d.ts +8 -8
- package/dist/capture/user-timing.d.ts +3 -3
- package/dist/capture/web-socket.d.ts +11 -11
- package/dist/capture/web-vitals.d.ts +20 -7
- package/dist/compression-AJJCMBOa.js +11 -0
- package/dist/compression-AJJCMBOa.js.map +1 -0
- package/dist/compression-lD9abCcO.cjs +2 -0
- package/dist/compression-lD9abCcO.cjs.map +1 -0
- package/dist/{console-BPZCuSLc.cjs → console-CLz_PvFn.cjs} +2 -2
- package/dist/console-CLz_PvFn.cjs.map +1 -0
- package/dist/{console-BeCF7n59.js → console-cwgHKXvM.js} +4 -4
- package/dist/console-cwgHKXvM.js.map +1 -0
- package/dist/constants-Bwl_YtQi.js +349 -0
- package/dist/constants-Bwl_YtQi.js.map +1 -0
- package/dist/constants-DakMxVB2.cjs +2 -0
- package/dist/constants-DakMxVB2.cjs.map +1 -0
- package/dist/constants.d.ts +150 -103
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
- package/dist/context-storage-BzkoHzkQ.js.map +1 -1
- package/dist/core/breadcrumbs.d.ts +16 -15
- package/dist/core/config.d.ts +3 -3
- package/dist/core/context.d.ts +7 -7
- package/dist/core/debug-buffer.d.ts +10 -10
- package/dist/core/debug-bundle.d.ts +3 -3
- package/dist/core/deferred.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +24 -21
- package/dist/core/drops.d.ts +7 -7
- package/dist/core/hold-buffer.d.ts +1 -1
- package/dist/core/journey.d.ts +22 -23
- package/dist/core/logger.d.ts +22 -21
- package/dist/core/measure.d.ts +7 -7
- package/dist/core/meter.d.ts +25 -21
- package/dist/core/pipeline.d.ts +42 -41
- package/dist/core/profile-buckets.d.ts +31 -0
- package/dist/core/profiler.d.ts +218 -0
- package/dist/core/record.d.ts +23 -23
- package/dist/core/remote-rules.d.ts +4 -4
- package/dist/core/remote-sampling.d.ts +21 -20
- package/dist/core/runtime.d.ts +206 -137
- package/dist/core/sampling.d.ts +18 -18
- package/dist/core/sender.d.ts +22 -20
- package/dist/core/spans.d.ts +5 -5
- package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
- package/dist/deadline-C4ccAuk5.js.map +1 -0
- package/dist/deadline-CUGbto-y.cjs +2 -0
- package/dist/deadline-CUGbto-y.cjs.map +1 -0
- package/dist/{debug-bundle-C7UkHZ-q.js → debug-bundle-BOdYmCeV.js} +10 -3
- package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
- package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
- package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.cjs.map +1 -1
- package/dist/doctor.d.ts +16 -6
- package/dist/doctor.js +147 -52
- package/dist/doctor.js.map +1 -1
- package/dist/{emergency-queue-Zy6lNafo.js → emergency-queue-B9WZxanZ.js} +4 -4
- package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
- package/dist/{emergency-queue-CNTRui5t.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
- package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
- package/dist/error-like-B11pB4aL.js.map +1 -1
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-Dh7kef0i.js → errors-D6bwgJtO.js} +3 -3
- package/dist/errors-D6bwgJtO.js.map +1 -0
- package/dist/{errors-tfEr48bS.cjs → errors-DCOCRdSi.cjs} +2 -2
- package/dist/errors-DCOCRdSi.cjs.map +1 -0
- package/dist/{factory-CJXVYp0R.cjs → factory-DLFDjdLv.cjs} +2 -2
- package/dist/factory-DLFDjdLv.cjs.map +1 -0
- package/dist/{factory-BonqI3NL.js → factory-e9Qo3K0z.js} +13 -13
- package/dist/factory-e9Qo3K0z.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
- package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/global-scope-D9I8s-oN.js.map +1 -1
- package/dist/guards-Cidk71ME.js.map +1 -1
- package/dist/guards-nJ70syPt.cjs.map +1 -1
- package/dist/{identity-Cxgj6pZX.cjs → identity-BlvlgjrU.cjs} +2 -2
- package/dist/identity-BlvlgjrU.cjs.map +1 -0
- package/dist/{identity-DT5VmvXy.js → identity-BrQp_5J5.js} +19 -19
- package/dist/identity-BrQp_5J5.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +112 -79
- package/dist/index.js +783 -635
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CIoW21Xd.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
- package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
- package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-DLXQzAGh.js} +4 -4
- package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
- package/dist/{interactions-DTgKy_6K.js → interactions-B6z2I4tU.js} +3 -3
- package/dist/interactions-B6z2I4tU.js.map +1 -0
- package/dist/{interactions-fEN6FbVo.cjs → interactions-P6pz08Jn.cjs} +2 -2
- package/dist/interactions-P6pz08Jn.cjs.map +1 -0
- package/dist/{journey-CuJrHzEg.js → journey-35yCMNFo.js} +20 -19
- package/dist/journey-35yCMNFo.js.map +1 -0
- package/dist/journey-DAGh5h9k.cjs +2 -0
- package/dist/journey-DAGh5h9k.cjs.map +1 -0
- package/dist/keys-BHhw_0Wh.cjs.map +1 -1
- package/dist/keys-BU9j5YqW.js.map +1 -1
- package/dist/{library-console-D2GY9Or6.cjs → library-console-BFWEuQsl.cjs} +2 -2
- package/dist/library-console-BFWEuQsl.cjs.map +1 -0
- package/dist/{library-console-C1m6g1BR.js → library-console-Dl_Ly6DQ.js} +2 -2
- package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
- package/dist/{library-request-1BX_UlaX.cjs → library-request-Da-CHKzT.cjs} +2 -2
- package/dist/library-request-Da-CHKzT.cjs.map +1 -0
- package/dist/{library-request-BQBT9N9Q.js → library-request-nI6pvI6I.js} +2 -2
- package/dist/library-request-nI6pvI6I.js.map +1 -0
- package/dist/{lifecycle-2EtUaRpo.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
- package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
- package/dist/{lifecycle-BaKx_-32.js → lifecycle-CZ6RRXc6.js} +2 -2
- package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
- package/dist/{log-record-i9zOTkpQ.cjs → log-record-D7bA1RPb.cjs} +2 -2
- package/dist/log-record-D7bA1RPb.cjs.map +1 -0
- package/dist/{log-record-CAoGBBf3.js → log-record-DIA6McNr.js} +2 -2
- package/dist/log-record-DIA6McNr.js.map +1 -0
- package/dist/{long-frames-Czk7IupC.js → long-frames-430_85Da.js} +8 -6
- package/dist/long-frames-430_85Da.js.map +1 -0
- package/dist/long-frames-Dd8tsi2U.cjs +2 -0
- package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
- package/dist/models/batch.d.ts +14 -15
- package/dist/models/bus.d.ts +24 -24
- package/dist/models/config.d.ts +402 -216
- package/dist/models/drop.d.ts +13 -11
- package/dist/models/health.d.ts +13 -13
- package/dist/models/log-record.d.ts +13 -14
- package/dist/models/metric.d.ts +82 -17
- package/dist/models/plugin.d.ts +13 -13
- package/dist/models/replay.d.ts +60 -0
- package/dist/models/serializer.d.ts +2 -3
- package/dist/models/stats.d.ts +2 -2
- package/dist/models/storage.d.ts +12 -11
- package/dist/{network-DBNwApoF.js → network-C7SkLf4v.js} +12 -12
- package/dist/network-C7SkLf4v.js.map +1 -0
- package/dist/{network-xbbuvG_6.cjs → network-pEX3PAJv.cjs} +2 -2
- package/dist/network-pEX3PAJv.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/otlp-2MCrC3kd.cjs +2 -0
- package/dist/otlp-2MCrC3kd.cjs.map +1 -0
- package/dist/{otlp-BTJdIa6F.js → otlp-COq033e3.js} +25 -32
- package/dist/otlp-COq033e3.js.map +1 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -1
- package/dist/patch-UdPz1ea8.js.map +1 -1
- package/dist/{platform-C2Ez5kDc.cjs → platform-12uR7kBQ.cjs} +2 -2
- package/dist/platform-12uR7kBQ.cjs.map +1 -0
- package/dist/{platform-DkcuXwe-.js → platform-CVewe4wQ.js} +7 -7
- package/dist/platform-CVewe4wQ.js.map +1 -0
- package/dist/profiler-BVWIOgnq.js +310 -0
- package/dist/profiler-BVWIOgnq.js.map +1 -0
- package/dist/profiler-eVCknCzS.cjs +2 -0
- package/dist/profiler-eVCknCzS.cjs.map +1 -0
- package/dist/profiler-frames-CLXlT_xL.js +86 -0
- package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
- package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
- package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
- package/dist/{remote-rules-Cfb4K-Nl.js → remote-rules-BJGDJGwA.js} +27 -27
- package/dist/remote-rules-BJGDJGwA.js.map +1 -0
- package/dist/{remote-rules-vzvk7aKf.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
- package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
- package/dist/replay-0zAJv9T3.js +338 -0
- package/dist/replay-0zAJv9T3.js.map +1 -0
- package/dist/replay-DomJpXqW.cjs +2 -0
- package/dist/replay-DomJpXqW.cjs.map +1 -0
- package/dist/{reports-Dk2YhKIh.cjs → reports-BsbqmP8h.cjs} +2 -2
- package/dist/reports-BsbqmP8h.cjs.map +1 -0
- package/dist/{reports-TA-zInnq.js → reports-BuXekPOS.js} +3 -3
- package/dist/reports-BuXekPOS.js.map +1 -0
- package/dist/{resource-timing-BLv3EA2A.js → resource-timing-CXGHwFRD.js} +4 -4
- package/dist/resource-timing-CXGHwFRD.js.map +1 -0
- package/dist/{resource-timing-Cysw1S1f.cjs → resource-timing-DkycFGDa.cjs} +2 -2
- package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
- package/dist/{sampling-Ckh2yW9k.cjs → sampling-Dd0wllyq.cjs} +2 -2
- package/dist/sampling-Dd0wllyq.cjs.map +1 -0
- package/dist/{sampling-C4VV-1MS.js → sampling-UUDbi3K0.js} +9 -9
- package/dist/sampling-UUDbi3K0.js.map +1 -0
- package/dist/{sanitize-6ymPlVvP.js → sanitize-CNmsD9r3.js} +2 -2
- package/dist/sanitize-CNmsD9r3.js.map +1 -0
- package/dist/{sanitize-BAWzkZt0.cjs → sanitize-ChLn97Ch.cjs} +2 -2
- package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
- package/dist/{select-ZF4by-lF.cjs → select-CTk-K5mG.cjs} +3 -3
- package/dist/select-CTk-K5mG.cjs.map +1 -0
- package/dist/{select-xtQaenIi.js → select-DPv_j6wq.js} +61 -61
- package/dist/select-DPv_j6wq.js.map +1 -0
- package/dist/{sender-CiMHC9YG.js → sender-15zEsZpr.js} +61 -60
- package/dist/sender-15zEsZpr.js.map +1 -0
- package/dist/sender-Bfpv9tad.cjs +2 -0
- package/dist/sender-Bfpv9tad.cjs.map +1 -0
- package/dist/storage/context-storage.d.ts +34 -33
- package/dist/storage/emergency-queue.d.ts +9 -9
- package/dist/storage/eviction.d.ts +12 -12
- package/dist/storage/factory.d.ts +8 -7
- package/dist/storage/gap.d.ts +6 -6
- package/dist/storage/idb-driver.d.ts +31 -32
- package/dist/storage/indexeddb-storage.d.ts +26 -27
- package/dist/storage/keys.d.ts +7 -7
- package/dist/storage/local-storage.d.ts +38 -38
- package/dist/storage/memory-storage.d.ts +21 -22
- package/dist/storage/persistence.d.ts +1 -1
- package/dist/storage-BA9RqRO-.cjs.map +1 -1
- package/dist/storage-DZwed89z.js.map +1 -1
- package/dist/{storm-VR024_QN.js → storm-BTSNTIWI.js} +2 -2
- package/dist/storm-BTSNTIWI.js.map +1 -0
- package/dist/{storm-CYi9Swpx.cjs → storm-D0_qZOEg.cjs} +2 -2
- package/dist/storm-D0_qZOEg.cjs.map +1 -0
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +7 -7
- package/dist/transport/exit-flush.d.ts +39 -39
- package/dist/transport/headers.d.ts +2 -2
- package/dist/transport/http-transport.d.ts +28 -27
- package/dist/transport/memory-transport.d.ts +6 -6
- package/dist/transport/retry-engine.d.ts +35 -34
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
- package/dist/transport/serializers/otlp-traces.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +16 -16
- package/dist/transport/serializers/select.d.ts +7 -7
- package/dist/transport/status-transport.d.ts +20 -20
- package/dist/transport/worker-protocol.d.ts +3 -3
- package/dist/types-BAerHgCq.js.map +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-DFUN57wY.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
- package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
- package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-Cob_jyTv.js} +2 -2
- package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
- package/dist/unref-CU9Nyz_9.cjs +2 -0
- package/dist/unref-CU9Nyz_9.cjs.map +1 -0
- package/dist/unref-DgHPQeWv.js +7 -0
- package/dist/unref-DgHPQeWv.js.map +1 -0
- package/dist/user-timing-CdYqx3PF.cjs +2 -0
- package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
- package/dist/{user-timing-_jZIhDKI.js → user-timing-DgHubxCI.js} +5 -3
- package/dist/user-timing-DgHubxCI.js.map +1 -0
- package/dist/utils/console.d.ts +2 -2
- package/dist/utils/deadline.d.ts +4 -4
- package/dist/utils/error-like.d.ts +7 -7
- package/dist/utils/fixed-window.d.ts +9 -8
- package/dist/utils/global-scope.d.ts +8 -8
- package/dist/utils/guards.d.ts +2 -2
- package/dist/utils/identity.d.ts +17 -17
- package/dist/utils/library-console.d.ts +4 -4
- package/dist/utils/library-request.d.ts +10 -10
- package/dist/utils/lock.d.ts +10 -9
- package/dist/utils/openfin.d.ts +5 -5
- package/dist/utils/patch.d.ts +6 -6
- package/dist/utils/platform.d.ts +13 -11
- package/dist/utils/sanitize.d.ts +4 -4
- package/dist/utils/timer.d.ts +1 -1
- package/dist/utils/tracing.d.ts +38 -38
- package/dist/utils/unref.d.ts +3 -3
- package/dist/{web-socket-BWUoqBh8.cjs → web-socket-BTuvYoJI.cjs} +2 -2
- package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
- package/dist/{web-socket-CV7yIMnm.js → web-socket-DthJuSAg.js} +4 -4
- package/dist/web-socket-DthJuSAg.js.map +1 -0
- package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
- package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
- package/dist/web-vitals-CsGCWnUr.js +77 -0
- package/dist/web-vitals-CsGCWnUr.js.map +1 -0
- package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-B0_8rWy5.js} +4 -4
- package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
- package/dist/{worker-protocol-Bai7GAIA.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
- package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
- package/dist/worker-server-4en-Lt-3.cjs +2 -0
- package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
- package/dist/{worker-server-Dp5HYm4b.js → worker-server-Cne9MX9I.js} +8 -8
- package/dist/{worker-server-Dp5HYm4b.js.map → worker-server-Cne9MX9I.js.map} +1 -1
- package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
- package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
- package/dist/{worker-transport-D6jtgpqN.js → worker-transport-C3SjJAEC.js} +62 -61
- package/dist/worker-transport-C3SjJAEC.js.map +1 -0
- package/package.json +8 -2
- package/dist/batch-C8OcWR2L.cjs.map +0 -1
- package/dist/batch-CL9uWYY3.js.map +0 -1
- package/dist/bus-BZ0GldpT.js.map +0 -1
- package/dist/bus-VWlmM5xs.cjs +0 -2
- package/dist/bus-VWlmM5xs.cjs.map +0 -1
- package/dist/console-BPZCuSLc.cjs.map +0 -1
- package/dist/console-BeCF7n59.js.map +0 -1
- package/dist/constants-DqKJH_MP.cjs +0 -2
- package/dist/constants-DqKJH_MP.cjs.map +0 -1
- package/dist/constants-zyrqveN4.js +0 -304
- package/dist/constants-zyrqveN4.js.map +0 -1
- package/dist/deadline-BOjOxNHj.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
- package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
- package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
- package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
- package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
- package/dist/errors-Dh7kef0i.js.map +0 -1
- package/dist/errors-tfEr48bS.cjs.map +0 -1
- package/dist/factory-BonqI3NL.js.map +0 -1
- package/dist/factory-CJXVYp0R.cjs.map +0 -1
- package/dist/identity-Cxgj6pZX.cjs.map +0 -1
- package/dist/identity-DT5VmvXy.js.map +0 -1
- package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
- package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
- package/dist/interactions-DTgKy_6K.js.map +0 -1
- package/dist/interactions-fEN6FbVo.cjs.map +0 -1
- package/dist/journey-CuJrHzEg.js.map +0 -1
- package/dist/journey-pffMVMfa.cjs +0 -2
- package/dist/journey-pffMVMfa.cjs.map +0 -1
- package/dist/library-console-C1m6g1BR.js.map +0 -1
- package/dist/library-console-D2GY9Or6.cjs.map +0 -1
- package/dist/library-request-1BX_UlaX.cjs.map +0 -1
- package/dist/library-request-BQBT9N9Q.js.map +0 -1
- package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
- package/dist/lifecycle-BaKx_-32.js.map +0 -1
- package/dist/log-record-CAoGBBf3.js.map +0 -1
- package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
- package/dist/long-frames-BVg4i5SC.cjs +0 -2
- package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
- package/dist/long-frames-Czk7IupC.js.map +0 -1
- package/dist/network-DBNwApoF.js.map +0 -1
- package/dist/network-xbbuvG_6.cjs.map +0 -1
- package/dist/otlp-BDvFrLnc.cjs +0 -2
- package/dist/otlp-BDvFrLnc.cjs.map +0 -1
- package/dist/otlp-BTJdIa6F.js.map +0 -1
- package/dist/platform-C2Ez5kDc.cjs.map +0 -1
- package/dist/platform-DkcuXwe-.js.map +0 -1
- package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
- package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
- package/dist/reports-Dk2YhKIh.cjs.map +0 -1
- package/dist/reports-TA-zInnq.js.map +0 -1
- package/dist/resource-timing-BLv3EA2A.js.map +0 -1
- package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
- package/dist/sampling-C4VV-1MS.js.map +0 -1
- package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
- package/dist/sanitize-6ymPlVvP.js.map +0 -1
- package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
- package/dist/select-ZF4by-lF.cjs.map +0 -1
- package/dist/select-xtQaenIi.js.map +0 -1
- package/dist/sender-CiMHC9YG.js.map +0 -1
- package/dist/sender-D5wBoXA8.cjs +0 -2
- package/dist/sender-D5wBoXA8.cjs.map +0 -1
- package/dist/storm-CYi9Swpx.cjs.map +0 -1
- package/dist/storm-VR024_QN.js.map +0 -1
- package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
- package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
- package/dist/user-timing-C9kfRq3J.cjs +0 -2
- package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
- package/dist/user-timing-_jZIhDKI.js.map +0 -1
- package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
- package/dist/web-socket-CV7yIMnm.js.map +0 -1
- package/dist/web-vitals-Bq4WFHQo.js +0 -52
- package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
- package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
- package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
- package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
- package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
- package/dist/worker-server-BrIYkfoa.cjs +0 -2
- package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
- package/dist/worker-transport-Bwej4N2e.cjs +0 -2
- package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
- package/dist/worker-transport-D6jtgpqN.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs"),t=require("./batch-D5LlU4Q9.cjs"),n=require("./factory-DLFDjdLv.cjs");function r(e){return e.error??Error(`The IndexedDB request failed.`)}function i(e){return new Promise((t,n)=>{e.onsuccess=()=>{t(e.result)},e.onerror=()=>{n(r(e))}})}var a=class{name;connection=null;constructor(e){this.name=e}async put(e){await i((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 i(n.index(`routingContext`).getAll(r,t))}async countContext(e){return i((await this.store(`readonly`)).index(`routingContext`).count(IDBKeyRange.bound([e,0],[e,2**53-1])))}async takeOldest(t){return i((await this.store(`readonly`)).index(e.ht).getAll(null,t))}async walkOldest(t){let n=(await this.store(`readonly`)).index(e.ht).openCursor();await new Promise((e,i)=>{n.onsuccess=()=>{let r=n.result;r===null||!t(r.value)?e():r.continue()},n.onerror=()=>{i(r(n))}})}async takeBefore(t){let n=await this.store(`readonly`),r=IDBKeyRange.upperBound(t,!0);return i(n.index(e.ht).getAll(r))}async delete(e){await i((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>i(t.delete(e))))}async bumpAttempts(e,t){let n=await this.store(`readwrite`),r=await i(n.get(e));r!==void 0&&await i(n.put({...r,attempts:t}))}async count(){return i((await this.store(`readonly`)).count())}async clear(){await i((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.gt,t).objectStore(e.gt)}open(){let t=this.connection;if(t!==null)return t;let n=new Promise((t,n)=>{let i=indexedDB.open(this.name,12),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.gt,{keyPath:`id`}).createIndex(e.ht,e.ht);let n=i.transaction.objectStore(e.gt);n.indexNames.contains(`routingContext`)||n.createIndex(`routingContext`,[`routingContextId`,`createdAt`])},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},t(e))},i.onerror=()=>{n(r(i))},i.onblocked=()=>{a=!0,n(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=n.catch(e=>{throw this.connection=null,e}),this.connection}},o=class{limits;diagnostics;onGap;name=e.Ln;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new a(e)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e),await this.prune()}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.n(this.diagnostics,this.onGap,i,r)}if(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))!==!0){let t={batches:1,records:e.records.length,reason:`quota`};n.n(this.diagnostics,this.onGap,t,[e])}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])}}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 e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),this.addGap(e,`expired`,n));let r=await this.db.count();if(r>this.limits.maxBatches){let t=await this.evictOldest(r-this.limits.maxBatches);this.addGap(e,`over_capacity`,t)}}),e}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.t(e,r,i.length,t.n(i));n.n(this.diagnostics,this.onGap,a,i)}async evictOldest(e){let t=new n.r(e,n.i);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=o;
|
|
2
|
+
//# sourceMappingURL=indexeddb-storage-CtLvZH1r.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-CtLvZH1r.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","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","evicted","records","gap","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 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/** 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 */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\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;\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 }\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: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\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 }\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 }\n },\n );\n\n return result;\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,kHAoBA,SAASU,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,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAAC,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,OAAOT,GACL,MAFkB,KAAK,MAAM,UAAU,EAAA,CAGpC,MAAM,gBAAgB,CAAC,CACvB,MAAM,YAAY,MAAM,CAACQ,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,CAAC,CACpE,CACF,CAOA,MAAM,WAAW,EAAoC,CAEnD,OAAOR,GAAsB,MADT,KAAK,MAAM,UAAU,EAAA,CACN,MAAMZ,EAAAA,EAA0B,CAAC,CAAC,OAAO,KAAMqB,CAAK,CAAC,CAC1F,C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AAQ,gBAAiBJ,CAAO,CAC9C,CACF,CACF,EAEOI,CACT,CAMA,MAAM,OAAyB,CAM7B,OAAO,MALa,KAAK,YAAY,WACnC,mBACA,sDACM,KAAK,GAAG,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,IAAMF,EAAMpC,EAAAA,EAAQsC,EAAQG,EAAQC,EAAQ,OAAQ3C,EAAAA,EAAa2C,CAAO,CAAC,EACzErC,EAAA,EAAe,KAAK,YAAa,KAAK,MAAO+B,EAAKM,CAAO,CAC3D,CASA,MAAc,YAAY,EAAsC,CAE9D,IAAMC,EAAO,IAAI1C,EAAAA,EAAa2C,EAAS1C,EAAAA,CAAS,EAChD,MAAM,KAAK,GAAG,WAAY,GAAUyC,EAAK,IAAI9B,CAAK,CAAC,EAEnD,IAAMgC,EAASF,EAAK,OAAO,EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWE,EAAO,IAAK,GAAUhC,EAAM,EAAE,CAAC,EAEjDgC,CACT,CACF,E"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as r } from "./batch-
|
|
3
|
-
import { i, n as a, r as o, t as s } from "./factory-
|
|
1
|
+
import { Ln as e, gt as t, ht as n } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
import { n as r } from "./batch-BjQUwjA6.js";
|
|
3
|
+
import { i, n as a, r as o, t as s } from "./factory-e9Qo3K0z.js";
|
|
4
4
|
// src/storage/idb-driver.ts
|
|
5
5
|
function c(e) {
|
|
6
6
|
return e.error ?? /* @__PURE__ */ Error("The IndexedDB request failed.");
|
|
@@ -200,4 +200,4 @@ var u = class {
|
|
|
200
200
|
};
|
|
201
201
|
export { d as IndexedDbStorage };
|
|
202
202
|
|
|
203
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
203
|
+
//# sourceMappingURL=indexeddb-storage-DLXQzAGh.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-DLXQzAGh.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","countRecords","reportEviction","EvictionPick","addDrop","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","evicted","records","gap","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 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/** 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 */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\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;\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 }\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: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\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 }\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 }\n },\n );\n\n return result;\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,SAASO,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;CAOQ;CAL7B,aAAkD;CAKlD,YAAY,GAA+B;EAAd,KAAA,OAAAC;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,CA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import "./constants-
|
|
1
|
+
import "./constants-Bwl_YtQi.js";
|
|
2
2
|
import { t as e } from "./patch-UdPz1ea8.js";
|
|
3
|
-
import { i as t } from "./platform-
|
|
3
|
+
import { i as t } from "./platform-CVewe4wQ.js";
|
|
4
4
|
// src/capture/interactions.ts
|
|
5
5
|
var n = "a[target=\"_blank\"], a[download]";
|
|
6
6
|
function r(e) {
|
|
@@ -116,4 +116,4 @@ var a = class {
|
|
|
116
116
|
};
|
|
117
117
|
export { a as InteractionCapture };
|
|
118
118
|
|
|
119
|
-
//# sourceMappingURL=interactions-
|
|
119
|
+
//# sourceMappingURL=interactions-B6z2I4tU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-B6z2I4tU.js","names":["patch","recordedUrl","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","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_MS,\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 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/**\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 /**\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 }\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\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates the trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\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) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\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 this.watchDead(message, options);\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 after a click on a control. If there's no DOM change, navigation or scroll\n * within `deadClickMs`, it records `ui.dead_click`. Only one check runs at a time.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\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 removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && 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 /** 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) return;\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 }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AAgBiB;CACvB;CAGA,mBAA0C;EACxC,IAAME,IAAO,KAAK,SACZC,IAAK,SAAS;EAKpB,IAJID,MAASC,MAGb,KAAK,UAAUA,GACX,KAAK,IAAI,WAAW,MAAM,KAAO;EAIrC,IAAMC,IAAO,KAAK,IAAI,OAAO,QAAQ,UAC/B,EAAE,oBAAiB,KAAK,IAAI,OAAO,SACnCC,IAAUrC,EAAYkC,GAAME,GAAME,GAAc,KAAK,IAAI,WAAW,GACpEC,IAAQvC,EAAYmC,GAAIC,GAAME,GAAc,KAAK,IAAI,WAAW;EAYtE,AAVA,KAAK,IAAI,QAAQ,OAAO,YAAY,GACpC,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,GAAGD,EAAQ,MAAME;EAC5B,CAAC,GAKD,KAAK,IAAI,OAAO,SAAS,cAAc,EAAE,qBAAqBF,EAAQ,CAAC;CACzE;CAGA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,KACrB;EAKF,IAAMzB,IAASJ,EAAe,GACxBgC,IAAa,KAAK,YAEpBC,IAAS,IAEPC,IAAmB3C,EACvBa,GACA,cACC,MACC,SAAyB,GAAG+B,GAAqB;GAI/C,AAHAC,EAAS,MAAM,MAAMD,CAAI,GAGrBF,KACF,eAAeD,CAAU;EAE7B,CACJ,GAEMK,IAAsB9C,EAC1Ba,GACA,iBACC,MACC,SAAyB,GAAG+B,GAAqB;GAE/C,AADAC,EAAS,MAAM,MAAMD,CAAI,GACrBF,KACF,eAAeD,CAAU;EAE7B,CACJ;EAEA,KAAK,SAAS,WAAW;GAGvB,AAFA,IAAS,IACTE,EAAiB,GACjBG,EAAoB;EACtB,CAAC;CACH;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require("./constants-
|
|
2
|
-
//# sourceMappingURL=interactions-
|
|
1
|
+
require("./constants-DakMxVB2.cjs");const e=require("./patch-BX8KrPCT.cjs"),t=require("./platform-12uR7kBQ.cjs");var n=`a[target="_blank"], a[download]`;function r(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 i(){return history}var a=class{ctx;name=`interactions`;installed=!1;restores=[];lastUrl=``;burst={target:null,times:[],reported:!1};stopDeadCheck;constructor(e){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.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.stopDeadCheck?.(),this.burst={target:null,times:[],reported:!1}}}onClick=e=>{if(this.ctx.isActive?.()===!1)return;let t=e.target;if(!(t instanceof Element))return;let i=this.ctx.config.capture.interactions,a=typeof i==`object`?i:{},o=a.ignoreSelector===void 0?`[data-observability-ignore]`:a.ignoreSelector;if(o&&t.closest(o))return;let s=a.actionAttribute??`data-observability-action`,c=((t.closest(`[${s}]`)?.getAttribute(s)??``)||`unknown-click`).slice(0,this.ctx.config.limits.maxBodyChars),l={};a.selector&&(l.selector=r(t)),a.text&&(l.text=t.textContent.trim().slice(0,a.maxTextChars??50)),this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:c,data:Object.keys(l).length>0?l:void 0}),a.rageClicks&&this.countRage(t,c,a),a.deadClicks&&t.closest(`a, button, summary, input[type="button"], input[type="submit"], input[type="reset"], [role="button"], [role="link"], [role="menuitem"], [role="tab"], [${s}]`)&&!t.closest(n)&&this.watchDead(c,a)};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){if(this.stopDeadCheck||typeof MutationObserver>`u`)return;let n=location.href,r=!1,i=()=>{r=!0},a=new MutationObserver(i);a.observe(document,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),addEventListener(`scroll`,i,{capture:!0,passive:!0});let o=()=>{clearTimeout(s),a.disconnect(),removeEventListener(`scroll`,i,!0),this.stopDeadCheck=void 0},s=setTimeout(()=>{o(),!r&&location.href===n&&this.ctx.isActive?.()!==!1&&this.ctx.logger.logEvent(`ui.dead_click`,{"click.action":e})},t.deadClickMs??1e3);this.stopDeadCheck=o}onNavigate=()=>{let e=this.lastUrl,n=location.href;if(e===n||(this.lastUrl=n,this.ctx.isActive?.()===!1))return;let r=this.ctx.config.capture.fullUrls,{urlTransform:i}=this.ctx.config.capture,a=t.i(e,r,i,this.ctx.diagnostics),o=t.i(n,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})};installHistory(){if(typeof history>`u`)return;let t=i(),n=this.onNavigate,r=!0,a=e.t(t,`pushState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)}),o=e.t(t,`replaceState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)});this.restores.push(()=>{r=!1,a(),o()})}};exports.InteractionCapture=a;
|
|
2
|
+
//# sourceMappingURL=interactions-P6pz08Jn.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions-P6pz08Jn.cjs","names":["recordedUrl","patch","require_patch","require_platform","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","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_MS,\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 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/**\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 /**\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 }\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\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates the trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\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) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\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 this.watchDead(message, options);\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 after a click on a control. If there's no DOM change, navigation or scroll\n * within `deadClickMs`, it records `ui.dead_click`. Only one check runs at a time.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\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 removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && 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 /** 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) return;\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,iHAqBA,IAAMI,EAAgB,kCAQtB,SAASC,EAAgB,EAA0B,CACjD,IAAMC,EAAMC,EAAQ,QAAQ,YAAY,EAElCC,EAASD,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIC,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAID,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAME,EAAQF,EAAQ,aAAa,YAAY,EAC/C,GAAIE,IAAU,KACZ,MAAO,GAAGH,EAAI,eAAeG,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBH,EAAQ,aAAa,OAAO,CAAC,EAAE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GAC5B,CAAC,EAKD,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBF,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,IACrB,OAKF,IAAMzB,EAASJ,EAAe,EACxBgC,EAAa,KAAK,WAEpBC,EAAS,GAEPC,EAAmB5C,EAAAA,EACvBc,EACA,YACC,GACC,SAAyB,GAAG+B,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EAGrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEMK,EAAsB/C,EAAAA,EAC1Bc,EACA,eACC,GACC,SAAyB,GAAG+B,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EACrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEA,KAAK,SAAS,SAAW,CACvB,EAAS,GACTE,EAAiB,EACjBG,EAAoB,CACtB,CAAC,CACH,CACF,E"}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { Bt as e, C as t,
|
|
2
|
-
import { n as d
|
|
3
|
-
import { i as
|
|
4
|
-
import { t as
|
|
1
|
+
import { Bt as e, C as t, Ct as n, S as r, St as i, T as a, Vt as o, bt as s, w as c, x as l, xt as u } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
import { n as d } from "./deadline-C4ccAuk5.js";
|
|
3
|
+
import { i as f, t as p } from "./identity-BrQp_5J5.js";
|
|
4
|
+
import { t as m } from "./openfin-Bxelt0yg.js";
|
|
5
|
+
import { t as h } from "./unref-DgHPQeWv.js";
|
|
5
6
|
// src/core/journey.ts
|
|
6
7
|
var g = {
|
|
7
|
-
maxAgeMs:
|
|
8
|
+
maxAgeMs: u,
|
|
8
9
|
endOnOwnerClose: !1,
|
|
9
|
-
urlParam:
|
|
10
|
+
urlParam: n
|
|
10
11
|
};
|
|
11
12
|
function _(e, t) {
|
|
12
13
|
let n = Reflect.get(e, t);
|
|
@@ -43,9 +44,9 @@ function x(e) {
|
|
|
43
44
|
i: e.id,
|
|
44
45
|
n: e.name.slice(0, 64),
|
|
45
46
|
s: e.startedAt
|
|
46
|
-
}), r = new TextEncoder().encode(n),
|
|
47
|
-
for (let e of r)
|
|
48
|
-
return btoa(
|
|
47
|
+
}), r = new TextEncoder().encode(n), i = "";
|
|
48
|
+
for (let e of r) i += String.fromCharCode(e);
|
|
49
|
+
return btoa(i).replace(c, "-").replace(a, "_").replace(t, "");
|
|
49
50
|
}
|
|
50
51
|
var S = class {
|
|
51
52
|
options;
|
|
@@ -55,7 +56,7 @@ var S = class {
|
|
|
55
56
|
stores;
|
|
56
57
|
journey = null;
|
|
57
58
|
expiryTimer = null;
|
|
58
|
-
constructor(e, t, n, r, i =
|
|
59
|
+
constructor(e, t, n, r, i = p) {
|
|
59
60
|
this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r, this.stores = i;
|
|
60
61
|
}
|
|
61
62
|
current() {
|
|
@@ -67,7 +68,7 @@ var S = class {
|
|
|
67
68
|
this.removeUrlToken();
|
|
68
69
|
return;
|
|
69
70
|
}
|
|
70
|
-
let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(
|
|
71
|
+
let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(i));
|
|
71
72
|
if (t && this.restore(t)) return;
|
|
72
73
|
let n = await this.readOpenFinToken();
|
|
73
74
|
n !== null && this.adopt(n, "openfin.customData");
|
|
@@ -83,7 +84,7 @@ var S = class {
|
|
|
83
84
|
return this.setJourney(n), this.onLocalChange(n), n;
|
|
84
85
|
}
|
|
85
86
|
journeyId(e) {
|
|
86
|
-
return e === void 0 ?
|
|
87
|
+
return e === void 0 ? f(this.diagnostics) : typeof e == "string" && s.test(e) ? e : (this.diagnostics.report("config.invalid", "startJourney() needs an id of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id."), f(this.diagnostics));
|
|
87
88
|
}
|
|
88
89
|
end() {
|
|
89
90
|
this.journey !== null && (this.setJourney(null), this.onLocalChange(null));
|
|
@@ -124,22 +125,22 @@ var S = class {
|
|
|
124
125
|
}
|
|
125
126
|
decodeToken(e) {
|
|
126
127
|
return this.diagnostics.guard("config.invalid", "The library could not decode a seeded journey token.", () => {
|
|
127
|
-
let t = e.replace(
|
|
128
|
+
let t = e.replace(l, "+").replace(r, "/"), n = (4 - t.length % 4) % 4, i = "=".repeat(n), a = Uint8Array.from(atob(t + i), (e) => e.charCodeAt(0));
|
|
128
129
|
return b(JSON.parse(new TextDecoder().decode(a)));
|
|
129
130
|
}) ?? null;
|
|
130
131
|
}
|
|
131
132
|
setJourney(e) {
|
|
132
133
|
if (this.journey = e, this.clearTimer(), this.diagnostics.guard("storage.unavailable", "The library could not save the journey.", () => {
|
|
133
|
-
e === null ? this.stores.session().removeItem(
|
|
134
|
+
e === null ? this.stores.session().removeItem(i) : this.stores.session().setItem(i, JSON.stringify(e));
|
|
134
135
|
}), e === null) return;
|
|
135
136
|
let t = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), n = setTimeout(() => {
|
|
136
137
|
this.diagnostics.report("journey.expired", `The journey "${e.name}" reached maxAgeMs. The library ended it.`, { journeyId: e.id }), this.journey = null, this.expiryTimer = null, this.clearStored();
|
|
137
138
|
}, t);
|
|
138
|
-
this.expiryTimer = n,
|
|
139
|
+
this.expiryTimer = n, h(n);
|
|
139
140
|
}
|
|
140
141
|
clearStored() {
|
|
141
142
|
this.diagnostics.guard("storage.unavailable", "The library could not clear the persisted journey.", () => {
|
|
142
|
-
this.stores.session().removeItem(
|
|
143
|
+
this.stores.session().removeItem(i);
|
|
143
144
|
});
|
|
144
145
|
}
|
|
145
146
|
clearTimer() {
|
|
@@ -155,12 +156,12 @@ var S = class {
|
|
|
155
156
|
});
|
|
156
157
|
}
|
|
157
158
|
async readOpenFinToken() {
|
|
158
|
-
let t =
|
|
159
|
+
let t = m()?.me, n = t?.getOptions;
|
|
159
160
|
if (n === void 0) return null;
|
|
160
|
-
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => d(n.call(t),
|
|
161
|
+
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => d(n.call(t), o)))?.customData?.[e];
|
|
161
162
|
return typeof r == "string" ? r : null;
|
|
162
163
|
}
|
|
163
164
|
};
|
|
164
165
|
export { S as n, y as r, g as t };
|
|
165
166
|
|
|
166
|
-
//# sourceMappingURL=journey-
|
|
167
|
+
//# sourceMappingURL=journey-35yCMNFo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journey-35yCMNFo.js","names":["OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PADDING_PATTERN","JOURNEY_URL_PARAM","BASE64URL_UNDERSCORE_PATTERN","JOURNEY_STORAGE_KEY","BASE64_SLASH_PATTERN","OPENFIN_OPTIONS_TIMEOUT_MS","JOURNEY_ID_PATTERN","BASE64_PLUS_PATTERN","BASE64URL_DASH_PATTERN","JOURNEY_MAX_AGE_MS","withDeadline","newId","BROWSER_STORES","getFin","unrefTimer","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","future","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","requested","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// Manages a user journey's lifecycle across windows: encodes tokens, stores the journey and\n// ends it at expiry. Never trust a value from storage or a token, because any code on the\n// origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_CLOCK_SKEW_MS,\n JOURNEY_ID_MAX_CHARS,\n JOURNEY_ID_PATTERN,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { getFin } from \"../utils/openfin\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey, which is one user task spanning several contexts. */\nexport interface JourneyOptions {\n /** Maximum time a journey stays open, in milliseconds. After that the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** The journey lifetime policy in effect. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Human-readable name of the journey's workflow. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Parent journey ID, set when the journey branches from an earlier one. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from another realm's bus message.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates a decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n const startedAt = readNumber(value, \"s\");\n // We always write a start time. A token without one, or with one from the future, would\n // never expire.\n const future = startedAt !== undefined && startedAt > Date.now() + JOURNEY_CLOCK_SKEW_MS;\n if (id === undefined || name === undefined || startedAt === undefined || future) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa, which throws above U+00FF.\n // Without this step, a name in a non-Latin script would fail.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. Checks the URL query first, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey, replacing the active one and telling connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: this.journeyId(opts.id),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /**\n * Picks the id for a new journey. A longer id, or one with multibyte characters, would make\n * the journey token too long for adoptJourney().\n * @param requested Id from the app, or undefined.\n * @returns The requested id when it matches JOURNEY_ID_PATTERN, otherwise a new id.\n */\n private journeyId(requested: unknown): string {\n if (requested === undefined) {\n return newId(this.diagnostics);\n }\n\n if (typeof requested === \"string\" && JOURNEY_ID_PATTERN.test(requested)) {\n return requested;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `startJourney() needs an id of 1 to ${String(JOURNEY_ID_MAX_CHARS)} letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id.`,\n );\n return newId(this.diagnostics);\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer without broadcasting it again. An echo would\n * make two windows send the change back and forth forever. A journey with the same ID as\n * the active one is ignored, so an echo can't restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token, and every step throws on bad input. The guard reports the failure\n * instead of letting it throw.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar once the engine has adopted it.\n * Otherwise a copied or bookmarked link would start the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state, because a router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from customData in the OpenFin window options. The wait is\n * capped by OPENFIN_OPTIONS_TIMEOUT_MS. At the deadline we report openfin.unavailable and\n * return no token. A window with no token gives the same result.\n * @returns Promise that resolves to the token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = getFin()?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call so the native OpenFin method keeps its receiver. A detached copy throws when\n // called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;;;;AA0CA,IAAagB,IAAkC;CAC7C,UAAUN;CACV,iBAAA;CACA,UAAUR;AACZ;AAsBA,SAASe,EAAW,GAAgB,GAAiC;CACnE,IAAMC,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAYA,MAAU,KAAKA,IAAQ,KAAA;AAC7D;AAQA,SAASG,EAAW,GAAgB,GAAiC;CACnE,IAAMH,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAY,O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GAC7B,KAAK,cAAc;CAEvB;CAMA,eAAsC;EAWpC,OAVc,KAAK,YAAY,MAC7B,kBACA,oEAEM,OAAO,WAAa,MACf,OAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,KAAS;CAClB;CAMA,iBAA+B;EAC7B,KAAK,YAAY,MACf,wBACA,sEACM;GACJ,IAAMqD,IAAM,IAAI,IAAI,SAAS,IAAI;GAGjC,AAFAA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,GAE7C,QAAQ,aAAa,QAAQ,OAAO,IAAIA,EAAI,IAAI;EAClD,CACF;CACF;CAQA,MAAc,mBAA2C;EACvD,IAAMC,IAAK5C,EAAO,CAAC,EAAE,IACf6C,IAAaD,GAAI;EACvB,IAAIC,MAAe,KAAA,GACjB,OAAO;EAUT,IAAMb,KAAQ,MALQ,KAAK,YAAY,WACrC,uBACA,yDACMnC,EAAagD,EAAW,KAAKD,CAAE,GAAGpD,CAA0B,CACpE,EAAA,EACuB,aAAaN;EACpC,OAAO,OAAO8C,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs"),t=require("./deadline-CUGbto-y.cjs"),n=require("./identity-BlvlgjrU.cjs"),r=require("./openfin-DtH2f7zX.cjs"),i=require("./unref-CU9Nyz_9.cjs");var a={maxAgeMs:e.xt,endOnOwnerClose:!1,urlParam:e.Ct};function o(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function s(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function c(e){if(typeof e!=`object`||!e)return null;let t=o(e,`id`),n=o(e,`name`),r=s(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:o(e,`parentId`),ownerContextId:o(e,`ownerContextId`)??``}}function l(e){if(typeof e!=`object`||!e)return null;let t=o(e,`i`),n=o(e,`n`),r=s(e,`s`),i=r!==void 0&&r>Date.now()+3e5;return t===void 0||n===void 0||r===void 0||i?null:{id:t,name:n,startedAt:r,parentId:void 0,ownerContextId:``}}function u(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.w,`-`).replace(e.T,`_`).replace(e.C,``)}var d=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,t,r,i,a=n.t){this.options=e,this.diagnostics=t,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`)){this.removeUrlToken();return}let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.St));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,t={}){let n={id:this.journeyId(t.id),name:e,startedAt:Date.now(),parentId:t.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(n),this.onLocalChange(n),n}journeyId(t){return t===void 0?n.i(this.diagnostics):typeof t==`string`&&e.bt.test(t)?t:(this.diagnostics.report(`config.invalid`,`startJourney() needs an id of 1 to 64 letters, digits, "_", ".", ":" or "-". The library uses a new id.`),n.i(this.diagnostics))}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=u(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=c(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.x,`+`).replace(e.S,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return l(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.St):this.stores.session().setItem(e.St,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=r,i.t(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.St)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}removeUrlToken(){this.diagnostics.guard(`platform.api_blocked`,`The library could not remove the journey token from the URL.`,()=>{let e=new URL(location.href);e.searchParams.delete(this.options.urlParam),history.replaceState(history.state,``,e.href)})}async readOpenFinToken(){let n=r.t()?.me,i=n?.getOptions;if(i===void 0)return null;let a=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.n(i.call(n),e.Vt)))?.customData?.[e.Bt];return typeof a==`string`?a:null}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
|
|
2
|
+
//# sourceMappingURL=journey-DAGh5h9k.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journey-DAGh5h9k.cjs","names":["JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","JOURNEY_ID_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","getFin","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","require_constants","require_deadline","require_identity","require_openfin","require_unref","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","future","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","requested","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// Manages a user journey's lifecycle across windows: encodes tokens, stores the journey and\n// ends it at expiry. Never trust a value from storage or a token, because any code on the\n// origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_CLOCK_SKEW_MS,\n JOURNEY_ID_MAX_CHARS,\n JOURNEY_ID_PATTERN,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { getFin } from \"../utils/openfin\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey, which is one user task spanning several contexts. */\nexport interface JourneyOptions {\n /** Maximum time a journey stays open, in milliseconds. After that the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** The journey lifetime policy in effect. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Human-readable name of the journey's workflow. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Parent journey ID, set when the journey branches from an earlier one. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from another realm's bus message.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates a decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n const startedAt = readNumber(value, \"s\");\n // We always write a start time. A token without one, or with one from the future, would\n // never expire.\n const future = startedAt !== undefined && startedAt > Date.now() + JOURNEY_CLOCK_SKEW_MS;\n if (id === undefined || name === undefined || startedAt === undefined || future) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa, which throws above U+00FF.\n // Without this step, a name in a non-Latin script would fail.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. Checks the URL query first, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey, replacing the active one and telling connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: this.journeyId(opts.id),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /**\n * Picks the id for a new journey. A longer id, or one with multibyte characters, would make\n * the journey token too long for adoptJourney().\n * @param requested Id from the app, or undefined.\n * @returns The requested id when it matches JOURNEY_ID_PATTERN, otherwise a new id.\n */\n private journeyId(requested: unknown): string {\n if (requested === undefined) {\n return newId(this.diagnostics);\n }\n\n if (typeof requested === \"string\" && JOURNEY_ID_PATTERN.test(requested)) {\n return requested;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `startJourney() needs an id of 1 to ${String(JOURNEY_ID_MAX_CHARS)} letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id.`,\n );\n return newId(this.diagnostics);\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer without broadcasting it again. An echo would\n * make two windows send the change back and forth forever. A journey with the same ID as\n * the active one is ignored, so an echo can't restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token, and every step throws on bad input. The guard reports the failure\n * instead of letting it throw.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar once the engine has adopted it.\n * Otherwise a copied or bookmarked link would start the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state, because a router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from customData in the OpenFin window options. The wait is\n * capped by OPENFIN_OPTIONS_TIMEOUT_MS. At the deadline we report openfin.unavailable and\n * return no token. A window with no token gives the same result.\n * @returns Promise that resolves to the token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = getFin()?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call so the native OpenFin method keeps its receiver. A detached copy throws when\n // called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":"A,4LA0CA,IAAaoB,EAAkC,CAC7C,SAAUpB,EAAAA,GACV,gBAAA,GACA,SAAUC,EAAAA,EACZ,EAsBA,SAASoB,EAAW,EAAgB,EAAiC,CACnE,IAAMC,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAYA,IAAU,GAAKA,EAAQ,IAAA,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AK,YAAY,MACf,sBACA,yDACM,CACJ,KAAK,OAAO,QAAQ,CAAC,CAAC,WAAWtD,EAAAA,EAAmB,CACtD,CACF,CACF,CAGA,YAA2B,CACrB,KAAK,cAAgB,OACvB,aAAa,KAAK,WAAW,EAC7B,KAAK,YAAc,KAEvB,CAMA,cAAsC,CAWpC,OAVc,KAAK,YAAY,MAC7B,iBACA,iEAEM,OAAO,SAAa,IACf,KAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,GAAS,IAClB,CAMA,gBAA+B,CAC7B,KAAK,YAAY,MACf,uBACA,mEACM,CACJ,IAAMuD,EAAM,IAAI,IAAI,SAAS,IAAI,EACjCA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,EAE7C,QAAQ,aAAa,QAAQ,MAAO,GAAIA,EAAI,IAAI,CAClD,CACF,CACF,CAQA,MAAc,kBAA2C,CACvD,IAAMC,EAAKnD,EAAAA,EAAO,CAAC,EAAE,GACfoD,EAAaD,GAAI,WACvB,GAAIC,IAAe,IAAA,GACjB,OAAO,KAUT,IAAMb,GAAQ,MALQ,KAAK,YAAY,WACrC,sBACA,sDACMtC,EAAAA,EAAamD,EAAW,KAAKD,CAAE,EAAGjD,EAAAA,EAA0B,CACpE,EAAA,EACuB,aAAaC,EAAAA,IACpC,OAAO,OAAOoC,GAAU,SAAWA,EAAQ,IAC7C,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys-BHhw_0Wh.cjs","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n//
|
|
1
|
+
{"version":3,"file":"keys-BHhw_0Wh.cjs","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n// Builds a batch's localStorage key and returns the sorted keys that start with a prefix.\n// A sandboxed frame and private mode throw on first access instead of returning null.\n\nimport { BATCH_KEY_TIME_WIDTH } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Formats a storage key with a zero-padded creation time, so the keys sort in FIFO order.\n * Always use batch.createdAt, never Date.now(), or the key won't match the written one.\n * @param prefix Storage key prefix.\n * @param batch The target log batch.\n * @returns The prefixed, timestamp-ordered storage key.\n */\nexport function batchKey(prefix: string, batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${prefix}${at}.${batch.id}`;\n}\n\n/**\n * Returns every localStorage key that starts with the prefix, sorted.\n * @param prefix The storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns The matching storage keys, sorted.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) is typed string | null, but it can't be null below length. A\n // null check here would add a branch that no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n },\n );\n\n return out.sort();\n}\n"],"mappings":"AAgBA,SAAgBA,EAAS,EAAgB,EAAyB,CAEhE,MAAO,GAAGC,IADC,OAAOC,EAAM,SAAS,CAAC,CAAC,SAAA,GAA+B,GAC/C,EAAG,GAAGA,EAAM,IACjC,CAQA,SAAgBC,EAAe,EAAgB,EAAoC,CACjF,IAAMC,EAAgB,CAAC,EAiBvB,OAfAC,EAAY,MACV,sBACA,wDACM,CACJ,IAAK,IAAIC,EAAI,EAAGA,EAAI,aAAa,OAAQ,IAAK,CAG5C,IAAMC,EAAM,OAAO,aAAa,IAAID,CAAC,CAAC,EAClCC,EAAI,WAAWN,CAAM,GACvBG,EAAI,KAAKG,CAAG,CAEhB,CACF,CACF,EAEOH,EAAI,KAAK,CAClB,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys-BU9j5YqW.js","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n//
|
|
1
|
+
{"version":3,"file":"keys-BU9j5YqW.js","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n// Builds a batch's localStorage key and returns the sorted keys that start with a prefix.\n// A sandboxed frame and private mode throw on first access instead of returning null.\n\nimport { BATCH_KEY_TIME_WIDTH } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Formats a storage key with a zero-padded creation time, so the keys sort in FIFO order.\n * Always use batch.createdAt, never Date.now(), or the key won't match the written one.\n * @param prefix Storage key prefix.\n * @param batch The target log batch.\n * @returns The prefixed, timestamp-ordered storage key.\n */\nexport function batchKey(prefix: string, batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${prefix}${at}.${batch.id}`;\n}\n\n/**\n * Returns every localStorage key that starts with the prefix, sorted.\n * @param prefix The storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns The matching storage keys, sorted.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) is typed string | null, but it can't be null below length. A\n // null check here would add a branch that no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n },\n );\n\n return out.sort();\n}\n"],"mappings":";AAgBA,SAAgBA,EAAS,GAAgB,GAAyB;CAEhE,OAAO,GAAGC,IADC,OAAOC,EAAM,SAAS,CAAC,CAAC,SAAA,IAA+B,GAC/C,EAAG,GAAGA,EAAM;AACjC;AAQA,SAAgBC,EAAe,GAAgB,GAAoC;CACjF,IAAMC,IAAgB,CAAC;CAiBvB,OAfAC,EAAY,MACV,uBACA,2DACM;EACJ,KAAK,IAAIC,IAAI,GAAGA,IAAI,aAAa,QAAQ,KAAK;GAG5C,IAAMC,IAAM,OAAO,aAAa,IAAID,CAAC,CAAC;GACtC,AAAIC,EAAI,WAAWN,CAAM,KACvBG,EAAI,KAAKG,CAAG;EAEhB;CACF,CACF,GAEOH,EAAI,KAAK;AAClB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=library-console-
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.Et);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
|
|
2
|
+
//# sourceMappingURL=library-console-BFWEuQsl.cjs.map
|