@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.
Files changed (383) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +273 -102
  3. package/bin/uiobs.mjs +1 -1
  4. package/dist/{batch-CL9uWYY3.js → batch-BjQUwjA6.js} +4 -4
  5. package/dist/batch-BjQUwjA6.js.map +1 -0
  6. package/dist/{batch-C8OcWR2L.cjs → batch-D5LlU4Q9.cjs} +2 -2
  7. package/dist/batch-D5LlU4Q9.cjs.map +1 -0
  8. package/dist/bus/bus.d.ts +48 -47
  9. package/dist/bus/links.d.ts +4 -4
  10. package/dist/bus/validation.d.ts +1 -1
  11. package/dist/bus-D_7pd7RN.cjs +2 -0
  12. package/dist/bus-D_7pd7RN.cjs.map +1 -0
  13. package/dist/{bus-BZ0GldpT.js → bus-ecxUNTja.js} +91 -91
  14. package/dist/bus-ecxUNTja.js.map +1 -0
  15. package/dist/capture/console.d.ts +10 -10
  16. package/dist/capture/errors.d.ts +6 -6
  17. package/dist/capture/interactions.d.ts +14 -14
  18. package/dist/capture/lifecycle.d.ts +3 -3
  19. package/dist/capture/long-frames.d.ts +6 -6
  20. package/dist/capture/network.d.ts +17 -17
  21. package/dist/capture/profiler-frames.d.ts +44 -0
  22. package/dist/capture/replay-buffer.d.ts +46 -0
  23. package/dist/capture/replay-upload.d.ts +74 -0
  24. package/dist/capture/replay.d.ts +114 -0
  25. package/dist/capture/reports.d.ts +2 -2
  26. package/dist/capture/resource-timing.d.ts +1 -1
  27. package/dist/capture/server-timing.d.ts +3 -3
  28. package/dist/capture/storm.d.ts +3 -3
  29. package/dist/capture/types.d.ts +45 -33
  30. package/dist/capture/unclean-exit.d.ts +8 -8
  31. package/dist/capture/user-timing.d.ts +3 -3
  32. package/dist/capture/web-socket.d.ts +11 -11
  33. package/dist/capture/web-vitals.d.ts +20 -7
  34. package/dist/compression-AJJCMBOa.js +11 -0
  35. package/dist/compression-AJJCMBOa.js.map +1 -0
  36. package/dist/compression-lD9abCcO.cjs +2 -0
  37. package/dist/compression-lD9abCcO.cjs.map +1 -0
  38. package/dist/{console-BPZCuSLc.cjs → console-CLz_PvFn.cjs} +2 -2
  39. package/dist/console-CLz_PvFn.cjs.map +1 -0
  40. package/dist/{console-BeCF7n59.js → console-cwgHKXvM.js} +4 -4
  41. package/dist/console-cwgHKXvM.js.map +1 -0
  42. package/dist/constants-Bwl_YtQi.js +349 -0
  43. package/dist/constants-Bwl_YtQi.js.map +1 -0
  44. package/dist/constants-DakMxVB2.cjs +2 -0
  45. package/dist/constants-DakMxVB2.cjs.map +1 -0
  46. package/dist/constants.d.ts +150 -103
  47. package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
  48. package/dist/context-storage-BzkoHzkQ.js.map +1 -1
  49. package/dist/core/breadcrumbs.d.ts +16 -15
  50. package/dist/core/config.d.ts +3 -3
  51. package/dist/core/context.d.ts +7 -7
  52. package/dist/core/debug-buffer.d.ts +10 -10
  53. package/dist/core/debug-bundle.d.ts +3 -3
  54. package/dist/core/deferred.d.ts +2 -2
  55. package/dist/core/diagnostics.d.ts +24 -21
  56. package/dist/core/drops.d.ts +7 -7
  57. package/dist/core/hold-buffer.d.ts +1 -1
  58. package/dist/core/journey.d.ts +22 -23
  59. package/dist/core/logger.d.ts +22 -21
  60. package/dist/core/measure.d.ts +7 -7
  61. package/dist/core/meter.d.ts +25 -21
  62. package/dist/core/pipeline.d.ts +42 -41
  63. package/dist/core/profile-buckets.d.ts +31 -0
  64. package/dist/core/profiler.d.ts +218 -0
  65. package/dist/core/record.d.ts +23 -23
  66. package/dist/core/remote-rules.d.ts +4 -4
  67. package/dist/core/remote-sampling.d.ts +21 -20
  68. package/dist/core/runtime.d.ts +206 -137
  69. package/dist/core/sampling.d.ts +18 -18
  70. package/dist/core/sender.d.ts +22 -20
  71. package/dist/core/spans.d.ts +5 -5
  72. package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
  73. package/dist/deadline-C4ccAuk5.js.map +1 -0
  74. package/dist/deadline-CUGbto-y.cjs +2 -0
  75. package/dist/deadline-CUGbto-y.cjs.map +1 -0
  76. package/dist/{debug-bundle-C7UkHZ-q.js → debug-bundle-BOdYmCeV.js} +10 -3
  77. package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
  78. package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
  79. package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
  80. package/dist/doctor.cjs +1 -1
  81. package/dist/doctor.cjs.map +1 -1
  82. package/dist/doctor.d.ts +16 -6
  83. package/dist/doctor.js +147 -52
  84. package/dist/doctor.js.map +1 -1
  85. package/dist/{emergency-queue-Zy6lNafo.js → emergency-queue-B9WZxanZ.js} +4 -4
  86. package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
  87. package/dist/{emergency-queue-CNTRui5t.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
  88. package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
  89. package/dist/error-like-B11pB4aL.js.map +1 -1
  90. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  91. package/dist/{errors-Dh7kef0i.js → errors-D6bwgJtO.js} +3 -3
  92. package/dist/errors-D6bwgJtO.js.map +1 -0
  93. package/dist/{errors-tfEr48bS.cjs → errors-DCOCRdSi.cjs} +2 -2
  94. package/dist/errors-DCOCRdSi.cjs.map +1 -0
  95. package/dist/{factory-CJXVYp0R.cjs → factory-DLFDjdLv.cjs} +2 -2
  96. package/dist/factory-DLFDjdLv.cjs.map +1 -0
  97. package/dist/{factory-BonqI3NL.js → factory-e9Qo3K0z.js} +13 -13
  98. package/dist/factory-e9Qo3K0z.js.map +1 -0
  99. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  100. package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
  101. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  102. package/dist/global-scope-D9I8s-oN.js.map +1 -1
  103. package/dist/guards-Cidk71ME.js.map +1 -1
  104. package/dist/guards-nJ70syPt.cjs.map +1 -1
  105. package/dist/{identity-Cxgj6pZX.cjs → identity-BlvlgjrU.cjs} +2 -2
  106. package/dist/identity-BlvlgjrU.cjs.map +1 -0
  107. package/dist/{identity-DT5VmvXy.js → identity-BrQp_5J5.js} +19 -19
  108. package/dist/identity-BrQp_5J5.js.map +1 -0
  109. package/dist/index.cjs +1 -1
  110. package/dist/index.cjs.map +1 -1
  111. package/dist/index.d.ts +112 -79
  112. package/dist/index.js +783 -635
  113. package/dist/index.js.map +1 -1
  114. package/dist/{indexeddb-storage-CIoW21Xd.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
  115. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
  116. package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-DLXQzAGh.js} +4 -4
  117. package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
  118. package/dist/{interactions-DTgKy_6K.js → interactions-B6z2I4tU.js} +3 -3
  119. package/dist/interactions-B6z2I4tU.js.map +1 -0
  120. package/dist/{interactions-fEN6FbVo.cjs → interactions-P6pz08Jn.cjs} +2 -2
  121. package/dist/interactions-P6pz08Jn.cjs.map +1 -0
  122. package/dist/{journey-CuJrHzEg.js → journey-35yCMNFo.js} +20 -19
  123. package/dist/journey-35yCMNFo.js.map +1 -0
  124. package/dist/journey-DAGh5h9k.cjs +2 -0
  125. package/dist/journey-DAGh5h9k.cjs.map +1 -0
  126. package/dist/keys-BHhw_0Wh.cjs.map +1 -1
  127. package/dist/keys-BU9j5YqW.js.map +1 -1
  128. package/dist/{library-console-D2GY9Or6.cjs → library-console-BFWEuQsl.cjs} +2 -2
  129. package/dist/library-console-BFWEuQsl.cjs.map +1 -0
  130. package/dist/{library-console-C1m6g1BR.js → library-console-Dl_Ly6DQ.js} +2 -2
  131. package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
  132. package/dist/{library-request-1BX_UlaX.cjs → library-request-Da-CHKzT.cjs} +2 -2
  133. package/dist/library-request-Da-CHKzT.cjs.map +1 -0
  134. package/dist/{library-request-BQBT9N9Q.js → library-request-nI6pvI6I.js} +2 -2
  135. package/dist/library-request-nI6pvI6I.js.map +1 -0
  136. package/dist/{lifecycle-2EtUaRpo.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
  137. package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
  138. package/dist/{lifecycle-BaKx_-32.js → lifecycle-CZ6RRXc6.js} +2 -2
  139. package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
  140. package/dist/{log-record-i9zOTkpQ.cjs → log-record-D7bA1RPb.cjs} +2 -2
  141. package/dist/log-record-D7bA1RPb.cjs.map +1 -0
  142. package/dist/{log-record-CAoGBBf3.js → log-record-DIA6McNr.js} +2 -2
  143. package/dist/log-record-DIA6McNr.js.map +1 -0
  144. package/dist/{long-frames-Czk7IupC.js → long-frames-430_85Da.js} +8 -6
  145. package/dist/long-frames-430_85Da.js.map +1 -0
  146. package/dist/long-frames-Dd8tsi2U.cjs +2 -0
  147. package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
  148. package/dist/models/batch.d.ts +14 -15
  149. package/dist/models/bus.d.ts +24 -24
  150. package/dist/models/config.d.ts +402 -216
  151. package/dist/models/drop.d.ts +13 -11
  152. package/dist/models/health.d.ts +13 -13
  153. package/dist/models/log-record.d.ts +13 -14
  154. package/dist/models/metric.d.ts +82 -17
  155. package/dist/models/plugin.d.ts +13 -13
  156. package/dist/models/replay.d.ts +60 -0
  157. package/dist/models/serializer.d.ts +2 -3
  158. package/dist/models/stats.d.ts +2 -2
  159. package/dist/models/storage.d.ts +12 -11
  160. package/dist/{network-DBNwApoF.js → network-C7SkLf4v.js} +12 -12
  161. package/dist/network-C7SkLf4v.js.map +1 -0
  162. package/dist/{network-xbbuvG_6.cjs → network-pEX3PAJv.cjs} +2 -2
  163. package/dist/network-pEX3PAJv.cjs.map +1 -0
  164. package/dist/openfin-Bxelt0yg.js.map +1 -1
  165. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  166. package/dist/otlp-2MCrC3kd.cjs +2 -0
  167. package/dist/otlp-2MCrC3kd.cjs.map +1 -0
  168. package/dist/{otlp-BTJdIa6F.js → otlp-COq033e3.js} +25 -32
  169. package/dist/otlp-COq033e3.js.map +1 -0
  170. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  171. package/dist/patch-UdPz1ea8.js.map +1 -1
  172. package/dist/{platform-C2Ez5kDc.cjs → platform-12uR7kBQ.cjs} +2 -2
  173. package/dist/platform-12uR7kBQ.cjs.map +1 -0
  174. package/dist/{platform-DkcuXwe-.js → platform-CVewe4wQ.js} +7 -7
  175. package/dist/platform-CVewe4wQ.js.map +1 -0
  176. package/dist/profiler-BVWIOgnq.js +310 -0
  177. package/dist/profiler-BVWIOgnq.js.map +1 -0
  178. package/dist/profiler-eVCknCzS.cjs +2 -0
  179. package/dist/profiler-eVCknCzS.cjs.map +1 -0
  180. package/dist/profiler-frames-CLXlT_xL.js +86 -0
  181. package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
  182. package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
  183. package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
  184. package/dist/{remote-rules-Cfb4K-Nl.js → remote-rules-BJGDJGwA.js} +27 -27
  185. package/dist/remote-rules-BJGDJGwA.js.map +1 -0
  186. package/dist/{remote-rules-vzvk7aKf.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
  187. package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
  188. package/dist/replay-0zAJv9T3.js +338 -0
  189. package/dist/replay-0zAJv9T3.js.map +1 -0
  190. package/dist/replay-DomJpXqW.cjs +2 -0
  191. package/dist/replay-DomJpXqW.cjs.map +1 -0
  192. package/dist/{reports-Dk2YhKIh.cjs → reports-BsbqmP8h.cjs} +2 -2
  193. package/dist/reports-BsbqmP8h.cjs.map +1 -0
  194. package/dist/{reports-TA-zInnq.js → reports-BuXekPOS.js} +3 -3
  195. package/dist/reports-BuXekPOS.js.map +1 -0
  196. package/dist/{resource-timing-BLv3EA2A.js → resource-timing-CXGHwFRD.js} +4 -4
  197. package/dist/resource-timing-CXGHwFRD.js.map +1 -0
  198. package/dist/{resource-timing-Cysw1S1f.cjs → resource-timing-DkycFGDa.cjs} +2 -2
  199. package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
  200. package/dist/{sampling-Ckh2yW9k.cjs → sampling-Dd0wllyq.cjs} +2 -2
  201. package/dist/sampling-Dd0wllyq.cjs.map +1 -0
  202. package/dist/{sampling-C4VV-1MS.js → sampling-UUDbi3K0.js} +9 -9
  203. package/dist/sampling-UUDbi3K0.js.map +1 -0
  204. package/dist/{sanitize-6ymPlVvP.js → sanitize-CNmsD9r3.js} +2 -2
  205. package/dist/sanitize-CNmsD9r3.js.map +1 -0
  206. package/dist/{sanitize-BAWzkZt0.cjs → sanitize-ChLn97Ch.cjs} +2 -2
  207. package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
  208. package/dist/{select-ZF4by-lF.cjs → select-CTk-K5mG.cjs} +3 -3
  209. package/dist/select-CTk-K5mG.cjs.map +1 -0
  210. package/dist/{select-xtQaenIi.js → select-DPv_j6wq.js} +61 -61
  211. package/dist/select-DPv_j6wq.js.map +1 -0
  212. package/dist/{sender-CiMHC9YG.js → sender-15zEsZpr.js} +61 -60
  213. package/dist/sender-15zEsZpr.js.map +1 -0
  214. package/dist/sender-Bfpv9tad.cjs +2 -0
  215. package/dist/sender-Bfpv9tad.cjs.map +1 -0
  216. package/dist/storage/context-storage.d.ts +34 -33
  217. package/dist/storage/emergency-queue.d.ts +9 -9
  218. package/dist/storage/eviction.d.ts +12 -12
  219. package/dist/storage/factory.d.ts +8 -7
  220. package/dist/storage/gap.d.ts +6 -6
  221. package/dist/storage/idb-driver.d.ts +31 -32
  222. package/dist/storage/indexeddb-storage.d.ts +26 -27
  223. package/dist/storage/keys.d.ts +7 -7
  224. package/dist/storage/local-storage.d.ts +38 -38
  225. package/dist/storage/memory-storage.d.ts +21 -22
  226. package/dist/storage/persistence.d.ts +1 -1
  227. package/dist/storage-BA9RqRO-.cjs.map +1 -1
  228. package/dist/storage-DZwed89z.js.map +1 -1
  229. package/dist/{storm-VR024_QN.js → storm-BTSNTIWI.js} +2 -2
  230. package/dist/storm-BTSNTIWI.js.map +1 -0
  231. package/dist/{storm-CYi9Swpx.cjs → storm-D0_qZOEg.cjs} +2 -2
  232. package/dist/storm-D0_qZOEg.cjs.map +1 -0
  233. package/dist/transport/compression.d.ts +2 -2
  234. package/dist/transport/errors.d.ts +7 -7
  235. package/dist/transport/exit-flush.d.ts +39 -39
  236. package/dist/transport/headers.d.ts +2 -2
  237. package/dist/transport/http-transport.d.ts +28 -27
  238. package/dist/transport/memory-transport.d.ts +6 -6
  239. package/dist/transport/retry-engine.d.ts +35 -34
  240. package/dist/transport/serializers/ecs.d.ts +1 -1
  241. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  242. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  243. package/dist/transport/serializers/otlp.d.ts +16 -16
  244. package/dist/transport/serializers/select.d.ts +7 -7
  245. package/dist/transport/status-transport.d.ts +20 -20
  246. package/dist/transport/worker-protocol.d.ts +3 -3
  247. package/dist/types-BAerHgCq.js.map +1 -1
  248. package/dist/types-C7WNpnG1.cjs.map +1 -1
  249. package/dist/{unclean-exit-DFUN57wY.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
  250. package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
  251. package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-Cob_jyTv.js} +2 -2
  252. package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
  253. package/dist/unref-CU9Nyz_9.cjs +2 -0
  254. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  255. package/dist/unref-DgHPQeWv.js +7 -0
  256. package/dist/unref-DgHPQeWv.js.map +1 -0
  257. package/dist/user-timing-CdYqx3PF.cjs +2 -0
  258. package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
  259. package/dist/{user-timing-_jZIhDKI.js → user-timing-DgHubxCI.js} +5 -3
  260. package/dist/user-timing-DgHubxCI.js.map +1 -0
  261. package/dist/utils/console.d.ts +2 -2
  262. package/dist/utils/deadline.d.ts +4 -4
  263. package/dist/utils/error-like.d.ts +7 -7
  264. package/dist/utils/fixed-window.d.ts +9 -8
  265. package/dist/utils/global-scope.d.ts +8 -8
  266. package/dist/utils/guards.d.ts +2 -2
  267. package/dist/utils/identity.d.ts +17 -17
  268. package/dist/utils/library-console.d.ts +4 -4
  269. package/dist/utils/library-request.d.ts +10 -10
  270. package/dist/utils/lock.d.ts +10 -9
  271. package/dist/utils/openfin.d.ts +5 -5
  272. package/dist/utils/patch.d.ts +6 -6
  273. package/dist/utils/platform.d.ts +13 -11
  274. package/dist/utils/sanitize.d.ts +4 -4
  275. package/dist/utils/timer.d.ts +1 -1
  276. package/dist/utils/tracing.d.ts +38 -38
  277. package/dist/utils/unref.d.ts +3 -3
  278. package/dist/{web-socket-BWUoqBh8.cjs → web-socket-BTuvYoJI.cjs} +2 -2
  279. package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
  280. package/dist/{web-socket-CV7yIMnm.js → web-socket-DthJuSAg.js} +4 -4
  281. package/dist/web-socket-DthJuSAg.js.map +1 -0
  282. package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
  283. package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
  284. package/dist/web-vitals-CsGCWnUr.js +77 -0
  285. package/dist/web-vitals-CsGCWnUr.js.map +1 -0
  286. package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-B0_8rWy5.js} +4 -4
  287. package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
  288. package/dist/{worker-protocol-Bai7GAIA.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
  289. package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
  290. package/dist/worker-server-4en-Lt-3.cjs +2 -0
  291. package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
  292. package/dist/{worker-server-Dp5HYm4b.js → worker-server-Cne9MX9I.js} +8 -8
  293. package/dist/{worker-server-Dp5HYm4b.js.map → worker-server-Cne9MX9I.js.map} +1 -1
  294. package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
  295. package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
  296. package/dist/{worker-transport-D6jtgpqN.js → worker-transport-C3SjJAEC.js} +62 -61
  297. package/dist/worker-transport-C3SjJAEC.js.map +1 -0
  298. package/package.json +8 -2
  299. package/dist/batch-C8OcWR2L.cjs.map +0 -1
  300. package/dist/batch-CL9uWYY3.js.map +0 -1
  301. package/dist/bus-BZ0GldpT.js.map +0 -1
  302. package/dist/bus-VWlmM5xs.cjs +0 -2
  303. package/dist/bus-VWlmM5xs.cjs.map +0 -1
  304. package/dist/console-BPZCuSLc.cjs.map +0 -1
  305. package/dist/console-BeCF7n59.js.map +0 -1
  306. package/dist/constants-DqKJH_MP.cjs +0 -2
  307. package/dist/constants-DqKJH_MP.cjs.map +0 -1
  308. package/dist/constants-zyrqveN4.js +0 -304
  309. package/dist/constants-zyrqveN4.js.map +0 -1
  310. package/dist/deadline-BOjOxNHj.js.map +0 -1
  311. package/dist/deadline-XSnm95pg.cjs +0 -2
  312. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  313. package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
  314. package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
  315. package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
  316. package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
  317. package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
  318. package/dist/errors-Dh7kef0i.js.map +0 -1
  319. package/dist/errors-tfEr48bS.cjs.map +0 -1
  320. package/dist/factory-BonqI3NL.js.map +0 -1
  321. package/dist/factory-CJXVYp0R.cjs.map +0 -1
  322. package/dist/identity-Cxgj6pZX.cjs.map +0 -1
  323. package/dist/identity-DT5VmvXy.js.map +0 -1
  324. package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
  325. package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
  326. package/dist/interactions-DTgKy_6K.js.map +0 -1
  327. package/dist/interactions-fEN6FbVo.cjs.map +0 -1
  328. package/dist/journey-CuJrHzEg.js.map +0 -1
  329. package/dist/journey-pffMVMfa.cjs +0 -2
  330. package/dist/journey-pffMVMfa.cjs.map +0 -1
  331. package/dist/library-console-C1m6g1BR.js.map +0 -1
  332. package/dist/library-console-D2GY9Or6.cjs.map +0 -1
  333. package/dist/library-request-1BX_UlaX.cjs.map +0 -1
  334. package/dist/library-request-BQBT9N9Q.js.map +0 -1
  335. package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
  336. package/dist/lifecycle-BaKx_-32.js.map +0 -1
  337. package/dist/log-record-CAoGBBf3.js.map +0 -1
  338. package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
  339. package/dist/long-frames-BVg4i5SC.cjs +0 -2
  340. package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
  341. package/dist/long-frames-Czk7IupC.js.map +0 -1
  342. package/dist/network-DBNwApoF.js.map +0 -1
  343. package/dist/network-xbbuvG_6.cjs.map +0 -1
  344. package/dist/otlp-BDvFrLnc.cjs +0 -2
  345. package/dist/otlp-BDvFrLnc.cjs.map +0 -1
  346. package/dist/otlp-BTJdIa6F.js.map +0 -1
  347. package/dist/platform-C2Ez5kDc.cjs.map +0 -1
  348. package/dist/platform-DkcuXwe-.js.map +0 -1
  349. package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
  350. package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
  351. package/dist/reports-Dk2YhKIh.cjs.map +0 -1
  352. package/dist/reports-TA-zInnq.js.map +0 -1
  353. package/dist/resource-timing-BLv3EA2A.js.map +0 -1
  354. package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
  355. package/dist/sampling-C4VV-1MS.js.map +0 -1
  356. package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
  357. package/dist/sanitize-6ymPlVvP.js.map +0 -1
  358. package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
  359. package/dist/select-ZF4by-lF.cjs.map +0 -1
  360. package/dist/select-xtQaenIi.js.map +0 -1
  361. package/dist/sender-CiMHC9YG.js.map +0 -1
  362. package/dist/sender-D5wBoXA8.cjs +0 -2
  363. package/dist/sender-D5wBoXA8.cjs.map +0 -1
  364. package/dist/storm-CYi9Swpx.cjs.map +0 -1
  365. package/dist/storm-VR024_QN.js.map +0 -1
  366. package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
  367. package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
  368. package/dist/user-timing-C9kfRq3J.cjs +0 -2
  369. package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
  370. package/dist/user-timing-_jZIhDKI.js.map +0 -1
  371. package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
  372. package/dist/web-socket-CV7yIMnm.js.map +0 -1
  373. package/dist/web-vitals-Bq4WFHQo.js +0 -52
  374. package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
  375. package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
  376. package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
  377. package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
  378. package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
  379. package/dist/worker-server-BrIYkfoa.cjs +0 -2
  380. package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
  381. package/dist/worker-transport-Bwej4N2e.cjs +0 -2
  382. package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
  383. package/dist/worker-transport-D6jtgpqN.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory-DLFDjdLv.cjs","names":["isActionRecord","STORAGE_NAME_LOCAL","BATCH_STORAGE_KEY_PREFIX","batchKey","countRecords","isLogBatch","keysWithPrefix","STORAGE_NAME_MEMORY","countRecords","STORAGE_DB_NAME","STORAGE_NAME_NONE","STORAGE_PROBE_KEY","require_constants","require_batch","require_keys","hasAction","batch","EvictionPick","howMany","isAudit","item","pickEvictable","pick","items","addDrop","batches","records","reason","reportEviction","gap","diagnostics","onGap","dropped","createdAtOf","start","prefix","at","key","LocalStorageStorage","limits","out","limit","id","count","attempts","cutoff","result","expired","alive","createdAt","excess","context","keys","entry","entries","raw","parsed","MemoryStorage","index","stored","found","evicted","storageName","namespace","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","storage","IndexedDbStorage","dbName"],"sources":["../src/storage/eviction.ts","../src/storage/gap.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts"],"sourcesContent":["// src/storage/eviction.ts\n//\n// Picks which stored batches to evict. An action is an audit fact, so batches without one go\n// first. The walk stops early, because reading the whole store on every save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Checks whether a batch holds an action. Eviction removes such a batch last.\n * @param batch The batch to check.\n * @returns True if any record in the batch is an action.\n */\nexport function hasAction(batch: LogBatch): boolean {\n // Another script on the origin can write to the database. A throw in a cursor handler would\n // stop the eviction walk, and the walk would never settle.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from an oldest-first walk. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** The oldest items with an audit fact. Only used when there aren't enough plain items. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n */\n constructor(\n private readonly howMany: number,\n private readonly isAudit: (item: T) => boolean,\n ) {}\n\n /**\n * Adds the next item of the walk.\n * @param item The next oldest item.\n * @returns False once the pick has enough items without an audit fact, which stops the walk.\n */\n add(item: T): boolean {\n if (!this.isAudit(item)) {\n this.plain.push(item);\n } else if (this.audit.length < this.howMany) {\n this.audit.push(item);\n }\n\n return this.plain.length < this.howMany;\n }\n\n /**\n * Returns the items to evict, with the ones without an audit fact first.\n * @returns The picked items.\n */\n picked(): T[] {\n return [...this.plain, ...this.audit].slice(0, this.howMany);\n }\n}\n\n/**\n * Picks the items to evict from an oldest-first walk, and stops the walk early.\n * @param items Items, oldest first. A generator reads each item only when the walk needs it.\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n * @returns The picked items, with the ones without an audit fact first.\n */\nexport function pickEvictable<T>(\n items: Iterable<T>,\n howMany: number,\n isAudit: (item: T) => boolean,\n): T[] {\n const pick = new EvictionPick(howMany, isAudit);\n\n for (const item of items) {\n if (!pick.add(item)) {\n break;\n }\n }\n\n return pick.picked();\n}\n","// src/storage/gap.ts\n//\n// Counts and reports the batches a storage adapter drops. Every dropped batch is a loss, and\n// the gap handler passes it on to onDrop.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult } from \"../models/storage\";\n\n/**\n * Adds one rule's drop to the prune result.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts for this rule alone, for the gap report.\n */\nexport function addDrop(\n result: PruneResult,\n reason: PruneResult[\"reason\"],\n batches: number,\n records: number,\n): PruneResult {\n result.batches += batches;\n result.records += records;\n result.reason = reason;\n return { batches, records, reason };\n}\n\n/**\n * Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.\n * @param diagnostics Diagnostics reporter.\n * @param onGap The adapter's gap handler.\n * @param gap The drop's counts and reason.\n * @param dropped The dropped batches that the adapter could read.\n */\nexport function reportEviction(\n diagnostics: Diagnostics,\n onGap: GapReporter | undefined,\n gap: PruneResult,\n dropped: readonly LogBatch[],\n): void {\n if (gap.batches === 0) {\n return;\n }\n\n diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(gap.batches)} stored batches (${String(gap.records)} records).`,\n { ...gap },\n );\n onGap?.(gap, dropped);\n}\n","// src/storage/local-storage.ts\n//\n// Stores batches in localStorage under time-ordered keys. The padding makes keys().sort() a\n// sort by creation time. Without it the sort would compare the decimal times as text, so \"10\"\n// sorts before \"9\", and take() would not return the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/** A stored entry. A corrupt entry has no batch. */\ninterface Entry {\n key: string;\n batch: LogBatch | null;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after every save, and reading the\n * time from the batch would parse the whole store each time.\n * @param key The prefixed storage key.\n * @param prefix The storage key prefix.\n * @returns Creation time in epoch milliseconds, or null for a malformed key.\n */\nfunction createdAtOf(key: string, prefix: string): number | null {\n const start = prefix.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** StorageAdapter that keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\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 private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n private readonly prefix = BATCH_STORAGE_KEY_PREFIX,\n ) {}\n\n /**\n * Writes a batch to localStorage, removing the oldest entries on a quota error.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\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 if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // A corrupt entry can't be recovered. Remove it without a gap count, because it has no\n // readable record count.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them. Stops\n * at the limit, so later entries are never parsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const batch of this.batches()) {\n if (out.length >= limit) {\n break;\n }\n if (batch.routingContextId === id) {\n out.push(batch);\n }\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Counts one context's stored batches. The context id isn't in the key, so every entry is\n * read.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n let count = 0;\n\n for (const batch of this.batches()) {\n if (batch.routingContextId === id) {\n count++;\n }\n }\n\n return Promise.resolve(count);\n }\n\n /**\n * Reads the valid batches one at a time, oldest first, and removes any corrupt entry.\n * @yields Each valid batch.\n */\n private *batches(): Generator<LogBatch> {\n for (const key of this.keys()) {\n const batch = this.read(key);\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n yield batch;\n }\n }\n\n /**\n * Deletes the batch with the given ID from localStorage.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count. The key doesn't change.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const expired: string[] = [];\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key, this.prefix);\n // A key with no readable time has no place in the sort order either.\n if (createdAt === null || createdAt < cutoff) {\n expired.push(key);\n continue;\n }\n alive.push(key);\n }\n\n // The record count is the one field the key doesn't hold, so parse only the deleted batches.\n this.drop(result, \"expired\", [...this.entries(expired)]);\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n this.drop(result, \"over_capacity\", this.evictable(alive, excess));\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys without deserializing the batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes every batch key from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** Does nothing. localStorage has no connection to close. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch The batch to store.\n * @param context The text diagnostics reports if the write fails.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(batchKey(this.prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Removes a quarter of the store to free quota, and counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n const howMany = Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR);\n\n this.drop(result, \"quota\", this.evictable(keys, howMany));\n }\n\n /**\n * Picks the entries to evict. Entries without an action go first, because an action is an\n * audit fact. A corrupt entry has no action, so it goes first too.\n * @param keys Batch keys, oldest first.\n * @param howMany Number of entries to evict.\n * @returns The picked entries.\n */\n private evictable(keys: string[], howMany: number): Entry[] {\n return pickEvictable(\n this.entries(keys),\n howMany,\n (entry) => entry.batch !== null && hasAction(entry.batch),\n );\n }\n\n /**\n * Reads the entries one at a time. The eviction walk stops early, so later entries are\n * never parsed.\n * @param keys Batch keys.\n * @yields Each key with its batch.\n */\n private *entries(keys: string[]): Generator<Entry> {\n for (const key of keys) {\n yield { key, batch: this.read(key) };\n }\n }\n\n /**\n * Removes entries and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that removes the entries.\n * @param entries The entries to remove.\n */\n private drop(result: PruneResult, reason: PruneResult[\"reason\"], entries: Entry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const dropped: LogBatch[] = [];\n\n for (const { key, batch } of entries) {\n this.removeKey(key);\n if (batch) {\n dropped.push(batch);\n }\n }\n\n // A corrupt entry counts as a batch with no records.\n const gap = addDrop(result, reason, entries.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Reads and validates the stored batch at a key.\n * @param key The storage key to read.\n * @returns The validated LogBatch, or null if it is missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read a stored batch.\",\n () => localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"A stored batch is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report would count one\n // corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\n * @param id Batch identifier.\n * @returns The matching storage key, or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes a list of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns every batch storage key, sorted.\n * @returns The sorted storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// Keeps batches in volatile memory during offline periods, so a reload loses all of them.\n// This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop } from \"./gap\";\n\n/** StorageAdapter that keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** The batches, in FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch and applies retention pruning.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n // A batch with a known id replaces the old copy in place, as IndexedDB put() does.\n const index = this.batches.findIndex((stored) => stored.id === batch.id);\n if (index >= 0) {\n this.batches[index] = batch;\n } else {\n this.batches.push(batch);\n }\n await this.prune();\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return Promise.resolve(\n this.batches.filter((batch) => batch.routingContextId === id).slice(0, limit),\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n return Promise.resolve(this.batches.filter((batch) => batch.routingContextId === id).length);\n }\n\n /**\n * Deletes the batch with the given ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\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 bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n this.report(result, \"expired\", expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n // An action is an audit fact, so evict the batches without one first.\n const evicted = pickEvictable(this.batches, excess, hasAction);\n this.batches = this.batches.filter((batch) => !evicted.includes(batch));\n this.report(result, \"over_capacity\", evicted);\n }\n\n return Promise.resolve(result);\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 report(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n if (dropped.length === 0) {\n return;\n }\n\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n this.onGap?.(gap, dropped);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Deletes every stored batch. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Deletes every stored batch when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Picks a storage adapter, falling back from IndexedDB to localStorage to memory instead of\n// throwing. IndexedDB is unavailable in private mode and in sandboxed frames.\n\nimport {\n STORAGE_DB_NAME,\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * Returns the database name for one application namespace. The sender and the deletion both\n * use this one rule.\n * @param namespace Application namespace. An empty value keeps the name used before namespaces.\n * @returns The IndexedDB database name.\n */\nexport function storageName(namespace: string): string {\n return namespace ? `${STORAGE_DB_NAME}:${namespace}` : STORAGE_DB_NAME;\n}\n\n/**\n * Builds the adapter that keeps nothing, returned for the \"none\" strategy. Every method\n * resolves, so a sender that calls close() on shutdown doesn't crash.\n * @param onGap Receives every batch the adapter doesn't keep. Each one is a loss.\n * @returns The adapter.\n */\nconst noop = (onGap?: GapReporter): StorageAdapter => ({\n name: STORAGE_NAME_NONE,\n save: (batch) => {\n onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return Promise.resolve();\n },\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n});\n\n/**\n * Checks whether IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks whether localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if a probe write to localStorage succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter, falling back to the next one when a dependency is\n * unavailable.\n * @param strategy The configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns A promise that resolves to the selected StorageAdapter.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n namespace = \"\",\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop(onGap);\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // The dynamic import keeps the driver out of the main bundle. If the chunk fails to\n // load, we fall back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here rather than on first use. Private mode, a corrupt profile\n // and some WebViews define indexedDB but reject open(), and only a rejection in\n // this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB is not available. The library uses memory storage instead.\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(\n limits,\n diagnostics,\n onGap,\n namespace ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:batch:` : undefined,\n );\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"No persistent storage is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n"],"mappings":"A,+GAYA,SAAgBe,EAAU,EAA0B,CAGlD,OAAO,MAAM,QAAQC,EAAM,OAAO,GAAKA,EAAM,QAAQ,KAAKhB,EAAAA,CAAc,CAC1E,CAGA,IAAaiB,EAAb,KAA6B,CAYR,QACA,QAX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,CAAK,EAKvE,OADA,MAAMuC,EAAQ,KAAK,EACZA,CACT,CACF,EACA,GAAID,EACF,OAAOA,CAEX,CAEA,GAAID,IAAA,YAKF,OAJAtC,EAAY,OACV,mBACA,sEACF,EACO,IAAI2B,EAAclB,EAAQR,CAAK,CAE1C,CAeA,OAbImC,EAAgBpC,CAAW,EACtB,IAAIQ,EACTC,EACAT,EACAC,EACAgC,EAAY,+BAA+B,mBAAmBA,CAAS,EAAE,SAAW,IAAA,EACtF,GAGFjC,EAAY,OACV,mBACA,2FACF,EACO,IAAI2B,EAAclB,EAAQR,CAAK,EACxC,C"}
@@ -1,5 +1,5 @@
1
- import { Dn as e, E as t, En as n, On as r, Sn as i, kn as a } from "./constants-zyrqveN4.js";
2
- import { i as o, n as s, r as c } from "./batch-CL9uWYY3.js";
1
+ import { Bn as e, E as t, Pn as n, Rn as r, Vn as i, zn as a } from "./constants-Bwl_YtQi.js";
2
+ import { i as o, n as s, r as c } from "./batch-BjQUwjA6.js";
3
3
  import { n as l, t as u } from "./keys-BU9j5YqW.js";
4
4
  // src/storage/eviction.ts
5
5
  function d(e) {
@@ -46,7 +46,7 @@ var _ = class {
46
46
  diagnostics;
47
47
  onGap;
48
48
  prefix;
49
- name = n;
49
+ name = r;
50
50
  constructor(e, n, r, i = t) {
51
51
  this.limits = e, this.diagnostics = n, this.onGap = r, this.prefix = i;
52
52
  }
@@ -173,7 +173,7 @@ var _ = class {
173
173
  }, v = class {
174
174
  limits;
175
175
  onGap;
176
- name = e;
176
+ name = a;
177
177
  batches = [];
178
178
  constructor(e, t) {
179
179
  this.limits = e, this.onGap = t;
@@ -229,15 +229,15 @@ var _ = class {
229
229
  };
230
230
  // src/storage/factory.ts
231
231
  function y(e) {
232
- return e ? `${i}:${e}` : i;
232
+ return e ? `${n}:${e}` : n;
233
233
  }
234
- var b = (e) => ({
235
- name: r,
236
- save: (t) => (e?.({
234
+ var b = (t) => ({
235
+ name: e,
236
+ save: (e) => (t?.({
237
237
  batches: 1,
238
- records: t.records.length,
238
+ records: e.records.length,
239
239
  reason: "not_stored"
240
- }, [t]), Promise.resolve()),
240
+ }, [e]), Promise.resolve()),
241
241
  take: () => Promise.resolve([]),
242
242
  remove: () => Promise.resolve(),
243
243
  bumpAttempts: () => Promise.resolve(),
@@ -254,7 +254,7 @@ function x(e) {
254
254
  return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
255
255
  }
256
256
  function S(e) {
257
- return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(a, "1"), localStorage.removeItem(a), !0)) === !0;
257
+ return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(i, "1"), localStorage.removeItem(i), !0)) === !0;
258
258
  }
259
259
  async function C(e, t, n, r, i, a = "") {
260
260
  if (e === "none") return b(i);
@@ -262,7 +262,7 @@ async function C(e, t, n, r, i, a = "") {
262
262
  if (e === "indexeddb" || e === "auto") {
263
263
  if (x(r)) {
264
264
  let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
265
- let { IndexedDbStorage: e } = await import("./indexeddb-storage-BJVtiQKm.js"), a = new e(t, n, r, i);
265
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-DLXQzAGh.js"), a = new e(t, n, r, i);
266
266
  return await a.open(), a;
267
267
  });
268
268
  if (e) return e;
@@ -273,4 +273,4 @@ async function C(e, t, n, r, i, a = "") {
273
273
  }
274
274
  export { C as createStorage, d as i, h as n, f as r, y as storageName, m as t };
275
275
 
276
- //# sourceMappingURL=factory-BonqI3NL.js.map
276
+ //# sourceMappingURL=factory-e9Qo3K0z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory-e9Qo3K0z.js","names":["STORAGE_NAME_NONE","BATCH_STORAGE_KEY_PREFIX","STORAGE_DB_NAME","STORAGE_NAME_LOCAL","STORAGE_PROBE_KEY","STORAGE_NAME_MEMORY","isLogBatch","countRecords","isActionRecord","keysWithPrefix","batchKey","hasAction","batch","EvictionPick","howMany","isAudit","item","pickEvictable","pick","items","addDrop","batches","records","reason","reportEviction","gap","diagnostics","onGap","dropped","createdAtOf","start","prefix","at","key","LocalStorageStorage","limits","out","limit","id","count","attempts","cutoff","result","expired","alive","createdAt","excess","context","keys","entry","entries","raw","parsed","MemoryStorage","index","stored","found","evicted","storageName","namespace","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","storage","IndexedDbStorage","dbName"],"sources":["../src/storage/eviction.ts","../src/storage/gap.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts"],"sourcesContent":["// src/storage/eviction.ts\n//\n// Picks which stored batches to evict. An action is an audit fact, so batches without one go\n// first. The walk stops early, because reading the whole store on every save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Checks whether a batch holds an action. Eviction removes such a batch last.\n * @param batch The batch to check.\n * @returns True if any record in the batch is an action.\n */\nexport function hasAction(batch: LogBatch): boolean {\n // Another script on the origin can write to the database. A throw in a cursor handler would\n // stop the eviction walk, and the walk would never settle.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from an oldest-first walk. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** The oldest items with an audit fact. Only used when there aren't enough plain items. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n */\n constructor(\n private readonly howMany: number,\n private readonly isAudit: (item: T) => boolean,\n ) {}\n\n /**\n * Adds the next item of the walk.\n * @param item The next oldest item.\n * @returns False once the pick has enough items without an audit fact, which stops the walk.\n */\n add(item: T): boolean {\n if (!this.isAudit(item)) {\n this.plain.push(item);\n } else if (this.audit.length < this.howMany) {\n this.audit.push(item);\n }\n\n return this.plain.length < this.howMany;\n }\n\n /**\n * Returns the items to evict, with the ones without an audit fact first.\n * @returns The picked items.\n */\n picked(): T[] {\n return [...this.plain, ...this.audit].slice(0, this.howMany);\n }\n}\n\n/**\n * Picks the items to evict from an oldest-first walk, and stops the walk early.\n * @param items Items, oldest first. A generator reads each item only when the walk needs it.\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n * @returns The picked items, with the ones without an audit fact first.\n */\nexport function pickEvictable<T>(\n items: Iterable<T>,\n howMany: number,\n isAudit: (item: T) => boolean,\n): T[] {\n const pick = new EvictionPick(howMany, isAudit);\n\n for (const item of items) {\n if (!pick.add(item)) {\n break;\n }\n }\n\n return pick.picked();\n}\n","// src/storage/gap.ts\n//\n// Counts and reports the batches a storage adapter drops. Every dropped batch is a loss, and\n// the gap handler passes it on to onDrop.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult } from \"../models/storage\";\n\n/**\n * Adds one rule's drop to the prune result.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts for this rule alone, for the gap report.\n */\nexport function addDrop(\n result: PruneResult,\n reason: PruneResult[\"reason\"],\n batches: number,\n records: number,\n): PruneResult {\n result.batches += batches;\n result.records += records;\n result.reason = reason;\n return { batches, records, reason };\n}\n\n/**\n * Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.\n * @param diagnostics Diagnostics reporter.\n * @param onGap The adapter's gap handler.\n * @param gap The drop's counts and reason.\n * @param dropped The dropped batches that the adapter could read.\n */\nexport function reportEviction(\n diagnostics: Diagnostics,\n onGap: GapReporter | undefined,\n gap: PruneResult,\n dropped: readonly LogBatch[],\n): void {\n if (gap.batches === 0) {\n return;\n }\n\n diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(gap.batches)} stored batches (${String(gap.records)} records).`,\n { ...gap },\n );\n onGap?.(gap, dropped);\n}\n","// src/storage/local-storage.ts\n//\n// Stores batches in localStorage under time-ordered keys. The padding makes keys().sort() a\n// sort by creation time. Without it the sort would compare the decimal times as text, so \"10\"\n// sorts before \"9\", and take() would not return the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/** A stored entry. A corrupt entry has no batch. */\ninterface Entry {\n key: string;\n batch: LogBatch | null;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after every save, and reading the\n * time from the batch would parse the whole store each time.\n * @param key The prefixed storage key.\n * @param prefix The storage key prefix.\n * @returns Creation time in epoch milliseconds, or null for a malformed key.\n */\nfunction createdAtOf(key: string, prefix: string): number | null {\n const start = prefix.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** StorageAdapter that keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\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 private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n private readonly prefix = BATCH_STORAGE_KEY_PREFIX,\n ) {}\n\n /**\n * Writes a batch to localStorage, removing the oldest entries on a quota error.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\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 if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // A corrupt entry can't be recovered. Remove it without a gap count, because it has no\n // readable record count.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them. Stops\n * at the limit, so later entries are never parsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const batch of this.batches()) {\n if (out.length >= limit) {\n break;\n }\n if (batch.routingContextId === id) {\n out.push(batch);\n }\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Counts one context's stored batches. The context id isn't in the key, so every entry is\n * read.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n let count = 0;\n\n for (const batch of this.batches()) {\n if (batch.routingContextId === id) {\n count++;\n }\n }\n\n return Promise.resolve(count);\n }\n\n /**\n * Reads the valid batches one at a time, oldest first, and removes any corrupt entry.\n * @yields Each valid batch.\n */\n private *batches(): Generator<LogBatch> {\n for (const key of this.keys()) {\n const batch = this.read(key);\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n yield batch;\n }\n }\n\n /**\n * Deletes the batch with the given ID from localStorage.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count. The key doesn't change.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const expired: string[] = [];\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key, this.prefix);\n // A key with no readable time has no place in the sort order either.\n if (createdAt === null || createdAt < cutoff) {\n expired.push(key);\n continue;\n }\n alive.push(key);\n }\n\n // The record count is the one field the key doesn't hold, so parse only the deleted batches.\n this.drop(result, \"expired\", [...this.entries(expired)]);\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n this.drop(result, \"over_capacity\", this.evictable(alive, excess));\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys without deserializing the batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes every batch key from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** Does nothing. localStorage has no connection to close. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch The batch to store.\n * @param context The text diagnostics reports if the write fails.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(batchKey(this.prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Removes a quarter of the store to free quota, and counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n const howMany = Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR);\n\n this.drop(result, \"quota\", this.evictable(keys, howMany));\n }\n\n /**\n * Picks the entries to evict. Entries without an action go first, because an action is an\n * audit fact. A corrupt entry has no action, so it goes first too.\n * @param keys Batch keys, oldest first.\n * @param howMany Number of entries to evict.\n * @returns The picked entries.\n */\n private evictable(keys: string[], howMany: number): Entry[] {\n return pickEvictable(\n this.entries(keys),\n howMany,\n (entry) => entry.batch !== null && hasAction(entry.batch),\n );\n }\n\n /**\n * Reads the entries one at a time. The eviction walk stops early, so later entries are\n * never parsed.\n * @param keys Batch keys.\n * @yields Each key with its batch.\n */\n private *entries(keys: string[]): Generator<Entry> {\n for (const key of keys) {\n yield { key, batch: this.read(key) };\n }\n }\n\n /**\n * Removes entries and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that removes the entries.\n * @param entries The entries to remove.\n */\n private drop(result: PruneResult, reason: PruneResult[\"reason\"], entries: Entry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const dropped: LogBatch[] = [];\n\n for (const { key, batch } of entries) {\n this.removeKey(key);\n if (batch) {\n dropped.push(batch);\n }\n }\n\n // A corrupt entry counts as a batch with no records.\n const gap = addDrop(result, reason, entries.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Reads and validates the stored batch at a key.\n * @param key The storage key to read.\n * @returns The validated LogBatch, or null if it is missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read a stored batch.\",\n () => localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"A stored batch is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report would count one\n // corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\n * @param id Batch identifier.\n * @returns The matching storage key, or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes a list of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns every batch storage key, sorted.\n * @returns The sorted storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// Keeps batches in volatile memory during offline periods, so a reload loses all of them.\n// This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop } from \"./gap\";\n\n/** StorageAdapter that keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** The batches, in FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch and applies retention pruning.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n // A batch with a known id replaces the old copy in place, as IndexedDB put() does.\n const index = this.batches.findIndex((stored) => stored.id === batch.id);\n if (index >= 0) {\n this.batches[index] = batch;\n } else {\n this.batches.push(batch);\n }\n await this.prune();\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return Promise.resolve(\n this.batches.filter((batch) => batch.routingContextId === id).slice(0, limit),\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n return Promise.resolve(this.batches.filter((batch) => batch.routingContextId === id).length);\n }\n\n /**\n * Deletes the batch with the given ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\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 bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n this.report(result, \"expired\", expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n // An action is an audit fact, so evict the batches without one first.\n const evicted = pickEvictable(this.batches, excess, hasAction);\n this.batches = this.batches.filter((batch) => !evicted.includes(batch));\n this.report(result, \"over_capacity\", evicted);\n }\n\n return Promise.resolve(result);\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 report(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n if (dropped.length === 0) {\n return;\n }\n\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n this.onGap?.(gap, dropped);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Deletes every stored batch. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Deletes every stored batch when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Picks a storage adapter, falling back from IndexedDB to localStorage to memory instead of\n// throwing. IndexedDB is unavailable in private mode and in sandboxed frames.\n\nimport {\n STORAGE_DB_NAME,\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * Returns the database name for one application namespace. The sender and the deletion both\n * use this one rule.\n * @param namespace Application namespace. An empty value keeps the name used before namespaces.\n * @returns The IndexedDB database name.\n */\nexport function storageName(namespace: string): string {\n return namespace ? `${STORAGE_DB_NAME}:${namespace}` : STORAGE_DB_NAME;\n}\n\n/**\n * Builds the adapter that keeps nothing, returned for the \"none\" strategy. Every method\n * resolves, so a sender that calls close() on shutdown doesn't crash.\n * @param onGap Receives every batch the adapter doesn't keep. Each one is a loss.\n * @returns The adapter.\n */\nconst noop = (onGap?: GapReporter): StorageAdapter => ({\n name: STORAGE_NAME_NONE,\n save: (batch) => {\n onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return Promise.resolve();\n },\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n});\n\n/**\n * Checks whether IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks whether localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if a probe write to localStorage succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter, falling back to the next one when a dependency is\n * unavailable.\n * @param strategy The configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns A promise that resolves to the selected StorageAdapter.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n namespace = \"\",\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop(onGap);\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // The dynamic import keeps the driver out of the main bundle. If the chunk fails to\n // load, we fall back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here rather than on first use. Private mode, a corrupt profile\n // and some WebViews define indexedDB but reject open(), and only a rejection in\n // this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB is not available. The library uses memory storage instead.\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(\n limits,\n diagnostics,\n onGap,\n namespace ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:batch:` : undefined,\n );\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"No persistent storage is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n"],"mappings":";;;;AAYA,SAAgBW,EAAU,GAA0B;CAGlD,OAAO,MAAM,QAAQC,EAAM,OAAO,KAAKA,EAAM,QAAQ,KAAKJ,CAAc;AAC1E;AAGA,IAAaK,IAAb,MAA6B;CAYR;CACA;CAXnB,QAA8B,CAAC;CAG/B,QAA8B,CAAC;CAM/B,YACE,GACA,GACA;EADiB,AADA,KAAA,UAAAC,GACA,KAAA,UAAAC;CAChB;CAOH,IAA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AE1C;CAeA,OAbImC,EAAgBpC,CAAW,IACtB,IAAIQ,EACTC,GACAT,GACAC,GACAgC,IAAY,+BAA+B,mBAAmBA,CAAS,EAAE,WAAW,KAAA,CACtF,KAGFjC,EAAY,OACV,oBACA,2FACF,GACO,IAAI2B,EAAclB,GAAQR,CAAK;AACxC"}
@@ -1 +1 @@
1
- {"version":3,"file":"fixed-window-CvESpFYV.cjs","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period adds no allowance. The capture modules and\n// the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param windowMs Length of the window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Tells if a fixed window has ended. The bus uses the same rule to expire its source entries.\n * @param window Window state.\n * @param windowMs Length of the window, in milliseconds.\n * @param now Current epoch time, in milliseconds.\n * @returns True after the window length, or when the clock moved back. Without the second\n * check, a clock that moves back keeps the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":"AAoBA,SAAgBA,EAAc,EAAqB,EAAe,EAA2B,CAC3F,IAAMC,EAAM,KAAK,IAAI,EASrB,OAPIC,EAAYC,EAAQC,EAAUH,CAAG,IACnC,EAAO,MAAQA,EACf,EAAO,MAAQ,GAGjB,EAAO,QAEAE,EAAO,OAASE,CACzB,CAUA,SAAgBH,EAAY,EAAqB,EAAkB,EAAsB,CACvF,OAAOD,EAAME,EAAO,OAASF,EAAME,EAAO,MAAQC,CACpD,C"}
1
+ {"version":3,"file":"fixed-window-CvESpFYV.cjs","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period earns no extra allowance. The capture\n// modules and the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window The window state to update.\n * @param limit Maximum events per window.\n * @param windowMs Window length in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Checks whether a fixed window has ended. The bus uses the same rule to expire its source\n * entries.\n * @param window Window state.\n * @param windowMs Window length in milliseconds.\n * @param now Current epoch time in milliseconds.\n * @returns True once the window length has passed, or when the clock moved back. Without the\n * second check, a clock that moves back would keep the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":"AAoBA,SAAgBA,EAAc,EAAqB,EAAe,EAA2B,CAC3F,IAAMC,EAAM,KAAK,IAAI,EASrB,OAPIC,EAAYC,EAAQC,EAAUH,CAAG,IACnC,EAAO,MAAQA,EACf,EAAO,MAAQ,GAGjB,EAAO,QAEAE,EAAO,OAASE,CACzB,CAWA,SAAgBH,EAAY,EAAqB,EAAkB,EAAsB,CACvF,OAAOD,EAAME,EAAO,OAASF,EAAME,EAAO,MAAQC,CACpD,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"fixed-window-Dq3MLUUv.js","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period adds no allowance. The capture modules and\n// the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window Window state to change.\n * @param limit Maximum events in each window.\n * @param windowMs Length of the window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Tells if a fixed window has ended. The bus uses the same rule to expire its source entries.\n * @param window Window state.\n * @param windowMs Length of the window, in milliseconds.\n * @param now Current epoch time, in milliseconds.\n * @returns True after the window length, or when the clock moved back. Without the second\n * check, a clock that moves back keeps the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":";AAoBA,SAAgBA,EAAc,GAAqB,GAAe,GAA2B;CAC3F,IAAMC,IAAM,KAAK,IAAI;CASrB,OAPIC,EAAYC,GAAQC,GAAUH,CAAG,MACnC,EAAO,QAAQA,GACf,EAAO,QAAQ,IAGjB,EAAO,SAEAE,EAAO,SAASE;AACzB;AAUA,SAAgBH,EAAY,GAAqB,GAAkB,GAAsB;CACvF,OAAOD,IAAME,EAAO,SAASF,IAAME,EAAO,QAAQC;AACpD"}
1
+ {"version":3,"file":"fixed-window-Dq3MLUUv.js","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period earns no extra allowance. The capture\n// modules and the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window The window state to update.\n * @param limit Maximum events per window.\n * @param windowMs Window length in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Checks whether a fixed window has ended. The bus uses the same rule to expire its source\n * entries.\n * @param window Window state.\n * @param windowMs Window length in milliseconds.\n * @param now Current epoch time in milliseconds.\n * @returns True once the window length has passed, or when the clock moved back. Without the\n * second check, a clock that moves back would keep the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":";AAoBA,SAAgBA,EAAc,GAAqB,GAAe,GAA2B;CAC3F,IAAMC,IAAM,KAAK,IAAI;CASrB,OAPIC,EAAYC,GAAQC,GAAUH,CAAG,MACnC,EAAO,QAAQA,GACf,EAAO,QAAQ,IAGjB,EAAO,SAEAE,EAAO,SAASE;AACzB;AAWA,SAAgBH,EAAY,GAAqB,GAAkB,GAAsB;CACvF,OAAOD,IAAME,EAAO,SAASF,IAAME,EAAO,QAAQC;AACpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests if a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF,C"}
1
+ {"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol, so two copies of the library on one page share the\n// count. Otherwise one copy would capture the other copy's requests and console lines.\n\n/** A scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. Only the synchronous part of the function is covered.\n * @param fn The function to run.\n * @returns The function's return value.\n */\n run<T>(fn: () => T): T;\n /**\n * Checks whether a scope is open.\n * @returns True while a function is running inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Creates a scope whose count lives on a global symbol.\n * @param key The global symbol's key.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // Counting keeps this correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"global-scope-D9I8s-oN.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests if a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
1
+ {"version":3,"file":"global-scope-D9I8s-oN.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol, so two copies of the library on one page share the\n// count. Otherwise one copy would capture the other copy's requests and console lines.\n\n/** A scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. Only the synchronous part of the function is covered.\n * @param fn The function to run.\n * @returns The function's return value.\n */\n run<T>(fn: () => T): T;\n /**\n * Checks whether a scope is open.\n * @returns True while a function is running inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Creates a scope whose count lives on a global symbol.\n * @param key The global symbol's key.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // Counting keeps this correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"guards-Cidk71ME.js","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAUA,SAAgBA,EAAS,GAAkD;CACzE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E"}
1
+ {"version":3,"file":"guards-Cidk71ME.js","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values that come from outside the library, such as config input, a server\n// answer or a call's payload.\n\n/**\n * Checks whether a value is a non-null object that isn't an array.\n * @param value The value to check.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAUA,SAAgBA,EAAS,GAAkD;CACzE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E"}
@@ -1 +1 @@
1
- {"version":3,"file":"guards-nJ70syPt.cjs","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":"AAUA,SAAgBA,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,C"}
1
+ {"version":3,"file":"guards-nJ70syPt.cjs","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values that come from outside the library, such as config input, a server\n// answer or a call's payload.\n\n/**\n * Checks whether a value is a non-null object that isn't an array.\n * @param value The value to check.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":"AAUA,SAAgBA,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,C"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-DqKJH_MP.cjs");var t={local:()=>localStorage,session:()=>sessionStorage};function n(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function r(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return r(16)}function a(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function o(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function s(t,n,r,i){let o=a(t,`local`,e.vn,n);if(o)try{let e=JSON.parse(o);return e.id&&(i===0||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function c(n,r=t,c=e._n){let l=i(n),u=Date.now(),d=i(n),f=s(r,n,u,c)??d,p=JSON.stringify({id:f,lastSeenAt:u});o(r,`local`,e.vn,p,n);let m=a(r,`session`,`ui-observability.tab`,n)??``;return m||(m=i(n),o(r,`session`,e.An,m,n)),{sessionId:f,tabId:m,contextId:l}}function l(t,n,r){o(r,`session`,e.An,t,n)}var u=class{diagnostics;stores;touchMs;idleMs;lastTouchAt=0;constructor(n,r=t,i=e.yn,a=e._n){this.diagnostics=n,this.stores=r,this.touchMs=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<this.touchMs)return;let n=s(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return s(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.vn,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
2
- //# sourceMappingURL=identity-Cxgj6pZX.cjs.map
1
+ const e=require("./constants-DakMxVB2.cjs");var t={local:()=>localStorage,session:()=>sessionStorage};function n(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function r(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return r(16)}function a(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function o(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function s(t,n,r,i){let o=a(t,`local`,e.An,n);if(o)try{let e=JSON.parse(o);return e.id&&(i===0||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function c(n,r=t,c=e.kn){let l=i(n),u=Date.now(),d=i(n),f=s(r,n,u,c)??d,p=JSON.stringify({id:f,lastSeenAt:u});o(r,`local`,e.An,p,n);let m=a(r,`session`,`ui-observability.tab`,n)??``;return m||(m=i(n),o(r,`session`,e.Hn,m,n)),{sessionId:f,tabId:m,contextId:l}}function l(t,n,r){o(r,`session`,e.Hn,t,n)}var u=class{diagnostics;stores;touchMs;idleMs;lastTouchAt=0;constructor(n,r=t,i=e.jn,a=e.kn){this.diagnostics=n,this.stores=r,this.touchMs=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<this.touchMs)return;let n=s(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return s(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.An,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
2
+ //# sourceMappingURL=identity-BlvlgjrU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-BlvlgjrU.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","SESSION_TOUCH_MS","require_constants","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","touchMs","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. 0 means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === 0 || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly touchMs = SESSION_TOUCH_MS,\n private readonly idleMs = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < this.touchMs) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"A,4CAwDA,IAAaK,EAAiC,CAC5C,UAAa,aACb,YAAe,cACjB,EAMA,SAAgBC,GAA+B,CAC7C,IAAMC,EAAQ,IAA6C,CACzD,QAAU,GAAQC,EAAI,IAAIC,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvBD,EAAI,IAAIC,EAAKC,CAAK,CACpB,EACA,WAAa,GAAQ,CACnBF,EAAI,OAAOC,CAAG,CAChB,CACF,GAEME,EAAaJ,EAAK,IAAI,GAAK,EAC3BK,EAAeL,EAAK,IAAI,GAAK,EAEnC,MAAO,CAAE,UAAaI,EAAY,YAAeC,CAAa,CAChE,CAQA,SAAgBC,EAAU,EAA4B,CACpD,IAAMC,EAAQ,IAAI,WAAWC,CAAU,EACvC,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,iBAAoB,WACrE,OAAO,gBAAgBD,CAAK,OAE5B,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAY,IAC9B,EAAMC,GAAK,KAAK,MAAM,KAAK,OAAO,EAAA,GAAoB,EAG1D,OAAO,MAAM,KAAKF,EAAQ,GAAMG,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAC1E,CAOA,SAAgBC,EAAM,EAAkC,CACtD,GAAI,CACF,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,CAE7B,MAAQ,CAGNC,EAAY,MAAM,sBAAsB,CAC1C,CAC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,UAAWpB,EAAAA,GAAYgC,EAAOf,CAAW,CAC7D,CAOA,IAAaiB,EAAb,KAA0B,CASd,YACS,OACA,QACA,OAVnB,YAAsB,EAMtB,YACE,EACA,EAA0C/B,EAC1C,EAA2BF,EAAAA,GAC3B,EAA0BF,EAAAA,GAC1B,CAJQ,KAAA,YAAAkB,EACS,KAAA,OAAAG,EACA,KAAA,QAAAe,EACA,KAAA,OAAAV,CAChB,CAMH,MAAM,EAAyB,CAC7B,IAAMC,EAAM,KAAK,IAAI,EAErB,GAAIA,EAAM,KAAK,YAAc,KAAK,QAChC,OAKF,IAAMU,EAASd,EAAY,KAAK,OAAQ,KAAK,YAAaI,EAAK,KAAK,MAAM,EACtEU,IAAW,IAAA,IAAaA,IAAWN,EACrC,KAAK,YAAcJ,EAIrB,KAAK,MAAMI,EAAWJ,CAAG,CAC3B,CAMA,QAA6B,CAC3B,OAAOJ,EAAY,KAAK,OAAQ,KAAK,YAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAC3E,CAMA,QAAQ,EAAyB,CAC/B,KAAK,MAAMQ,EAAW,KAAK,IAAI,CAAC,CAClC,CAOA,MAAc,EAAmB,EAAmB,CAClD,KAAK,YAAcJ,EACnB,IAAMK,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYJ,CAAI,CAAC,EACjEL,EAAU,KAAK,OAAQ,QAASvB,EAAAA,GAAgBiC,EAAS,KAAK,WAAW,CAC3E,CACF,E"}
@@ -1,4 +1,4 @@
1
- import { An as e, _n as t, vn as n, yn as r } from "./constants-zyrqveN4.js";
1
+ import { An as e, Hn as t, jn as n, kn as r } from "./constants-Bwl_YtQi.js";
2
2
  // src/utils/identity.ts
3
3
  var i = {
4
4
  local: () => localStorage,
@@ -41,31 +41,31 @@ function l(e, t, n, r, i) {
41
41
  e[t]().setItem(n, r);
42
42
  });
43
43
  }
44
- function u(e, t, r, i) {
45
- let a = c(e, "local", n, t);
44
+ function u(t, n, r, i) {
45
+ let a = c(t, "local", e, n);
46
46
  if (a) try {
47
47
  let e = JSON.parse(a);
48
48
  return e.id && (i === 0 || r - (e.lastSeenAt ?? 0) < i) ? e.id : void 0;
49
49
  } catch {
50
- t.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
50
+ n.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
51
51
  return;
52
52
  }
53
53
  }
54
- function d(r, a = i, o = t) {
55
- let d = s(r), f = Date.now(), p = s(r), m = u(a, r, f, o) ?? p, h = JSON.stringify({
54
+ function d(n, a = i, o = r) {
55
+ let d = s(n), f = Date.now(), p = s(n), m = u(a, n, f, o) ?? p, h = JSON.stringify({
56
56
  id: m,
57
57
  lastSeenAt: f
58
58
  });
59
- l(a, "local", n, h, r);
60
- let g = c(a, "session", "ui-observability.tab", r) ?? "";
61
- return g || (g = s(r), l(a, "session", e, g, r)), {
59
+ l(a, "local", e, h, n);
60
+ let g = c(a, "session", "ui-observability.tab", n) ?? "";
61
+ return g || (g = s(n), l(a, "session", t, g, n)), {
62
62
  sessionId: m,
63
63
  tabId: g,
64
64
  contextId: d
65
65
  };
66
66
  }
67
- function f(t, n, r) {
68
- l(r, "session", e, t, n);
67
+ function f(e, n, r) {
68
+ l(r, "session", t, e, n);
69
69
  }
70
70
  var p = class {
71
71
  diagnostics;
@@ -73,8 +73,8 @@ var p = class {
73
73
  touchMs;
74
74
  idleMs;
75
75
  lastTouchAt = 0;
76
- constructor(e, n = i, a = r, o = t) {
77
- this.diagnostics = e, this.stores = n, this.touchMs = a, this.idleMs = o;
76
+ constructor(e, t = i, a = n, o = r) {
77
+ this.diagnostics = e, this.stores = t, this.touchMs = a, this.idleMs = o;
78
78
  }
79
79
  touch(e) {
80
80
  let t = Date.now();
@@ -88,15 +88,15 @@ var p = class {
88
88
  restart(e) {
89
89
  this.write(e, Date.now());
90
90
  }
91
- write(e, t) {
92
- this.lastTouchAt = t;
91
+ write(t, n) {
92
+ this.lastTouchAt = n;
93
93
  let r = JSON.stringify({
94
- id: e,
95
- lastSeenAt: t
94
+ id: t,
95
+ lastSeenAt: n
96
96
  });
97
- l(this.stores, "local", n, r, this.diagnostics);
97
+ l(this.stores, "local", e, r, this.diagnostics);
98
98
  }
99
99
  };
100
100
  export { f as a, s as i, p as n, o, a as r, d as s, i as t };
101
101
 
102
- //# sourceMappingURL=identity-DT5VmvXy.js.map
102
+ //# sourceMappingURL=identity-BrQp_5J5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-BrQp_5J5.js","names":["SESSION_ID_KEY","TAB_ID_KEY","SESSION_TOUCH_MS","SESSION_IDLE_MS","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","touchMs","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. 0 means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === 0 || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly touchMs = SESSION_TOUCH_MS,\n private readonly idleMs = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < this.touchMs) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":";;AAwDA,IAAaI,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKC,CAAK;EACpB;EACA,aAAa,MAAQ;GACnB,EAAI,OAAOD,CAAG;EAChB;CACF,IAEME,IAAaJ,kBAAK,IAAI,IAAI,CAAC,GAC3BK,IAAeL,kBAAK,IAAI,IAAI,CAAC;CAEnC,OAAO;EAAE,aAAaI;EAAY,eAAeC;CAAa;AAChE;AAQA,SAAgBC,EAAU,GAA4B;CACpD,IAAMC,IAAQ,IAAI,WAAWC,CAAU;CACvC,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,mBAAoB,YACrE,OAAO,gBAAgBD,CAAK;MAE5B,KAAK,IAAIE,IAAI,GAAGA,IAAID,GAAY,KAC9B,EAAMC,KAAK,KAAK,MAAM,KAAK,OAAO,IAAA,GAAoB;CAG1D,OAAO,MAAM,KAAKF,IAAQ,MAA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