@utk09/ui-observability 0.12.0 → 1.1.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 (523) hide show
  1. package/CHANGELOG.md +280 -10
  2. package/README.md +70 -839
  3. package/dist/{batch-BjQUwjA6.js → batch-D3NHhF9L.js} +4 -4
  4. package/dist/{batch-BjQUwjA6.js.map → batch-D3NHhF9L.js.map} +1 -1
  5. package/dist/{batch-D5LlU4Q9.cjs → batch-DnYRJqhU.cjs} +2 -2
  6. package/dist/{batch-D5LlU4Q9.cjs.map → batch-DnYRJqhU.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +355 -0
  8. package/dist/bus/bus.d.ts +86 -12
  9. package/dist/bus/links.d.cts +132 -0
  10. package/dist/bus/links.d.ts +18 -3
  11. package/dist/bus/validation.d.cts +16 -0
  12. package/dist/bus/validation.d.ts +10 -1
  13. package/dist/bus-B__467mL.cjs +2 -0
  14. package/dist/bus-B__467mL.cjs.map +1 -0
  15. package/dist/bus-dw7T92sO.js +788 -0
  16. package/dist/bus-dw7T92sO.js.map +1 -0
  17. package/dist/capture/console.d.cts +37 -0
  18. package/dist/capture/console.d.ts +1 -1
  19. package/dist/capture/errors.d.cts +32 -0
  20. package/dist/capture/errors.d.ts +1 -1
  21. package/dist/capture/interactions.d.cts +80 -0
  22. package/dist/capture/interactions.d.ts +36 -4
  23. package/dist/capture/lifecycle.d.cts +20 -0
  24. package/dist/capture/lifecycle.d.ts +1 -1
  25. package/dist/capture/long-frames.d.cts +31 -0
  26. package/dist/capture/long-frames.d.ts +1 -1
  27. package/dist/capture/network.d.cts +57 -0
  28. package/dist/capture/network.d.ts +1 -1
  29. package/dist/capture/observed-windows.d.cts +51 -0
  30. package/dist/capture/observed-windows.d.ts +51 -0
  31. package/dist/capture/profiler-frames.d.cts +44 -0
  32. package/dist/capture/profiler-frames.d.ts +1 -1
  33. package/dist/capture/replay-buffer.d.cts +45 -0
  34. package/dist/capture/replay-buffer.d.ts +9 -10
  35. package/dist/capture/replay-upload.d.cts +79 -0
  36. package/dist/capture/replay-upload.d.ts +7 -2
  37. package/dist/capture/replay.d.cts +114 -0
  38. package/dist/capture/replay.d.ts +1 -1
  39. package/dist/capture/reports.d.cts +17 -0
  40. package/dist/capture/reports.d.ts +1 -1
  41. package/dist/capture/resource-timing.d.cts +14 -0
  42. package/dist/capture/resource-timing.d.ts +1 -1
  43. package/dist/capture/server-timing.d.cts +19 -0
  44. package/dist/capture/storm.d.cts +13 -0
  45. package/dist/capture/storm.d.ts +5 -5
  46. package/dist/capture/types.d.cts +128 -0
  47. package/dist/capture/types.d.ts +10 -9
  48. package/dist/capture/unclean-exit.d.cts +31 -0
  49. package/dist/capture/unclean-exit.d.ts +1 -1
  50. package/dist/capture/user-timing.d.cts +22 -0
  51. package/dist/capture/user-timing.d.ts +2 -2
  52. package/dist/capture/web-socket.d.cts +40 -0
  53. package/dist/capture/web-socket.d.ts +3 -3
  54. package/dist/capture/web-vitals.d.cts +40 -0
  55. package/dist/capture/web-vitals.d.ts +1 -1
  56. package/dist/{compression-lD9abCcO.cjs → compression-C0hUHKR-.cjs} +2 -2
  57. package/dist/{compression-lD9abCcO.cjs.map → compression-C0hUHKR-.cjs.map} +1 -1
  58. package/dist/{compression-AJJCMBOa.js → compression-SHPAvS4U.js} +2 -2
  59. package/dist/{compression-AJJCMBOa.js.map → compression-SHPAvS4U.js.map} +1 -1
  60. package/dist/config-CSNcS7OZ.js +558 -0
  61. package/dist/config-CSNcS7OZ.js.map +1 -0
  62. package/dist/config-CybPP5VM.cjs +2 -0
  63. package/dist/config-CybPP5VM.cjs.map +1 -0
  64. package/dist/console-BsM-fSCQ.js +81 -0
  65. package/dist/console-BsM-fSCQ.js.map +1 -0
  66. package/dist/console-Dkxs6IVQ.cjs +2 -0
  67. package/dist/console-Dkxs6IVQ.cjs.map +1 -0
  68. package/dist/constants-BwJDXzj6.js +357 -0
  69. package/dist/constants-BwJDXzj6.js.map +1 -0
  70. package/dist/constants-CtF52hIV.cjs +2 -0
  71. package/dist/constants-CtF52hIV.cjs.map +1 -0
  72. package/dist/constants.d.cts +763 -0
  73. package/dist/constants.d.ts +100 -20
  74. package/dist/core/breadcrumbs.d.cts +54 -0
  75. package/dist/core/breadcrumbs.d.ts +5 -0
  76. package/dist/core/config.d.cts +45 -0
  77. package/dist/core/config.d.ts +30 -2
  78. package/dist/core/context.d.cts +24 -0
  79. package/dist/core/context.d.ts +3 -8
  80. package/dist/core/debug-buffer.d.cts +34 -0
  81. package/dist/core/debug-buffer.d.ts +3 -3
  82. package/dist/core/debug-bundle.d.cts +12 -0
  83. package/dist/core/debug-bundle.d.ts +3 -3
  84. package/dist/core/deferred.d.cts +7 -0
  85. package/dist/core/deferred.d.ts +2 -2
  86. package/dist/core/diagnostics.d.cts +86 -0
  87. package/dist/core/diagnostics.d.ts +1 -1
  88. package/dist/core/drops.d.cts +39 -0
  89. package/dist/core/drops.d.ts +16 -6
  90. package/dist/core/hold-buffer.d.cts +36 -0
  91. package/dist/core/hold-buffer.d.ts +16 -7
  92. package/dist/core/journey.d.cts +148 -0
  93. package/dist/core/journey.d.ts +7 -7
  94. package/dist/core/logger.d.cts +141 -0
  95. package/dist/core/logger.d.ts +23 -30
  96. package/dist/core/measure.d.cts +30 -0
  97. package/dist/core/measure.d.ts +14 -3
  98. package/dist/core/meter.d.cts +78 -0
  99. package/dist/core/meter.d.ts +14 -8
  100. package/dist/core/pipeline.d.cts +227 -0
  101. package/dist/core/pipeline.d.ts +73 -10
  102. package/dist/core/profile-buckets.d.cts +31 -0
  103. package/dist/core/profiler.d.cts +218 -0
  104. package/dist/core/profiler.d.ts +2 -2
  105. package/dist/core/record.d.cts +190 -0
  106. package/dist/core/record.d.ts +44 -12
  107. package/dist/core/remote-rules.d.cts +17 -0
  108. package/dist/core/remote-rules.d.ts +3 -3
  109. package/dist/core/remote-sampling.d.cts +74 -0
  110. package/dist/core/remote-sampling.d.ts +3 -3
  111. package/dist/core/rotation.d.cts +99 -0
  112. package/dist/core/rotation.d.ts +99 -0
  113. package/dist/core/runtime.d.cts +774 -0
  114. package/dist/core/runtime.d.ts +254 -70
  115. package/dist/core/sampling.d.cts +86 -0
  116. package/dist/core/sampling.d.ts +5 -5
  117. package/dist/core/sender.d.cts +161 -0
  118. package/dist/core/sender.d.ts +59 -15
  119. package/dist/core/spans.d.cts +39 -0
  120. package/dist/core/spans.d.ts +1 -1
  121. package/dist/debug-bundle-B2v6Cym-.cjs +2 -0
  122. package/dist/debug-bundle-B2v6Cym-.cjs.map +1 -0
  123. package/dist/debug-bundle-Cs_YWzTa.js +35 -0
  124. package/dist/debug-bundle-Cs_YWzTa.js.map +1 -0
  125. package/dist/defineProperty-X1c4tIPD.cjs +1 -0
  126. package/dist/defineProperty-s2S8BXUc.js +35 -0
  127. package/dist/doctor.cjs +1 -1
  128. package/dist/doctor.cjs.map +1 -1
  129. package/dist/doctor.d.cts +36 -0
  130. package/dist/doctor.d.ts +5 -2
  131. package/dist/doctor.js +119 -87
  132. package/dist/doctor.js.map +1 -1
  133. package/dist/errors-DP2RUm4V.cjs +3 -0
  134. package/dist/errors-DP2RUm4V.cjs.map +1 -0
  135. package/dist/errors-Q3Ng1ciC.js +86 -0
  136. package/dist/errors-Q3Ng1ciC.js.map +1 -0
  137. package/dist/factory-DV17sm2p.js +404 -0
  138. package/dist/factory-DV17sm2p.js.map +1 -0
  139. package/dist/factory-K8O6gpux.cjs +2 -0
  140. package/dist/factory-K8O6gpux.cjs.map +1 -0
  141. package/dist/guards-BlYGRK4l.js +10 -0
  142. package/dist/guards-BlYGRK4l.js.map +1 -0
  143. package/dist/guards-EjG3ahFp.cjs +2 -0
  144. package/dist/guards-EjG3ahFp.cjs.map +1 -0
  145. package/dist/{identity-BrQp_5J5.js → identity-BgtHyY4u.js} +33 -26
  146. package/dist/identity-BgtHyY4u.js.map +1 -0
  147. package/dist/identity-CvuyqZk7.cjs +2 -0
  148. package/dist/identity-CvuyqZk7.cjs.map +1 -0
  149. package/dist/index.cjs +1 -1
  150. package/dist/index.cjs.map +1 -1
  151. package/dist/index.d.cts +301 -0
  152. package/dist/index.d.ts +90 -98
  153. package/dist/index.js +1253 -1555
  154. package/dist/index.js.map +1 -1
  155. package/dist/indexeddb-storage-D4KVcqdD.cjs +2 -0
  156. package/dist/indexeddb-storage-D4KVcqdD.cjs.map +1 -0
  157. package/dist/{indexeddb-storage-DLXQzAGh.js → indexeddb-storage-e-13ZLWm.js} +61 -57
  158. package/dist/indexeddb-storage-e-13ZLWm.js.map +1 -0
  159. package/dist/interactions-Byxf1C82.js +207 -0
  160. package/dist/interactions-Byxf1C82.js.map +1 -0
  161. package/dist/interactions-OK85T-Dk.cjs +2 -0
  162. package/dist/interactions-OK85T-Dk.cjs.map +1 -0
  163. package/dist/{journey-35yCMNFo.js → journey-C93FTYcs.js} +46 -49
  164. package/dist/journey-C93FTYcs.js.map +1 -0
  165. package/dist/journey-nMbob3OB.cjs +2 -0
  166. package/dist/journey-nMbob3OB.cjs.map +1 -0
  167. package/dist/{library-console-BFWEuQsl.cjs → library-console-DJUQzcgM.cjs} +2 -2
  168. package/dist/{library-console-BFWEuQsl.cjs.map → library-console-DJUQzcgM.cjs.map} +1 -1
  169. package/dist/{library-console-Dl_Ly6DQ.js → library-console-DklSmucS.js} +2 -2
  170. package/dist/{library-console-Dl_Ly6DQ.js.map → library-console-DklSmucS.js.map} +1 -1
  171. package/dist/{library-request-nI6pvI6I.js → library-request-UGEwOHpf.js} +2 -2
  172. package/dist/{library-request-nI6pvI6I.js.map → library-request-UGEwOHpf.js.map} +1 -1
  173. package/dist/{library-request-Da-CHKzT.cjs → library-request-kY9iTpIF.cjs} +2 -2
  174. package/dist/{library-request-Da-CHKzT.cjs.map → library-request-kY9iTpIF.cjs.map} +1 -1
  175. package/dist/{lifecycle-CZ6RRXc6.js → lifecycle-B2PlIuQu.js} +21 -29
  176. package/dist/lifecycle-B2PlIuQu.js.map +1 -0
  177. package/dist/lifecycle-DaMdH_X7.cjs +2 -0
  178. package/dist/lifecycle-DaMdH_X7.cjs.map +1 -0
  179. package/dist/log-record-Bmx6etMh.cjs +2 -0
  180. package/dist/log-record-Bmx6etMh.cjs.map +1 -0
  181. package/dist/{log-record-DIA6McNr.js → log-record-DSt2P-Sr.js} +8 -7
  182. package/dist/log-record-DSt2P-Sr.js.map +1 -0
  183. package/dist/{long-frames-430_85Da.js → long-frames-Bamjs1WV.js} +18 -22
  184. package/dist/long-frames-Bamjs1WV.js.map +1 -0
  185. package/dist/long-frames-lhtONgGt.cjs +2 -0
  186. package/dist/long-frames-lhtONgGt.cjs.map +1 -0
  187. package/dist/models/batch.d.cts +57 -0
  188. package/dist/models/batch.d.ts +2 -2
  189. package/dist/models/bus.d.cts +163 -0
  190. package/dist/models/bus.d.ts +28 -3
  191. package/dist/models/config.d.cts +1555 -0
  192. package/dist/models/config.d.ts +377 -261
  193. package/dist/models/drop.d.cts +54 -0
  194. package/dist/models/drop.d.ts +16 -3
  195. package/dist/models/health.d.cts +148 -0
  196. package/dist/models/health.d.ts +108 -12
  197. package/dist/models/log-record.d.cts +61 -0
  198. package/dist/models/metric.d.cts +139 -0
  199. package/dist/models/metric.d.ts +13 -2
  200. package/dist/models/plugin.d.cts +47 -0
  201. package/dist/models/plugin.d.ts +3 -3
  202. package/dist/models/replay.d.cts +60 -0
  203. package/dist/models/serializer.d.cts +25 -0
  204. package/dist/models/serializer.d.ts +4 -2
  205. package/dist/models/storage.d.cts +95 -0
  206. package/dist/models/storage.d.ts +7 -5
  207. package/dist/network-BCn8Gn47.cjs +2 -0
  208. package/dist/network-BCn8Gn47.cjs.map +1 -0
  209. package/dist/{network-C7SkLf4v.js → network-Cg1L2w2r.js} +57 -57
  210. package/dist/network-Cg1L2w2r.js.map +1 -0
  211. package/dist/observed-windows-B3gJkdql.cjs +2 -0
  212. package/dist/observed-windows-B3gJkdql.cjs.map +1 -0
  213. package/dist/observed-windows-BrwaJNlj.js +64 -0
  214. package/dist/observed-windows-BrwaJNlj.js.map +1 -0
  215. package/dist/{otlp-2MCrC3kd.cjs → otlp-CrAWkQdO.cjs} +2 -2
  216. package/dist/{otlp-2MCrC3kd.cjs.map → otlp-CrAWkQdO.cjs.map} +1 -1
  217. package/dist/{otlp-COq033e3.js → otlp-D6dRZyB8.js} +9 -9
  218. package/dist/{otlp-COq033e3.js.map → otlp-D6dRZyB8.js.map} +1 -1
  219. package/dist/{platform-CVewe4wQ.js → platform-8DLhjddo.js} +9 -9
  220. package/dist/{platform-CVewe4wQ.js.map → platform-8DLhjddo.js.map} +1 -1
  221. package/dist/{platform-12uR7kBQ.cjs → platform-BqRc-7RO.cjs} +2 -2
  222. package/dist/{platform-12uR7kBQ.cjs.map → platform-BqRc-7RO.cjs.map} +1 -1
  223. package/dist/{profiler-BVWIOgnq.js → profiler-BaXSqCfz.js} +78 -96
  224. package/dist/profiler-BaXSqCfz.js.map +1 -0
  225. package/dist/profiler-BvWW2kNM.cjs +2 -0
  226. package/dist/profiler-BvWW2kNM.cjs.map +1 -0
  227. package/dist/{profiler-frames-CLXlT_xL.js → profiler-frames-C4ySHN0X.js} +21 -29
  228. package/dist/profiler-frames-C4ySHN0X.js.map +1 -0
  229. package/dist/profiler-frames-DeaBiB-5.cjs +2 -0
  230. package/dist/profiler-frames-DeaBiB-5.cjs.map +1 -0
  231. package/dist/remote-rules-D7L6D_D2.cjs +2 -0
  232. package/dist/remote-rules-D7L6D_D2.cjs.map +1 -0
  233. package/dist/remote-rules-Dq9xe7Qn.js +95 -0
  234. package/dist/remote-rules-Dq9xe7Qn.js.map +1 -0
  235. package/dist/replay-B0M8kWz_.js +310 -0
  236. package/dist/replay-B0M8kWz_.js.map +1 -0
  237. package/dist/replay-QOFBpAXh.cjs +2 -0
  238. package/dist/replay-QOFBpAXh.cjs.map +1 -0
  239. package/dist/{reports-BuXekPOS.js → reports--8APRLa-.js} +25 -30
  240. package/dist/reports--8APRLa-.js.map +1 -0
  241. package/dist/reports-ojuMKGO7.cjs +2 -0
  242. package/dist/reports-ojuMKGO7.cjs.map +1 -0
  243. package/dist/{resource-timing-CXGHwFRD.js → resource-timing-BzR05rE-.js} +20 -23
  244. package/dist/resource-timing-BzR05rE-.js.map +1 -0
  245. package/dist/resource-timing-pAG3ZhB5.cjs +2 -0
  246. package/dist/resource-timing-pAG3ZhB5.cjs.map +1 -0
  247. package/dist/response-body-BWvwKQ2p.js +331 -0
  248. package/dist/response-body-BWvwKQ2p.js.map +1 -0
  249. package/dist/response-body-CKEJ5itk.cjs +3 -0
  250. package/dist/response-body-CKEJ5itk.cjs.map +1 -0
  251. package/dist/rotation-BylN1B9e.js +93 -0
  252. package/dist/rotation-BylN1B9e.js.map +1 -0
  253. package/dist/rotation-E2eKClIs.cjs +2 -0
  254. package/dist/rotation-E2eKClIs.cjs.map +1 -0
  255. package/dist/sampling-B46LW0cy.cjs +2 -0
  256. package/dist/sampling-B46LW0cy.cjs.map +1 -0
  257. package/dist/sampling-zXA6r-Nw.js +63 -0
  258. package/dist/sampling-zXA6r-Nw.js.map +1 -0
  259. package/dist/{sanitize-CNmsD9r3.js → sanitize-DjnR6RXR.js} +2 -2
  260. package/dist/sanitize-DjnR6RXR.js.map +1 -0
  261. package/dist/{sanitize-ChLn97Ch.cjs → sanitize-Qj6LuZqp.cjs} +2 -2
  262. package/dist/sanitize-Qj6LuZqp.cjs.map +1 -0
  263. package/dist/sender-Bdp-TAS4.js +979 -0
  264. package/dist/sender-Bdp-TAS4.js.map +1 -0
  265. package/dist/sender-DR7ZycZY.cjs +2 -0
  266. package/dist/sender-DR7ZycZY.cjs.map +1 -0
  267. package/dist/storage/context-storage.d.cts +90 -0
  268. package/dist/storage/context-storage.d.ts +5 -5
  269. package/dist/storage/emergency-queue.d.cts +27 -0
  270. package/dist/storage/emergency-queue.d.ts +4 -4
  271. package/dist/storage/eviction.d.cts +40 -0
  272. package/dist/storage/eviction.d.ts +1 -1
  273. package/dist/storage/factory.d.cts +21 -0
  274. package/dist/storage/factory.d.ts +3 -3
  275. package/dist/storage/gap.d.cts +20 -0
  276. package/dist/storage/gap.d.ts +3 -3
  277. package/dist/storage/idb-driver.d.cts +93 -0
  278. package/dist/storage/idb-driver.d.ts +1 -1
  279. package/dist/storage/indexeddb-storage.d.cts +97 -0
  280. package/dist/storage/indexeddb-storage.d.ts +12 -4
  281. package/dist/storage/keys.d.cts +17 -0
  282. package/dist/storage/keys.d.ts +2 -2
  283. package/dist/storage/local-storage.d.cts +139 -0
  284. package/dist/storage/local-storage.d.ts +11 -4
  285. package/dist/storage/memory-storage.d.cts +73 -0
  286. package/dist/storage/memory-storage.d.ts +4 -3
  287. package/dist/storage/persistence.d.cts +8 -0
  288. package/dist/storage/persistence.d.ts +2 -2
  289. package/dist/storage/stored-context.d.cts +34 -0
  290. package/dist/storage/stored-context.d.ts +34 -0
  291. package/dist/stored-context-BOu54M8Y.cjs +2 -0
  292. package/dist/stored-context-BOu54M8Y.cjs.map +1 -0
  293. package/dist/stored-context-CSttrAsw.js +51 -0
  294. package/dist/stored-context-CSttrAsw.js.map +1 -0
  295. package/dist/storm-BHgI12iS.cjs +2 -0
  296. package/dist/storm-BHgI12iS.cjs.map +1 -0
  297. package/dist/storm-DKlpv0FL.js +9 -0
  298. package/dist/storm-DKlpv0FL.js.map +1 -0
  299. package/dist/transport/compression.d.cts +7 -0
  300. package/dist/transport/custom-transport.d.cts +22 -0
  301. package/dist/transport/custom-transport.d.ts +6 -5
  302. package/dist/transport/errors.d.cts +31 -0
  303. package/dist/transport/exit-flush.d.cts +135 -0
  304. package/dist/transport/exit-flush.d.ts +30 -13
  305. package/dist/transport/headers.d.cts +8 -0
  306. package/dist/transport/headers.d.ts +2 -2
  307. package/dist/transport/http-transport.d.cts +116 -0
  308. package/dist/transport/http-transport.d.ts +20 -8
  309. package/dist/transport/memory-transport.d.cts +30 -0
  310. package/dist/transport/memory-transport.d.ts +2 -2
  311. package/dist/transport/response-body.d.cts +49 -0
  312. package/dist/transport/response-body.d.ts +49 -0
  313. package/dist/transport/retry-engine.d.cts +129 -0
  314. package/dist/transport/retry-engine.d.ts +27 -9
  315. package/dist/transport/serializers/ecs.d.cts +3 -0
  316. package/dist/transport/serializers/ecs.d.ts +1 -1
  317. package/dist/transport/serializers/otlp-metrics.d.cts +3 -0
  318. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  319. package/dist/transport/serializers/otlp-traces.d.cts +3 -0
  320. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  321. package/dist/transport/serializers/otlp.d.cts +47 -0
  322. package/dist/transport/serializers/otlp.d.ts +2 -2
  323. package/dist/transport/serializers/select.d.cts +38 -0
  324. package/dist/transport/serializers/select.d.ts +5 -5
  325. package/dist/transport/status-transport.d.cts +129 -0
  326. package/dist/transport/status-transport.d.ts +25 -8
  327. package/dist/transport/worker-client.d.cts +23 -0
  328. package/dist/transport/worker-client.d.ts +12 -3
  329. package/dist/transport/worker-entry.d.cts +5 -0
  330. package/dist/transport/worker-entry.d.ts +1 -1
  331. package/dist/transport/worker-protocol.d.cts +38 -0
  332. package/dist/transport/worker-protocol.d.ts +4 -2
  333. package/dist/transport/worker-server.d.cts +3 -0
  334. package/dist/transport/worker-server.d.ts +1 -1
  335. package/dist/transport/worker-transport.d.cts +10 -0
  336. package/dist/transport/worker-transport.d.ts +5 -4
  337. package/dist/types-BAerHgCq.js.map +1 -1
  338. package/dist/types-C7WNpnG1.cjs.map +1 -1
  339. package/dist/unclean-exit-BYPYYkQ5.cjs +2 -0
  340. package/dist/unclean-exit-BYPYYkQ5.cjs.map +1 -0
  341. package/dist/{unclean-exit-Cob_jyTv.js → unclean-exit-BcOB8A2e.js} +23 -30
  342. package/dist/unclean-exit-BcOB8A2e.js.map +1 -0
  343. package/dist/{user-timing-DgHubxCI.js → user-timing-4KIJ74Vi.js} +15 -17
  344. package/dist/user-timing-4KIJ74Vi.js.map +1 -0
  345. package/dist/user-timing-BsU2wQKE.cjs +2 -0
  346. package/dist/user-timing-BsU2wQKE.cjs.map +1 -0
  347. package/dist/utils/console.d.cts +36 -0
  348. package/dist/utils/console.d.ts +4 -4
  349. package/dist/utils/deadline.d.cts +14 -0
  350. package/dist/utils/error-like.d.cts +25 -0
  351. package/dist/utils/fixed-window.d.cts +25 -0
  352. package/dist/utils/global-scope.d.cts +20 -0
  353. package/dist/utils/guards.d.cts +14 -0
  354. package/dist/utils/guards.d.ts +8 -0
  355. package/dist/utils/identity.d.cts +114 -0
  356. package/dist/utils/identity.d.ts +8 -4
  357. package/dist/utils/library-console.d.cts +11 -0
  358. package/dist/utils/library-request.d.cts +24 -0
  359. package/dist/utils/lock.d.cts +24 -0
  360. package/dist/utils/lock.d.ts +1 -1
  361. package/dist/utils/openfin.d.cts +48 -0
  362. package/dist/utils/patch.d.cts +9 -0
  363. package/dist/utils/platform.d.cts +62 -0
  364. package/dist/utils/platform.d.ts +2 -2
  365. package/dist/utils/sanitize.d.cts +52 -0
  366. package/dist/utils/sanitize.d.ts +1 -1
  367. package/dist/utils/sequence.d.cts +10 -0
  368. package/dist/utils/tracing.d.cts +158 -0
  369. package/dist/utils/tracing.d.ts +11 -4
  370. package/dist/utils/unref.d.cts +9 -0
  371. package/dist/web-socket-Cs1ZbmmN.cjs +2 -0
  372. package/dist/{web-socket-DthJuSAg.js.map → web-socket-Cs1ZbmmN.cjs.map} +1 -1
  373. package/dist/{web-socket-DthJuSAg.js → web-socket-Zg0hj1LB.js} +23 -28
  374. package/dist/web-socket-Zg0hj1LB.js.map +1 -0
  375. package/dist/{web-vitals-CsGCWnUr.js → web-vitals-4pWACwaR.js} +15 -21
  376. package/dist/web-vitals-4pWACwaR.js.map +1 -0
  377. package/dist/web-vitals-__X7t4pj.cjs +2 -0
  378. package/dist/web-vitals-__X7t4pj.cjs.map +1 -0
  379. package/dist/{worker-protocol-B0_8rWy5.js → worker-protocol-CYpAbrVl.js} +14 -11
  380. package/dist/worker-protocol-CYpAbrVl.js.map +1 -0
  381. package/dist/worker-protocol-DFYXIFus.cjs +2 -0
  382. package/dist/worker-protocol-DFYXIFus.cjs.map +1 -0
  383. package/dist/worker-server--yGTadTA.cjs +2 -0
  384. package/dist/worker-server--yGTadTA.cjs.map +1 -0
  385. package/dist/worker-server-BokySIII.js +94 -0
  386. package/dist/worker-server-BokySIII.js.map +1 -0
  387. package/dist/worker-transport-BdEvh_-a.cjs +2 -0
  388. package/dist/worker-transport-BdEvh_-a.cjs.map +1 -0
  389. package/dist/worker-transport-JK-Fby9J.js +194 -0
  390. package/dist/worker-transport-JK-Fby9J.js.map +1 -0
  391. package/llms.txt +400 -0
  392. package/package.json +65 -49
  393. package/dist/bus-D_7pd7RN.cjs +0 -2
  394. package/dist/bus-D_7pd7RN.cjs.map +0 -1
  395. package/dist/bus-ecxUNTja.js +0 -660
  396. package/dist/bus-ecxUNTja.js.map +0 -1
  397. package/dist/console-CLz_PvFn.cjs +0 -2
  398. package/dist/console-CLz_PvFn.cjs.map +0 -1
  399. package/dist/console-cwgHKXvM.js +0 -82
  400. package/dist/console-cwgHKXvM.js.map +0 -1
  401. package/dist/constants-Bwl_YtQi.js +0 -349
  402. package/dist/constants-Bwl_YtQi.js.map +0 -1
  403. package/dist/constants-DakMxVB2.cjs +0 -2
  404. package/dist/constants-DakMxVB2.cjs.map +0 -1
  405. package/dist/context-storage-BjzeBSxH.cjs +0 -2
  406. package/dist/context-storage-BjzeBSxH.cjs.map +0 -1
  407. package/dist/context-storage-BzkoHzkQ.js +0 -51
  408. package/dist/context-storage-BzkoHzkQ.js.map +0 -1
  409. package/dist/debug-bundle-BOdYmCeV.js +0 -32
  410. package/dist/debug-bundle-BOdYmCeV.js.map +0 -1
  411. package/dist/debug-bundle-Ex4L_LSP.cjs +0 -2
  412. package/dist/debug-bundle-Ex4L_LSP.cjs.map +0 -1
  413. package/dist/emergency-queue-B9WZxanZ.js +0 -67
  414. package/dist/emergency-queue-B9WZxanZ.js.map +0 -1
  415. package/dist/emergency-queue-HBpL5r3V.cjs +0 -2
  416. package/dist/emergency-queue-HBpL5r3V.cjs.map +0 -1
  417. package/dist/errors-D6bwgJtO.js +0 -92
  418. package/dist/errors-D6bwgJtO.js.map +0 -1
  419. package/dist/errors-DCOCRdSi.cjs +0 -3
  420. package/dist/errors-DCOCRdSi.cjs.map +0 -1
  421. package/dist/factory-DLFDjdLv.cjs +0 -2
  422. package/dist/factory-DLFDjdLv.cjs.map +0 -1
  423. package/dist/factory-e9Qo3K0z.js +0 -276
  424. package/dist/factory-e9Qo3K0z.js.map +0 -1
  425. package/dist/guards-Cidk71ME.js +0 -7
  426. package/dist/guards-Cidk71ME.js.map +0 -1
  427. package/dist/guards-nJ70syPt.cjs +0 -2
  428. package/dist/guards-nJ70syPt.cjs.map +0 -1
  429. package/dist/identity-BlvlgjrU.cjs +0 -2
  430. package/dist/identity-BlvlgjrU.cjs.map +0 -1
  431. package/dist/identity-BrQp_5J5.js.map +0 -1
  432. package/dist/indexeddb-storage-CtLvZH1r.cjs +0 -2
  433. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +0 -1
  434. package/dist/indexeddb-storage-DLXQzAGh.js.map +0 -1
  435. package/dist/interactions-B6z2I4tU.js +0 -119
  436. package/dist/interactions-B6z2I4tU.js.map +0 -1
  437. package/dist/interactions-P6pz08Jn.cjs +0 -2
  438. package/dist/interactions-P6pz08Jn.cjs.map +0 -1
  439. package/dist/journey-35yCMNFo.js.map +0 -1
  440. package/dist/journey-DAGh5h9k.cjs +0 -2
  441. package/dist/journey-DAGh5h9k.cjs.map +0 -1
  442. package/dist/keys-BHhw_0Wh.cjs +0 -2
  443. package/dist/keys-BHhw_0Wh.cjs.map +0 -1
  444. package/dist/keys-BU9j5YqW.js +0 -16
  445. package/dist/keys-BU9j5YqW.js.map +0 -1
  446. package/dist/lifecycle-BGGOcN4N.cjs +0 -2
  447. package/dist/lifecycle-BGGOcN4N.cjs.map +0 -1
  448. package/dist/lifecycle-CZ6RRXc6.js.map +0 -1
  449. package/dist/log-record-D7bA1RPb.cjs +0 -2
  450. package/dist/log-record-D7bA1RPb.cjs.map +0 -1
  451. package/dist/log-record-DIA6McNr.js.map +0 -1
  452. package/dist/long-frames-430_85Da.js.map +0 -1
  453. package/dist/long-frames-Dd8tsi2U.cjs +0 -2
  454. package/dist/long-frames-Dd8tsi2U.cjs.map +0 -1
  455. package/dist/models/stats.d.ts +0 -11
  456. package/dist/network-C7SkLf4v.js.map +0 -1
  457. package/dist/network-pEX3PAJv.cjs +0 -2
  458. package/dist/network-pEX3PAJv.cjs.map +0 -1
  459. package/dist/profiler-BVWIOgnq.js.map +0 -1
  460. package/dist/profiler-eVCknCzS.cjs +0 -2
  461. package/dist/profiler-eVCknCzS.cjs.map +0 -1
  462. package/dist/profiler-frames-CLXlT_xL.js.map +0 -1
  463. package/dist/profiler-frames-Dg2OebB2.cjs +0 -2
  464. package/dist/profiler-frames-Dg2OebB2.cjs.map +0 -1
  465. package/dist/remote-rules-BJGDJGwA.js +0 -98
  466. package/dist/remote-rules-BJGDJGwA.js.map +0 -1
  467. package/dist/remote-rules-CJD3ToVk.cjs +0 -2
  468. package/dist/remote-rules-CJD3ToVk.cjs.map +0 -1
  469. package/dist/replay-0zAJv9T3.js +0 -338
  470. package/dist/replay-0zAJv9T3.js.map +0 -1
  471. package/dist/replay-DomJpXqW.cjs +0 -2
  472. package/dist/replay-DomJpXqW.cjs.map +0 -1
  473. package/dist/reports-BsbqmP8h.cjs +0 -2
  474. package/dist/reports-BsbqmP8h.cjs.map +0 -1
  475. package/dist/reports-BuXekPOS.js.map +0 -1
  476. package/dist/resource-timing-CXGHwFRD.js.map +0 -1
  477. package/dist/resource-timing-DkycFGDa.cjs +0 -2
  478. package/dist/resource-timing-DkycFGDa.cjs.map +0 -1
  479. package/dist/sampling-Dd0wllyq.cjs +0 -2
  480. package/dist/sampling-Dd0wllyq.cjs.map +0 -1
  481. package/dist/sampling-UUDbi3K0.js +0 -60
  482. package/dist/sampling-UUDbi3K0.js.map +0 -1
  483. package/dist/sanitize-CNmsD9r3.js.map +0 -1
  484. package/dist/sanitize-ChLn97Ch.cjs.map +0 -1
  485. package/dist/select-CTk-K5mG.cjs +0 -3
  486. package/dist/select-CTk-K5mG.cjs.map +0 -1
  487. package/dist/select-DPv_j6wq.js +0 -270
  488. package/dist/select-DPv_j6wq.js.map +0 -1
  489. package/dist/sender-15zEsZpr.js +0 -857
  490. package/dist/sender-15zEsZpr.js.map +0 -1
  491. package/dist/sender-Bfpv9tad.cjs +0 -2
  492. package/dist/sender-Bfpv9tad.cjs.map +0 -1
  493. package/dist/storage-BA9RqRO-.cjs +0 -2
  494. package/dist/storage-BA9RqRO-.cjs.map +0 -1
  495. package/dist/storage-DZwed89z.js +0 -16
  496. package/dist/storage-DZwed89z.js.map +0 -1
  497. package/dist/storm-BTSNTIWI.js +0 -9
  498. package/dist/storm-BTSNTIWI.js.map +0 -1
  499. package/dist/storm-D0_qZOEg.cjs +0 -2
  500. package/dist/storm-D0_qZOEg.cjs.map +0 -1
  501. package/dist/unclean-exit-ClGzrc2A.cjs +0 -2
  502. package/dist/unclean-exit-ClGzrc2A.cjs.map +0 -1
  503. package/dist/unclean-exit-Cob_jyTv.js.map +0 -1
  504. package/dist/user-timing-CdYqx3PF.cjs +0 -2
  505. package/dist/user-timing-CdYqx3PF.cjs.map +0 -1
  506. package/dist/user-timing-DgHubxCI.js.map +0 -1
  507. package/dist/utils/timer.d.ts +0 -19
  508. package/dist/web-socket-BTuvYoJI.cjs +0 -2
  509. package/dist/web-socket-BTuvYoJI.cjs.map +0 -1
  510. package/dist/web-vitals-Ch5BpDmo.cjs +0 -2
  511. package/dist/web-vitals-Ch5BpDmo.cjs.map +0 -1
  512. package/dist/web-vitals-CsGCWnUr.js.map +0 -1
  513. package/dist/worker-protocol-B0_8rWy5.js.map +0 -1
  514. package/dist/worker-protocol-BjzFORfq.cjs +0 -2
  515. package/dist/worker-protocol-BjzFORfq.cjs.map +0 -1
  516. package/dist/worker-server-4en-Lt-3.cjs +0 -2
  517. package/dist/worker-server-4en-Lt-3.cjs.map +0 -1
  518. package/dist/worker-server-Cne9MX9I.js +0 -83
  519. package/dist/worker-server-Cne9MX9I.js.map +0 -1
  520. package/dist/worker-transport-B-GF4Aqn.cjs +0 -2
  521. package/dist/worker-transport-B-GF4Aqn.cjs.map +0 -1
  522. package/dist/worker-transport-C3SjJAEC.js +0 -200
  523. package/dist/worker-transport-C3SjJAEC.js.map +0 -1
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./batch-D5LlU4Q9.cjs"),n=require("./keys-BHhw_0Wh.cjs");function r(e){return Array.isArray(e.records)&&e.records.some(t.r)}var i=class{howMany;isAudit;plain=[];audit=[];constructor(e,t){this.howMany=e,this.isAudit=t}add(e){return this.isAudit(e)?this.audit.length<this.howMany&&this.audit.push(e):this.plain.push(e),this.plain.length<this.howMany}picked(){return[...this.plain,...this.audit].slice(0,this.howMany)}};function a(e,t,n){let r=new i(t,n);for(let t of e)if(!r.add(t))break;return r.picked()}function o(e,t,n,r){return e.batches+=n,e.records+=r,e.reason=t,{batches:n,records:r,reason:t}}function s(e,t,n,r){n.batches!==0&&(e.report(`storage.evicted`,`The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`,{...n}),t?.(n,r))}function c(e,t){let n=t.length,r=Number(e.slice(n,n+14));return Number.isFinite(r)?r:null}var l=class{limits;diagnostics;onGap;prefix;name=e.Rn;constructor(t,n,r,i=e.E){this.limits=t,this.diagnostics=n,this.onGap=r,this.prefix=i}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`))await this.prune();else if(this.evictForQuota(),!this.write(e,`localStorage refused a batch even after evicting`)){let t={batches:1,records:e.records.length,reason:`quota`};s(this.diagnostics,this.onGap,t,[e])}}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}takeContext(e,t){let n=[];for(let r of this.batches()){if(n.length>=t)break;r.routingContextId===e&&n.push(r)}return Promise.resolve(n)}countContext(e){let t=0;for(let n of this.batches())n.routingContextId===e&&t++;return Promise.resolve(t)}*batches(){for(let e of this.keys()){let t=this.read(e);t===null?this.removeKey(e):yield t}}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=[],r=[];for(let t of this.keys()){let i=c(t,this.prefix);i===null||i<e?n.push(t):r.push(t)}this.drop(t,`expired`,[...this.entries(n)]);let i=r.length-this.limits.maxBatches;return i>0&&this.drop(t,`over_capacity`,this.evictable(r,i)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(n.t(this.prefix,e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`},n=Math.ceil(e.length/4);this.drop(t,`quota`,this.evictable(e,n))}evictable(e,t){return a(this.entries(e),t,e=>e.batch!==null&&r(e.batch))}*entries(e){for(let t of e)yield{key:t,batch:this.read(t)}}drop(e,n,r){if(r.length===0)return;let i=[];for(let{key:e,batch:t}of r)this.removeKey(e),t&&i.push(t);let a=o(e,n,r.length,t.n(i));s(this.diagnostics,this.onGap,a,i)}read(e){let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!n)return null;let r=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(n));return r===void 0?null:t.i(r)?r:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return n.n(this.prefix,this.diagnostics)}},u=class{limits;onGap;name=e.zn;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){let t=this.batches.findIndex(t=>t.id===e.id);t>=0?this.batches[t]=e:this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}takeContext(e,t){return Promise.resolve(this.batches.filter(t=>t.routingContextId===e).slice(0,t))}countContext(e){return Promise.resolve(this.batches.filter(t=>t.routingContextId===e).length)}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),this.report(t,`expired`,n);let i=this.batches.length-this.limits.maxBatches;if(i>0){let e=a(this.batches,i,r);this.batches=this.batches.filter(t=>!e.includes(t)),this.report(t,`over_capacity`,e)}return Promise.resolve(t)}report(e,n,r){if(r.length===0)return;let i=o(e,n,r.length,t.n(r));this.onGap?.(i,r)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}};function d(t){return t?`${e.Pn}:${t}`:e.Pn}var f=t=>({name:e.Bn,save:e=>(t?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),Promise.resolve()),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()});function p(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function m(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e.Vn,`1`),localStorage.removeItem(e.Vn),!0))===!0}async function h(e,t,n,r,i,a=``){if(e===`none`)return f(i);if(e===`memory`)return new u(n,i);if(e===`indexeddb`||e===`auto`){if(p(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-CtLvZH1r.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new u(n,i)}return m(r)?new l(n,r,i,a?`ui-observability:namespaced:${encodeURIComponent(a)}:batch:`:void 0):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new u(n,i))}exports.createStorage=h,exports.i=r,exports.n=s,exports.r=i,exports.storageName=d,exports.t=o;
2
- //# sourceMappingURL=factory-DLFDjdLv.cjs.map
@@ -1 +0,0 @@
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,QAXnB,MAA8B,CAAC,EAG/B,MAA8B,CAAC,EAM/B,YACE,EACA,EACA,CAFiB,KAAA,QAAAC,EACA,KAAA,QAAAC,CAChB,CAOH,IAAI,EAAkB,CAOpB,OANK,KAAK,QAAQC,CAAI,EAEX,KAAK,MAAM,OAAS,KAAK,SAClC,KAAK,MAAM,KAAKA,CAAI,EAFpB,KAAK,MAAM,KAAKA,CAAI,EAKf,KAAK,MAAM,OAAS,KAAK,OAClC,CAMA,QAAc,CACZ,MAAO,CAAC,GAAG,KAAK,MAAO,GAAG,KAAK,KAAK,CAAC,CAAC,MAAM,EAAG,KAAK,OAAO,CAC7D,CACF,EASA,SAAgBC,EACd,EACA,EACA,EACK,CACL,IAAMC,EAAO,IAAIL,EAAaC,EAASC,CAAO,EAE9C,IAAK,IAAMC,KAAQG,EACjB,GAAI,CAACD,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AQ,CAC/B,GAOA,SAASiD,EAAa,EAAmC,CAUvD,OATkBnC,EAAY,MAC5B,sBACA,4CAEmB,WAAiD,WACtB,IAIzC,IAAc,EACvB,CAOA,SAASoC,EAAgB,EAAmC,CAW1D,OAVepC,EAAY,MACzB,sBACA,+DAEE,aAAa,QAAQnB,EAAAA,GAAmB,GAAG,EAC3C,aAAa,WAAWA,EAAAA,EAAiB,EAClC,GAIJ,IAAW,EACpB,CAYA,eAAsBwD,EACpB,EACA,EACA,EACA,EACA,EACA,EAAY,GACa,CACzB,GAAIC,IAAA,OACF,OAAOJ,EAAKjC,CAAK,EAEnB,GAAIqC,IAAA,SACF,OAAO,IAAIX,EAAclB,EAAQR,CAAK,EAGxC,GAAIqC,IAAA,aAAuCA,IAAa,OAAQ,CAC9D,GAAIH,EAAanC,CAAW,EAAG,CAG7B,IAAMuC,EAAU,MAAMvC,EAAY,WAChC,sBACA,wCACA,SAAY,CACV,GAAM,CAAE,oBAAqB,MAAA,QAAA,QAAA,CAAA,CAAA,SAAA,QAAM,kCAAA,CAAA,EAC7BwC,EAAU,IAAIC,EAAiBC,EAAQjC,EAAQT,EAAaC,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,276 +0,0 @@
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
- import { n as l, t as u } from "./keys-BU9j5YqW.js";
4
- // src/storage/eviction.ts
5
- function d(e) {
6
- return Array.isArray(e.records) && e.records.some(c);
7
- }
8
- var f = class {
9
- howMany;
10
- isAudit;
11
- plain = [];
12
- audit = [];
13
- constructor(e, t) {
14
- this.howMany = e, this.isAudit = t;
15
- }
16
- add(e) {
17
- return this.isAudit(e) ? this.audit.length < this.howMany && this.audit.push(e) : this.plain.push(e), this.plain.length < this.howMany;
18
- }
19
- picked() {
20
- return [...this.plain, ...this.audit].slice(0, this.howMany);
21
- }
22
- };
23
- function p(e, t, n) {
24
- let r = new f(t, n);
25
- for (let t of e) if (!r.add(t)) break;
26
- return r.picked();
27
- }
28
- // src/storage/gap.ts
29
- function m(e, t, n, r) {
30
- return e.batches += n, e.records += r, e.reason = t, {
31
- batches: n,
32
- records: r,
33
- reason: t
34
- };
35
- }
36
- function h(e, t, n, r) {
37
- n.batches !== 0 && (e.report("storage.evicted", `The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`, { ...n }), t?.(n, r));
38
- }
39
- // src/storage/local-storage.ts
40
- function g(e, t) {
41
- let n = t.length, r = Number(e.slice(n, n + 14));
42
- return Number.isFinite(r) ? r : null;
43
- }
44
- var _ = class {
45
- limits;
46
- diagnostics;
47
- onGap;
48
- prefix;
49
- name = r;
50
- constructor(e, n, r, i = t) {
51
- this.limits = e, this.diagnostics = n, this.onGap = r, this.prefix = i;
52
- }
53
- async save(e) {
54
- if (this.write(e, "localStorage refused a batch, evicting the oldest")) await this.prune();
55
- else if (this.evictForQuota(), !this.write(e, "localStorage refused a batch even after evicting")) {
56
- let t = {
57
- batches: 1,
58
- records: e.records.length,
59
- reason: "quota"
60
- };
61
- h(this.diagnostics, this.onGap, t, [e]);
62
- }
63
- }
64
- take(e) {
65
- let t = [];
66
- for (let n of this.keys().slice(0, e)) {
67
- let e = this.read(n);
68
- e === null ? this.removeKey(n) : t.push(e);
69
- }
70
- return Promise.resolve(t);
71
- }
72
- takeContext(e, t) {
73
- let n = [];
74
- for (let r of this.batches()) {
75
- if (n.length >= t) break;
76
- r.routingContextId === e && n.push(r);
77
- }
78
- return Promise.resolve(n);
79
- }
80
- countContext(e) {
81
- let t = 0;
82
- for (let n of this.batches()) n.routingContextId === e && t++;
83
- return Promise.resolve(t);
84
- }
85
- *batches() {
86
- for (let e of this.keys()) {
87
- let t = this.read(e);
88
- t === null ? this.removeKey(e) : yield t;
89
- }
90
- }
91
- remove(e) {
92
- let t = this.keyOf(e);
93
- return t !== null && this.removeKey(t), Promise.resolve();
94
- }
95
- bumpAttempts(e, t) {
96
- let n = this.keyOf(e);
97
- if (n === null) return Promise.resolve();
98
- let r = this.read(n);
99
- return r === null || (r.attempts = t, this.diagnostics.guard("storage.degraded", "The library could not update the attempt count.", () => {
100
- localStorage.setItem(n, JSON.stringify(r));
101
- })), Promise.resolve();
102
- }
103
- prune() {
104
- let e = Date.now() - this.limits.maxAgeMs, t = {
105
- batches: 0,
106
- records: 0,
107
- reason: "expired"
108
- }, n = [], r = [];
109
- for (let t of this.keys()) {
110
- let i = g(t, this.prefix);
111
- i === null || i < e ? n.push(t) : r.push(t);
112
- }
113
- this.drop(t, "expired", [...this.entries(n)]);
114
- let i = r.length - this.limits.maxBatches;
115
- return i > 0 && this.drop(t, "over_capacity", this.evictable(r, i)), Promise.resolve(t);
116
- }
117
- count() {
118
- return Promise.resolve(this.keys().length);
119
- }
120
- clear() {
121
- return this.evict(this.keys()), Promise.resolve();
122
- }
123
- close() {
124
- return Promise.resolve();
125
- }
126
- write(e, t) {
127
- return this.diagnostics.guard("storage.quota_exceeded", t, () => (localStorage.setItem(u(this.prefix, e), JSON.stringify(e)), !0)) === !0;
128
- }
129
- evictForQuota() {
130
- let e = this.keys(), t = {
131
- batches: 0,
132
- records: 0,
133
- reason: "quota"
134
- }, n = Math.ceil(e.length / 4);
135
- this.drop(t, "quota", this.evictable(e, n));
136
- }
137
- evictable(e, t) {
138
- return p(this.entries(e), t, (e) => e.batch !== null && d(e.batch));
139
- }
140
- *entries(e) {
141
- for (let t of e) yield {
142
- key: t,
143
- batch: this.read(t)
144
- };
145
- }
146
- drop(e, t, n) {
147
- if (n.length === 0) return;
148
- let r = [];
149
- for (let { key: e, batch: t } of n) this.removeKey(e), t && r.push(t);
150
- let i = m(e, t, n.length, s(r));
151
- h(this.diagnostics, this.onGap, i, r);
152
- }
153
- read(e) {
154
- let t = this.diagnostics.guard("storage.unavailable", "The library could not read a stored batch.", () => localStorage.getItem(e));
155
- if (!t) return null;
156
- let n = this.diagnostics.guard("storage.degraded", "A stored batch is corrupt. The library removed it.", () => JSON.parse(t));
157
- return n === void 0 ? null : o(n) ? n : (this.diagnostics.report("storage.degraded", "A stored entry is not a batch. The library dropped it."), null);
158
- }
159
- keyOf(e) {
160
- return this.keys().find((t) => t.endsWith(`.${e}`)) ?? null;
161
- }
162
- evict(e) {
163
- for (let t of e) this.removeKey(t);
164
- }
165
- removeKey(e) {
166
- this.diagnostics.guard("storage.degraded", "The library could not remove a stored batch.", () => {
167
- localStorage.removeItem(e);
168
- });
169
- }
170
- keys() {
171
- return l(this.prefix, this.diagnostics);
172
- }
173
- }, v = class {
174
- limits;
175
- onGap;
176
- name = a;
177
- batches = [];
178
- constructor(e, t) {
179
- this.limits = e, this.onGap = t;
180
- }
181
- async save(e) {
182
- let t = this.batches.findIndex((t) => t.id === e.id);
183
- t >= 0 ? this.batches[t] = e : this.batches.push(e), await this.prune();
184
- }
185
- take(e) {
186
- return Promise.resolve(this.batches.slice(0, e));
187
- }
188
- takeContext(e, t) {
189
- return Promise.resolve(this.batches.filter((t) => t.routingContextId === e).slice(0, t));
190
- }
191
- countContext(e) {
192
- return Promise.resolve(this.batches.filter((t) => t.routingContextId === e).length);
193
- }
194
- remove(e) {
195
- return this.batches = this.batches.filter((t) => t.id !== e), Promise.resolve();
196
- }
197
- bumpAttempts(e, t) {
198
- let n = this.batches.find((t) => t.id === e);
199
- return n && (n.attempts = t), Promise.resolve();
200
- }
201
- prune() {
202
- let e = Date.now() - this.limits.maxAgeMs, t = {
203
- batches: 0,
204
- records: 0,
205
- reason: "expired"
206
- }, n = this.batches.filter((t) => t.createdAt < e);
207
- this.batches = this.batches.filter((t) => t.createdAt >= e), this.report(t, "expired", n);
208
- let r = this.batches.length - this.limits.maxBatches;
209
- if (r > 0) {
210
- let e = p(this.batches, r, d);
211
- this.batches = this.batches.filter((t) => !e.includes(t)), this.report(t, "over_capacity", e);
212
- }
213
- return Promise.resolve(t);
214
- }
215
- report(e, t, n) {
216
- if (n.length === 0) return;
217
- let r = m(e, t, n.length, s(n));
218
- this.onGap?.(r, n);
219
- }
220
- count() {
221
- return Promise.resolve(this.batches.length);
222
- }
223
- clear() {
224
- return this.batches = [], Promise.resolve();
225
- }
226
- close() {
227
- return this.batches = [], Promise.resolve();
228
- }
229
- };
230
- // src/storage/factory.ts
231
- function y(e) {
232
- return e ? `${n}:${e}` : n;
233
- }
234
- var b = (t) => ({
235
- name: e,
236
- save: (e) => (t?.({
237
- batches: 1,
238
- records: e.records.length,
239
- reason: "not_stored"
240
- }, [e]), Promise.resolve()),
241
- take: () => Promise.resolve([]),
242
- remove: () => Promise.resolve(),
243
- bumpAttempts: () => Promise.resolve(),
244
- prune: () => Promise.resolve({
245
- batches: 0,
246
- records: 0,
247
- reason: "expired"
248
- }),
249
- count: () => Promise.resolve(0),
250
- clear: () => Promise.resolve(),
251
- close: () => Promise.resolve()
252
- });
253
- function x(e) {
254
- return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
255
- }
256
- function S(e) {
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
- }
259
- async function C(e, t, n, r, i, a = "") {
260
- if (e === "none") return b(i);
261
- if (e === "memory") return new v(n, i);
262
- if (e === "indexeddb" || e === "auto") {
263
- if (x(r)) {
264
- let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
265
- let { IndexedDbStorage: e } = await import("./indexeddb-storage-DLXQzAGh.js"), a = new e(t, n, r, i);
266
- return await a.open(), a;
267
- });
268
- if (e) return e;
269
- }
270
- if (e === "indexeddb") return r.report("storage.degraded", "IndexedDB is not available. The library uses memory storage instead."), new v(n, i);
271
- }
272
- return S(r) ? new _(n, r, i, a ? `ui-observability:namespaced:${encodeURIComponent(a)}:batch:` : void 0) : (r.report("storage.degraded", "No persistent storage is available. The library keeps undelivered records in memory only."), new v(n, i));
273
- }
274
- export { C as createStorage, d as i, h as n, f as r, y as storageName, m as t };
275
-
276
- //# sourceMappingURL=factory-e9Qo3K0z.js.map
@@ -1 +0,0 @@
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,IAAI,GAAkB;EAOpB,OANK,KAAK,QAAQC,CAAI,IAEX,KAAK,MAAM,SAAS,KAAK,WAClC,KAAK,MAAM,KAAKA,CAAI,IAFpB,KAAK,MAAM,KAAKA,CAAI,GAKf,KAAK,MAAM,SAAS,KAAK;CAClC;CAMA,SAAc;EACZ,OAAO,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,KAAK,OAAO;CAC7D;AACF;AASA,SAAgBC,EACd,GACA,GACA,GACK;CACL,IAAMC,IAAO,IAAIL,EAAaC,GAASC,CAAO;CAE9C,KAAK,IAAMC,KAAQG,GACjB,IAAI,CAACD,EAAK,IAAIF,CAAI,GAChB;CAIJ,OAAOE,EAAK,OAAO;AACrB;;AC/DA,SAAgBE,EACd,GACA,GACA,GACA,GACa;CAIb,OAHA,EAAO,WAAWC,GAClB,EAAO,WAAWC,GAClB,EAAO,SAASC,GACT;EAAE;EAAS;EAAS;CAAO;AACpC;AASA,SAAgBC,EACd,GACA,GACA,GACA,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iB,GAClC,GAIJ,MAAW;AACpB;AAYA,eAAsB2D,EACpB,GACA,GACA,GACA,GACA,GACA,IAAY,IACa;CACzB,IAAIC,MAAA,QACF,OAAOJ,EAAKjC,CAAK;CAEnB,IAAIqC,MAAA,UACF,OAAO,IAAIX,EAAclB,GAAQR,CAAK;CAGxC,IAAIqC,MAAA,eAAuCA,MAAa,QAAQ;EAC9D,IAAIH,EAAanC,CAAW,GAAG;GAG7B,IAAMuC,IAAU,MAAMvC,EAAY,WAChC,uBACA,yCACA,YAAY;IACV,IAAM,EAAE,wBAAqB,MAAM,OAAO,oCACpCwC,IAAU,IAAIC,EAAiBC,GAAQjC,GAAQT,GAAaC,CAAK;IAKvE,OADA,MAAMuC,EAAQ,KAAK,GACZA;GACT,CACF;GACA,IAAID,GACF,OAAOA;EAEX;EAEA,IAAID,MAAA,aAKF,OAJAtC,EAAY,OACV,oBACA,sEACF,GACO,IAAI2B,EAAclB,GAAQR,CAAK;CAE1C;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,7 +0,0 @@
1
- // src/utils/guards.ts
2
- function e(e) {
3
- return typeof e == "object" && !!e && !Array.isArray(e);
4
- }
5
- export { e as t };
6
-
7
- //# sourceMappingURL=guards-Cidk71ME.js.map
@@ -1 +0,0 @@
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,2 +0,0 @@
1
- function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
- //# sourceMappingURL=guards-nJ70syPt.cjs.map
@@ -1 +0,0 @@
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 +0,0 @@
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
@@ -1 +0,0 @@
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,CACA,OAAON,EAAA,EAAwB,CACjC,CAUA,SAASO,EACP,EACA,EACA,EACA,EACe,CACf,OACED,EAAY,MAAM,sBAAuB,8BAA8BE,EAAM,cAC3EC,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E,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 +0,0 @@
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;EACl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KAAK,MAAMI,GAAWJ,CAAG;CAC3B;CAMA,SAA6B;EAC3B,OAAOJ,EAAY,KAAK,QAAQ,KAAK,aAAa,KAAK,IAAI,GAAG,KAAK,MAAM;CAC3E;CAMA,QAAQ,GAAyB;EAC/B,KAAK,MAAMQ,GAAW,KAAK,IAAI,CAAC;CAClC;CAOA,MAAc,GAAmB,GAAmB;EAClD,KAAK,cAAcJ;EACnB,IAAMK,IAAU,KAAK,UAAU;GAAE,IAAID;GAAW,YAAYJ;EAAI,CAAC;EACjE,EAAU,KAAK,QAAQ,SAAS3B,GAAgBgC,GAAS,KAAK,WAAW;CAC3E;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./batch-D5LlU4Q9.cjs"),n=require("./factory-DLFDjdLv.cjs");function r(e){return e.error??Error(`The IndexedDB request failed.`)}function i(e){return new Promise((t,n)=>{e.onsuccess=()=>{t(e.result)},e.onerror=()=>{n(r(e))}})}var a=class{name;connection=null;constructor(e){this.name=e}async put(e){await i((await this.store(`readwrite`)).put(e))}async takeContext(e,t){let n=await this.store(`readonly`),r=IDBKeyRange.bound([e,0],[e,2**53-1]);return i(n.index(`routingContext`).getAll(r,t))}async countContext(e){return i((await this.store(`readonly`)).index(`routingContext`).count(IDBKeyRange.bound([e,0],[e,2**53-1])))}async takeOldest(t){return i((await this.store(`readonly`)).index(e.ht).getAll(null,t))}async walkOldest(t){let n=(await this.store(`readonly`)).index(e.ht).openCursor();await new Promise((e,i)=>{n.onsuccess=()=>{let r=n.result;r===null||!t(r.value)?e():r.continue()},n.onerror=()=>{i(r(n))}})}async takeBefore(t){let n=await this.store(`readonly`),r=IDBKeyRange.upperBound(t,!0);return i(n.index(e.ht).getAll(r))}async delete(e){await i((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>i(t.delete(e))))}async bumpAttempts(e,t){let n=await this.store(`readwrite`),r=await i(n.get(e));r!==void 0&&await i(n.put({...r,attempts:t}))}async count(){return i((await this.store(`readonly`)).count())}async clear(){await i((await this.store(`readwrite`)).clear())}async ready(){await this.open()}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.gt,t).objectStore(e.gt)}open(){let t=this.connection;if(t!==null)return t;let n=new Promise((t,n)=>{let i=indexedDB.open(this.name,12),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.gt,{keyPath:`id`}).createIndex(e.ht,e.ht);let n=i.transaction.objectStore(e.gt);n.indexNames.contains(`routingContext`)||n.createIndex(`routingContext`,[`routingContextId`,`createdAt`])},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},t(e))},i.onerror=()=>{n(r(i))},i.onblocked=()=>{a=!0,n(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=n.catch(e=>{throw this.connection=null,e}),this.connection}},o=class{limits;diagnostics;onGap;name=e.Ln;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new a(e)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e),await this.prune()}catch(r){if(r instanceof Error&&r.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full. The library removes the oldest batches.`);let r=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove old batches after a full disk.`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));if(r){let e=t.n(r),i={batches:r.length,records:e,reason:`quota`};n.n(this.diagnostics,this.onGap,i,r)}if(await this.diagnostics.guardAsync(`storage.degraded`,`The library could not write the batch after it removed old batches.`,async()=>(await this.db.put(e),!0))!==!0){let t={batches:1,records:e.records.length,reason:`quota`};n.n(this.diagnostics,this.onGap,t,[e])}return}this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},r),this.onGap?.({batches:1,records:e.records.length,reason:`not_stored`},[e])}}async takeContext(e,t){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not query the context partition.`,()=>this.db.takeContext(e,Math.min(t,4294967295)))??[]}async countContext(e){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not count the context partition.`,()=>this.db.countContext(e))??0}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(Math.min(e,4294967295)))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not delete a batch.`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not update the attempt count.`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),this.addGap(e,`expired`,n));let r=await this.db.count();if(r>this.limits.maxBatches){let t=await this.evictOldest(r-this.limits.maxBatches);this.addGap(e,`over_capacity`,t)}}),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the stored batches.`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not clear the stored batches.`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not close the database.`,()=>this.db.close())}addGap(e,r,i){let a=n.t(e,r,i.length,t.n(i));n.n(this.diagnostics,this.onGap,a,i)}async evictOldest(e){let t=new n.r(e,n.i);await this.db.walkOldest(e=>t.add(e));let r=t.picked();return await this.db.deleteMany(r.map(e=>e.id)),r}};exports.IndexedDbStorage=o;
2
- //# sourceMappingURL=indexeddb-storage-CtLvZH1r.cjs.map