@utk09/ui-observability 0.11.0 → 1.0.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 (557) hide show
  1. package/CHANGELOG.md +481 -0
  2. package/README.md +73 -669
  3. package/bin/uiobs.mjs +1 -1
  4. package/dist/{batch-CL9uWYY3.js → batch-CXmPmTse.js} +3 -3
  5. package/dist/batch-CXmPmTse.js.map +1 -0
  6. package/dist/{batch-C8OcWR2L.cjs → batch-mmPigCpi.cjs} +2 -2
  7. package/dist/batch-mmPigCpi.cjs.map +1 -0
  8. package/dist/bus/bus.d.cts +331 -0
  9. package/dist/bus/bus.d.ts +108 -57
  10. package/dist/bus/links.d.cts +132 -0
  11. package/dist/bus/links.d.ts +22 -7
  12. package/dist/bus/validation.d.cts +16 -0
  13. package/dist/bus/validation.d.ts +11 -2
  14. package/dist/bus-C39wspFV.js +775 -0
  15. package/dist/bus-C39wspFV.js.map +1 -0
  16. package/dist/bus-_EaOVPGq.cjs +2 -0
  17. package/dist/bus-_EaOVPGq.cjs.map +1 -0
  18. package/dist/capture/console.d.cts +37 -0
  19. package/dist/capture/console.d.ts +11 -11
  20. package/dist/capture/errors.d.cts +32 -0
  21. package/dist/capture/errors.d.ts +7 -7
  22. package/dist/capture/interactions.d.cts +48 -0
  23. package/dist/capture/interactions.d.ts +15 -15
  24. package/dist/capture/lifecycle.d.cts +20 -0
  25. package/dist/capture/lifecycle.d.ts +4 -4
  26. package/dist/capture/long-frames.d.cts +31 -0
  27. package/dist/capture/long-frames.d.ts +7 -7
  28. package/dist/capture/network.d.cts +57 -0
  29. package/dist/capture/network.d.ts +18 -18
  30. package/dist/capture/profiler-frames.d.cts +44 -0
  31. package/dist/capture/profiler-frames.d.ts +44 -0
  32. package/dist/capture/replay-buffer.d.cts +45 -0
  33. package/dist/capture/replay-buffer.d.ts +45 -0
  34. package/dist/capture/replay-upload.d.cts +79 -0
  35. package/dist/capture/replay-upload.d.ts +79 -0
  36. package/dist/capture/replay.d.cts +114 -0
  37. package/dist/capture/replay.d.ts +114 -0
  38. package/dist/capture/reports.d.cts +17 -0
  39. package/dist/capture/reports.d.ts +3 -3
  40. package/dist/capture/resource-timing.d.cts +14 -0
  41. package/dist/capture/resource-timing.d.ts +2 -2
  42. package/dist/capture/server-timing.d.cts +19 -0
  43. package/dist/capture/server-timing.d.ts +3 -3
  44. package/dist/capture/storm.d.cts +13 -0
  45. package/dist/capture/storm.d.ts +7 -7
  46. package/dist/capture/types.d.cts +128 -0
  47. package/dist/capture/types.d.ts +54 -41
  48. package/dist/capture/unclean-exit.d.cts +31 -0
  49. package/dist/capture/unclean-exit.d.ts +9 -9
  50. package/dist/capture/user-timing.d.cts +22 -0
  51. package/dist/capture/user-timing.d.ts +4 -4
  52. package/dist/capture/web-socket.d.cts +40 -0
  53. package/dist/capture/web-socket.d.ts +14 -14
  54. package/dist/capture/web-vitals.d.cts +40 -0
  55. package/dist/capture/web-vitals.d.ts +21 -8
  56. package/dist/compression-CvED_Jel.cjs +2 -0
  57. package/dist/compression-CvED_Jel.cjs.map +1 -0
  58. package/dist/compression-tVtXwVjX.js +11 -0
  59. package/dist/compression-tVtXwVjX.js.map +1 -0
  60. package/dist/config-DUs7uHHt.cjs +2 -0
  61. package/dist/config-DUs7uHHt.cjs.map +1 -0
  62. package/dist/config-SgQcCP1_.js +560 -0
  63. package/dist/config-SgQcCP1_.js.map +1 -0
  64. package/dist/console-BGgGnjSi.js +81 -0
  65. package/dist/console-BGgGnjSi.js.map +1 -0
  66. package/dist/console-CSZ5_Vx5.cjs +2 -0
  67. package/dist/console-CSZ5_Vx5.cjs.map +1 -0
  68. package/dist/constants-CUyd9cTZ.js +357 -0
  69. package/dist/constants-CUyd9cTZ.js.map +1 -0
  70. package/dist/constants-CqdJhTxH.cjs +2 -0
  71. package/dist/constants-CqdJhTxH.cjs.map +1 -0
  72. package/dist/constants.d.cts +751 -0
  73. package/dist/constants.d.ts +231 -116
  74. package/dist/core/breadcrumbs.d.cts +54 -0
  75. package/dist/core/breadcrumbs.d.ts +21 -15
  76. package/dist/core/config.d.cts +45 -0
  77. package/dist/core/config.d.ts +33 -5
  78. package/dist/core/context.d.cts +24 -0
  79. package/dist/core/context.d.ts +8 -13
  80. package/dist/core/debug-buffer.d.cts +34 -0
  81. package/dist/core/debug-buffer.d.ts +13 -13
  82. package/dist/core/debug-bundle.d.cts +12 -0
  83. package/dist/core/debug-bundle.d.ts +6 -6
  84. package/dist/core/deferred.d.cts +7 -0
  85. package/dist/core/deferred.d.ts +4 -4
  86. package/dist/core/diagnostics.d.cts +86 -0
  87. package/dist/core/diagnostics.d.ts +25 -22
  88. package/dist/core/drops.d.cts +39 -0
  89. package/dist/core/drops.d.ts +22 -12
  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 +28 -29
  94. package/dist/core/logger.d.cts +141 -0
  95. package/dist/core/logger.d.ts +45 -51
  96. package/dist/core/measure.d.cts +30 -0
  97. package/dist/core/measure.d.ts +21 -10
  98. package/dist/core/meter.d.cts +78 -0
  99. package/dist/core/meter.d.ts +38 -28
  100. package/dist/core/pipeline.d.cts +227 -0
  101. package/dist/core/pipeline.d.ts +114 -50
  102. package/dist/core/profile-buckets.d.cts +31 -0
  103. package/dist/core/profile-buckets.d.ts +31 -0
  104. package/dist/core/profiler.d.cts +218 -0
  105. package/dist/core/profiler.d.ts +218 -0
  106. package/dist/core/record.d.cts +190 -0
  107. package/dist/core/record.d.ts +67 -35
  108. package/dist/core/remote-rules.d.cts +17 -0
  109. package/dist/core/remote-rules.d.ts +7 -7
  110. package/dist/core/remote-sampling.d.cts +74 -0
  111. package/dist/core/remote-sampling.d.ts +24 -23
  112. package/dist/core/rotation.d.cts +75 -0
  113. package/dist/core/rotation.d.ts +75 -0
  114. package/dist/core/runtime.d.cts +765 -0
  115. package/dist/core/runtime.d.ts +430 -186
  116. package/dist/core/sampling.d.cts +86 -0
  117. package/dist/core/sampling.d.ts +22 -22
  118. package/dist/core/sender.d.cts +161 -0
  119. package/dist/core/sender.d.ts +80 -34
  120. package/dist/core/spans.d.cts +39 -0
  121. package/dist/core/spans.d.ts +6 -6
  122. package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
  123. package/dist/deadline-C4ccAuk5.js.map +1 -0
  124. package/dist/deadline-CUGbto-y.cjs +2 -0
  125. package/dist/deadline-CUGbto-y.cjs.map +1 -0
  126. package/dist/debug-bundle-BXIlwDKM.cjs +2 -0
  127. package/dist/debug-bundle-BXIlwDKM.cjs.map +1 -0
  128. package/dist/debug-bundle-CRpYV_ui.js +35 -0
  129. package/dist/debug-bundle-CRpYV_ui.js.map +1 -0
  130. package/dist/defineProperty-X1c4tIPD.cjs +1 -0
  131. package/dist/defineProperty-s2S8BXUc.js +35 -0
  132. package/dist/doctor.cjs +1 -1
  133. package/dist/doctor.cjs.map +1 -1
  134. package/dist/doctor.d.cts +36 -0
  135. package/dist/doctor.d.ts +19 -6
  136. package/dist/doctor.js +180 -53
  137. package/dist/doctor.js.map +1 -1
  138. package/dist/error-like-B11pB4aL.js.map +1 -1
  139. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  140. package/dist/errors-BE_EZV7Q.js +86 -0
  141. package/dist/errors-BE_EZV7Q.js.map +1 -0
  142. package/dist/errors-CNPbesMs.cjs +3 -0
  143. package/dist/errors-CNPbesMs.cjs.map +1 -0
  144. package/dist/factory-CTi0Is3F.js +404 -0
  145. package/dist/factory-CTi0Is3F.js.map +1 -0
  146. package/dist/factory-hRrH32v5.cjs +2 -0
  147. package/dist/factory-hRrH32v5.cjs.map +1 -0
  148. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  149. package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
  150. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  151. package/dist/global-scope-D9I8s-oN.js.map +1 -1
  152. package/dist/guards-BlYGRK4l.js +10 -0
  153. package/dist/guards-BlYGRK4l.js.map +1 -0
  154. package/dist/guards-EjG3ahFp.cjs +2 -0
  155. package/dist/guards-EjG3ahFp.cjs.map +1 -0
  156. package/dist/{identity-DT5VmvXy.js → identity-DdhKgrpk.js} +11 -15
  157. package/dist/identity-DdhKgrpk.js.map +1 -0
  158. package/dist/identity-DlWRIuwy.cjs +2 -0
  159. package/dist/identity-DlWRIuwy.cjs.map +1 -0
  160. package/dist/index.cjs +1 -1
  161. package/dist/index.cjs.map +1 -1
  162. package/dist/index.d.cts +300 -0
  163. package/dist/index.d.ts +165 -141
  164. package/dist/index.js +1283 -1468
  165. package/dist/index.js.map +1 -1
  166. package/dist/indexeddb-storage-CL9uqBCy.cjs +2 -0
  167. package/dist/indexeddb-storage-CL9uqBCy.cjs.map +1 -0
  168. package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-GHdl0t8A.js} +51 -47
  169. package/dist/indexeddb-storage-GHdl0t8A.js.map +1 -0
  170. package/dist/interactions-CUkzK8sR.cjs +2 -0
  171. package/dist/interactions-CUkzK8sR.cjs.map +1 -0
  172. package/dist/{interactions-DTgKy_6K.js → interactions-DiFvCosX.js} +41 -49
  173. package/dist/interactions-DiFvCosX.js.map +1 -0
  174. package/dist/journey-B4Adltjm.cjs +2 -0
  175. package/dist/journey-B4Adltjm.cjs.map +1 -0
  176. package/dist/{journey-CuJrHzEg.js → journey-D2_sia57.js} +51 -53
  177. package/dist/journey-D2_sia57.js.map +1 -0
  178. package/dist/{library-console-C1m6g1BR.js → library-console-Btrzt814.js} +2 -2
  179. package/dist/library-console-Btrzt814.js.map +1 -0
  180. package/dist/{library-console-D2GY9Or6.cjs → library-console-CPW6bvZH.cjs} +2 -2
  181. package/dist/library-console-CPW6bvZH.cjs.map +1 -0
  182. package/dist/{library-request-BQBT9N9Q.js → library-request-BJ9PLRaD.js} +2 -2
  183. package/dist/library-request-BJ9PLRaD.js.map +1 -0
  184. package/dist/{library-request-1BX_UlaX.cjs → library-request-D7OvTxZV.cjs} +2 -2
  185. package/dist/library-request-D7OvTxZV.cjs.map +1 -0
  186. package/dist/{lifecycle-BaKx_-32.js → lifecycle-22CUCrc9.js} +21 -29
  187. package/dist/lifecycle-22CUCrc9.js.map +1 -0
  188. package/dist/lifecycle-IaAm1mOC.cjs +2 -0
  189. package/dist/lifecycle-IaAm1mOC.cjs.map +1 -0
  190. package/dist/{log-record-CAoGBBf3.js → log-record-BNiLfqtL.js} +8 -7
  191. package/dist/log-record-BNiLfqtL.js.map +1 -0
  192. package/dist/log-record-CkivuiEl.cjs +2 -0
  193. package/dist/log-record-CkivuiEl.cjs.map +1 -0
  194. package/dist/long-frames-BUUbXd-B.cjs +2 -0
  195. package/dist/long-frames-BUUbXd-B.cjs.map +1 -0
  196. package/dist/long-frames-DNFaRnC3.js +62 -0
  197. package/dist/long-frames-DNFaRnC3.js.map +1 -0
  198. package/dist/models/batch.d.cts +57 -0
  199. package/dist/models/batch.d.ts +16 -17
  200. package/dist/models/bus.d.cts +158 -0
  201. package/dist/models/bus.d.ts +46 -26
  202. package/dist/models/config.d.cts +1540 -0
  203. package/dist/models/config.d.ts +692 -405
  204. package/dist/models/drop.d.cts +54 -0
  205. package/dist/models/drop.d.ts +29 -14
  206. package/dist/models/health.d.cts +148 -0
  207. package/dist/models/health.d.ts +119 -23
  208. package/dist/models/log-record.d.cts +61 -0
  209. package/dist/models/log-record.d.ts +13 -14
  210. package/dist/models/metric.d.cts +139 -0
  211. package/dist/models/metric.d.ts +94 -18
  212. package/dist/models/plugin.d.cts +47 -0
  213. package/dist/models/plugin.d.ts +16 -16
  214. package/dist/models/replay.d.cts +60 -0
  215. package/dist/models/replay.d.ts +60 -0
  216. package/dist/models/serializer.d.cts +23 -0
  217. package/dist/models/serializer.d.ts +3 -4
  218. package/dist/models/storage.d.cts +95 -0
  219. package/dist/models/storage.d.ts +17 -14
  220. package/dist/network-CGMLQ-mA.cjs +2 -0
  221. package/dist/network-CGMLQ-mA.cjs.map +1 -0
  222. package/dist/{network-DBNwApoF.js → network-on2zZT6H.js} +57 -57
  223. package/dist/network-on2zZT6H.js.map +1 -0
  224. package/dist/openfin-Bxelt0yg.js.map +1 -1
  225. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  226. package/dist/otlp-BENHf3g9.cjs +2 -0
  227. package/dist/otlp-BENHf3g9.cjs.map +1 -0
  228. package/dist/{otlp-BTJdIa6F.js → otlp-DimfrRor.js} +22 -29
  229. package/dist/otlp-DimfrRor.js.map +1 -0
  230. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  231. package/dist/patch-UdPz1ea8.js.map +1 -1
  232. package/dist/{platform-DkcuXwe-.js → platform-BaaFIPCU.js} +8 -8
  233. package/dist/platform-BaaFIPCU.js.map +1 -0
  234. package/dist/{platform-C2Ez5kDc.cjs → platform-CfA3-7sJ.cjs} +2 -2
  235. package/dist/platform-CfA3-7sJ.cjs.map +1 -0
  236. package/dist/profiler-BAZoh7A4.js +292 -0
  237. package/dist/profiler-BAZoh7A4.js.map +1 -0
  238. package/dist/profiler-D4tJpDRc.cjs +2 -0
  239. package/dist/profiler-D4tJpDRc.cjs.map +1 -0
  240. package/dist/profiler-frames-C4xr7KfH.cjs +2 -0
  241. package/dist/profiler-frames-C4xr7KfH.cjs.map +1 -0
  242. package/dist/profiler-frames-cJMx9wNM.js +78 -0
  243. package/dist/profiler-frames-cJMx9wNM.js.map +1 -0
  244. package/dist/remote-rules-Dz9MRAsB.js +95 -0
  245. package/dist/remote-rules-Dz9MRAsB.js.map +1 -0
  246. package/dist/remote-rules-_tY0zj5o.cjs +2 -0
  247. package/dist/remote-rules-_tY0zj5o.cjs.map +1 -0
  248. package/dist/replay-B3gFXIZd.cjs +2 -0
  249. package/dist/replay-B3gFXIZd.cjs.map +1 -0
  250. package/dist/replay-Ds-ANH34.js +310 -0
  251. package/dist/replay-Ds-ANH34.js.map +1 -0
  252. package/dist/reports-BDSe4dFH.cjs +2 -0
  253. package/dist/reports-BDSe4dFH.cjs.map +1 -0
  254. package/dist/{reports-TA-zInnq.js → reports-C-thq-bk.js} +25 -30
  255. package/dist/reports-C-thq-bk.js.map +1 -0
  256. package/dist/resource-timing-C576gFIQ.cjs +2 -0
  257. package/dist/resource-timing-C576gFIQ.cjs.map +1 -0
  258. package/dist/{resource-timing-BLv3EA2A.js → resource-timing-eUl2dNgC.js} +20 -23
  259. package/dist/resource-timing-eUl2dNgC.js.map +1 -0
  260. package/dist/response-body-YdNl-HkR.cjs +3 -0
  261. package/dist/response-body-YdNl-HkR.cjs.map +1 -0
  262. package/dist/response-body-eoSQpLiH.js +331 -0
  263. package/dist/response-body-eoSQpLiH.js.map +1 -0
  264. package/dist/rotation-Cwct4ckk.js +94 -0
  265. package/dist/rotation-Cwct4ckk.js.map +1 -0
  266. package/dist/rotation-D4qUAHAu.cjs +2 -0
  267. package/dist/rotation-D4qUAHAu.cjs.map +1 -0
  268. package/dist/sampling-BlrI8jor.js +63 -0
  269. package/dist/sampling-BlrI8jor.js.map +1 -0
  270. package/dist/sampling-mXt4dstx.cjs +2 -0
  271. package/dist/sampling-mXt4dstx.cjs.map +1 -0
  272. package/dist/{sanitize-6ymPlVvP.js → sanitize-Ba0KqU06.js} +2 -2
  273. package/dist/sanitize-Ba0KqU06.js.map +1 -0
  274. package/dist/{sanitize-BAWzkZt0.cjs → sanitize-DQyiI_KY.cjs} +2 -2
  275. package/dist/sanitize-DQyiI_KY.cjs.map +1 -0
  276. package/dist/sender-BdRuNVhF.cjs +2 -0
  277. package/dist/sender-BdRuNVhF.cjs.map +1 -0
  278. package/dist/sender-Dv8rAmpV.js +979 -0
  279. package/dist/sender-Dv8rAmpV.js.map +1 -0
  280. package/dist/storage/context-storage.d.cts +90 -0
  281. package/dist/storage/context-storage.d.ts +38 -37
  282. package/dist/storage/emergency-queue.d.cts +27 -0
  283. package/dist/storage/emergency-queue.d.ts +13 -13
  284. package/dist/storage/eviction.d.cts +40 -0
  285. package/dist/storage/eviction.d.ts +13 -13
  286. package/dist/storage/factory.d.cts +21 -0
  287. package/dist/storage/factory.d.ts +11 -10
  288. package/dist/storage/gap.d.cts +20 -0
  289. package/dist/storage/gap.d.ts +9 -9
  290. package/dist/storage/idb-driver.d.cts +93 -0
  291. package/dist/storage/idb-driver.d.ts +32 -33
  292. package/dist/storage/indexeddb-storage.d.cts +97 -0
  293. package/dist/storage/indexeddb-storage.d.ts +38 -31
  294. package/dist/storage/keys.d.cts +17 -0
  295. package/dist/storage/keys.d.ts +9 -9
  296. package/dist/storage/local-storage.d.cts +139 -0
  297. package/dist/storage/local-storage.d.ts +49 -42
  298. package/dist/storage/memory-storage.d.cts +73 -0
  299. package/dist/storage/memory-storage.d.ts +25 -25
  300. package/dist/storage/persistence.d.cts +8 -0
  301. package/dist/storage/persistence.d.ts +3 -3
  302. package/dist/storage/stored-context.d.cts +34 -0
  303. package/dist/storage/stored-context.d.ts +34 -0
  304. package/dist/stored-context-B2EzVuYm.js +51 -0
  305. package/dist/stored-context-B2EzVuYm.js.map +1 -0
  306. package/dist/stored-context-CXt7eHZL.cjs +2 -0
  307. package/dist/stored-context-CXt7eHZL.cjs.map +1 -0
  308. package/dist/storm-C-zYSdDX.cjs +2 -0
  309. package/dist/storm-C-zYSdDX.cjs.map +1 -0
  310. package/dist/storm-DjKetLKZ.js +9 -0
  311. package/dist/storm-DjKetLKZ.js.map +1 -0
  312. package/dist/transport/compression.d.cts +7 -0
  313. package/dist/transport/compression.d.ts +2 -2
  314. package/dist/transport/custom-transport.d.cts +22 -0
  315. package/dist/transport/custom-transport.d.ts +6 -5
  316. package/dist/transport/errors.d.cts +31 -0
  317. package/dist/transport/errors.d.ts +7 -7
  318. package/dist/transport/exit-flush.d.cts +135 -0
  319. package/dist/transport/exit-flush.d.ts +62 -45
  320. package/dist/transport/headers.d.cts +8 -0
  321. package/dist/transport/headers.d.ts +4 -4
  322. package/dist/transport/http-transport.d.cts +116 -0
  323. package/dist/transport/http-transport.d.ts +48 -35
  324. package/dist/transport/memory-transport.d.cts +30 -0
  325. package/dist/transport/memory-transport.d.ts +8 -8
  326. package/dist/transport/response-body.d.cts +49 -0
  327. package/dist/transport/response-body.d.ts +49 -0
  328. package/dist/transport/retry-engine.d.cts +129 -0
  329. package/dist/transport/retry-engine.d.ts +62 -43
  330. package/dist/transport/serializers/ecs.d.cts +3 -0
  331. package/dist/transport/serializers/ecs.d.ts +2 -2
  332. package/dist/transport/serializers/otlp-metrics.d.cts +3 -0
  333. package/dist/transport/serializers/otlp-metrics.d.ts +2 -2
  334. package/dist/transport/serializers/otlp-traces.d.cts +3 -0
  335. package/dist/transport/serializers/otlp-traces.d.ts +2 -2
  336. package/dist/transport/serializers/otlp.d.cts +47 -0
  337. package/dist/transport/serializers/otlp.d.ts +18 -18
  338. package/dist/transport/serializers/select.d.cts +38 -0
  339. package/dist/transport/serializers/select.d.ts +11 -11
  340. package/dist/transport/status-transport.d.cts +129 -0
  341. package/dist/transport/status-transport.d.ts +45 -28
  342. package/dist/transport/worker-client.d.cts +23 -0
  343. package/dist/transport/worker-client.d.ts +12 -3
  344. package/dist/transport/worker-entry.d.cts +5 -0
  345. package/dist/transport/worker-entry.d.ts +1 -1
  346. package/dist/transport/worker-protocol.d.cts +38 -0
  347. package/dist/transport/worker-protocol.d.ts +7 -5
  348. package/dist/transport/worker-server.d.cts +3 -0
  349. package/dist/transport/worker-server.d.ts +1 -1
  350. package/dist/transport/worker-transport.d.cts +10 -0
  351. package/dist/transport/worker-transport.d.ts +5 -4
  352. package/dist/types-BAerHgCq.js.map +1 -1
  353. package/dist/types-C7WNpnG1.cjs.map +1 -1
  354. package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-DQD1cT7c.js} +23 -30
  355. package/dist/unclean-exit-DQD1cT7c.js.map +1 -0
  356. package/dist/unclean-exit-py99ApzT.cjs +2 -0
  357. package/dist/unclean-exit-py99ApzT.cjs.map +1 -0
  358. package/dist/unref-CU9Nyz_9.cjs +2 -0
  359. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  360. package/dist/unref-DgHPQeWv.js +7 -0
  361. package/dist/unref-DgHPQeWv.js.map +1 -0
  362. package/dist/{user-timing-_jZIhDKI.js → user-timing-BePqb1uN.js} +18 -18
  363. package/dist/user-timing-BePqb1uN.js.map +1 -0
  364. package/dist/user-timing-D6XTmpuM.cjs +2 -0
  365. package/dist/user-timing-D6XTmpuM.cjs.map +1 -0
  366. package/dist/utils/console.d.cts +36 -0
  367. package/dist/utils/console.d.ts +6 -6
  368. package/dist/utils/deadline.d.cts +14 -0
  369. package/dist/utils/deadline.d.ts +4 -4
  370. package/dist/utils/error-like.d.cts +25 -0
  371. package/dist/utils/error-like.d.ts +7 -7
  372. package/dist/utils/fixed-window.d.cts +25 -0
  373. package/dist/utils/fixed-window.d.ts +9 -8
  374. package/dist/utils/global-scope.d.cts +20 -0
  375. package/dist/utils/global-scope.d.ts +8 -8
  376. package/dist/utils/guards.d.cts +14 -0
  377. package/dist/utils/guards.d.ts +10 -2
  378. package/dist/utils/identity.d.cts +109 -0
  379. package/dist/utils/identity.d.ts +20 -21
  380. package/dist/utils/library-console.d.cts +11 -0
  381. package/dist/utils/library-console.d.ts +4 -4
  382. package/dist/utils/library-request.d.cts +24 -0
  383. package/dist/utils/library-request.d.ts +10 -10
  384. package/dist/utils/lock.d.cts +24 -0
  385. package/dist/utils/lock.d.ts +11 -10
  386. package/dist/utils/openfin.d.cts +48 -0
  387. package/dist/utils/openfin.d.ts +5 -5
  388. package/dist/utils/patch.d.cts +9 -0
  389. package/dist/utils/patch.d.ts +6 -6
  390. package/dist/utils/platform.d.cts +62 -0
  391. package/dist/utils/platform.d.ts +15 -13
  392. package/dist/utils/sanitize.d.cts +52 -0
  393. package/dist/utils/sanitize.d.ts +5 -5
  394. package/dist/utils/sequence.d.cts +10 -0
  395. package/dist/utils/tracing.d.cts +158 -0
  396. package/dist/utils/tracing.d.ts +49 -42
  397. package/dist/utils/unref.d.cts +9 -0
  398. package/dist/utils/unref.d.ts +3 -3
  399. package/dist/web-socket-CoIUBM3C.cjs +2 -0
  400. package/dist/web-socket-CoIUBM3C.cjs.map +1 -0
  401. package/dist/{web-socket-CV7yIMnm.js → web-socket-DSHgDiZ6.js} +23 -28
  402. package/dist/web-socket-DSHgDiZ6.js.map +1 -0
  403. package/dist/web-vitals-4pWACwaR.js +71 -0
  404. package/dist/web-vitals-4pWACwaR.js.map +1 -0
  405. package/dist/web-vitals-__X7t4pj.cjs +2 -0
  406. package/dist/web-vitals-__X7t4pj.cjs.map +1 -0
  407. package/dist/worker-protocol-QbvqNazn.cjs +2 -0
  408. package/dist/worker-protocol-QbvqNazn.cjs.map +1 -0
  409. package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-x074Rpet.js} +14 -11
  410. package/dist/worker-protocol-x074Rpet.js.map +1 -0
  411. package/dist/worker-server-CFe4nvos.cjs +2 -0
  412. package/dist/worker-server-CFe4nvos.cjs.map +1 -0
  413. package/dist/worker-server-iUVSjH8L.js +94 -0
  414. package/dist/worker-server-iUVSjH8L.js.map +1 -0
  415. package/dist/worker-transport-CRAX-09c.cjs +2 -0
  416. package/dist/worker-transport-CRAX-09c.cjs.map +1 -0
  417. package/dist/worker-transport-Dy1KMA7t.js +190 -0
  418. package/dist/worker-transport-Dy1KMA7t.js.map +1 -0
  419. package/llms.txt +397 -0
  420. package/package.json +55 -41
  421. package/dist/batch-C8OcWR2L.cjs.map +0 -1
  422. package/dist/batch-CL9uWYY3.js.map +0 -1
  423. package/dist/bus-BZ0GldpT.js +0 -660
  424. package/dist/bus-BZ0GldpT.js.map +0 -1
  425. package/dist/bus-VWlmM5xs.cjs +0 -2
  426. package/dist/bus-VWlmM5xs.cjs.map +0 -1
  427. package/dist/console-BPZCuSLc.cjs +0 -2
  428. package/dist/console-BPZCuSLc.cjs.map +0 -1
  429. package/dist/console-BeCF7n59.js +0 -82
  430. package/dist/console-BeCF7n59.js.map +0 -1
  431. package/dist/constants-DqKJH_MP.cjs +0 -2
  432. package/dist/constants-DqKJH_MP.cjs.map +0 -1
  433. package/dist/constants-zyrqveN4.js +0 -304
  434. package/dist/constants-zyrqveN4.js.map +0 -1
  435. package/dist/context-storage-BjzeBSxH.cjs +0 -2
  436. package/dist/context-storage-BjzeBSxH.cjs.map +0 -1
  437. package/dist/context-storage-BzkoHzkQ.js +0 -51
  438. package/dist/context-storage-BzkoHzkQ.js.map +0 -1
  439. package/dist/deadline-BOjOxNHj.js.map +0 -1
  440. package/dist/deadline-XSnm95pg.cjs +0 -2
  441. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  442. package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
  443. package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
  444. package/dist/debug-bundle-C7UkHZ-q.js +0 -25
  445. package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
  446. package/dist/emergency-queue-CNTRui5t.cjs +0 -2
  447. package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
  448. package/dist/emergency-queue-Zy6lNafo.js +0 -67
  449. package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
  450. package/dist/errors-Dh7kef0i.js +0 -92
  451. package/dist/errors-Dh7kef0i.js.map +0 -1
  452. package/dist/errors-tfEr48bS.cjs +0 -3
  453. package/dist/errors-tfEr48bS.cjs.map +0 -1
  454. package/dist/factory-BonqI3NL.js +0 -276
  455. package/dist/factory-BonqI3NL.js.map +0 -1
  456. package/dist/factory-CJXVYp0R.cjs +0 -2
  457. package/dist/factory-CJXVYp0R.cjs.map +0 -1
  458. package/dist/guards-Cidk71ME.js +0 -7
  459. package/dist/guards-Cidk71ME.js.map +0 -1
  460. package/dist/guards-nJ70syPt.cjs +0 -2
  461. package/dist/guards-nJ70syPt.cjs.map +0 -1
  462. package/dist/identity-Cxgj6pZX.cjs +0 -2
  463. package/dist/identity-Cxgj6pZX.cjs.map +0 -1
  464. package/dist/identity-DT5VmvXy.js.map +0 -1
  465. package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
  466. package/dist/indexeddb-storage-CIoW21Xd.cjs +0 -2
  467. package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
  468. package/dist/interactions-DTgKy_6K.js.map +0 -1
  469. package/dist/interactions-fEN6FbVo.cjs +0 -2
  470. package/dist/interactions-fEN6FbVo.cjs.map +0 -1
  471. package/dist/journey-CuJrHzEg.js.map +0 -1
  472. package/dist/journey-pffMVMfa.cjs +0 -2
  473. package/dist/journey-pffMVMfa.cjs.map +0 -1
  474. package/dist/keys-BHhw_0Wh.cjs +0 -2
  475. package/dist/keys-BHhw_0Wh.cjs.map +0 -1
  476. package/dist/keys-BU9j5YqW.js +0 -16
  477. package/dist/keys-BU9j5YqW.js.map +0 -1
  478. package/dist/library-console-C1m6g1BR.js.map +0 -1
  479. package/dist/library-console-D2GY9Or6.cjs.map +0 -1
  480. package/dist/library-request-1BX_UlaX.cjs.map +0 -1
  481. package/dist/library-request-BQBT9N9Q.js.map +0 -1
  482. package/dist/lifecycle-2EtUaRpo.cjs +0 -2
  483. package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
  484. package/dist/lifecycle-BaKx_-32.js.map +0 -1
  485. package/dist/log-record-CAoGBBf3.js.map +0 -1
  486. package/dist/log-record-i9zOTkpQ.cjs +0 -2
  487. package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
  488. package/dist/long-frames-BVg4i5SC.cjs +0 -2
  489. package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
  490. package/dist/long-frames-Czk7IupC.js +0 -64
  491. package/dist/long-frames-Czk7IupC.js.map +0 -1
  492. package/dist/models/stats.d.ts +0 -11
  493. package/dist/network-DBNwApoF.js.map +0 -1
  494. package/dist/network-xbbuvG_6.cjs +0 -2
  495. package/dist/network-xbbuvG_6.cjs.map +0 -1
  496. package/dist/otlp-BDvFrLnc.cjs +0 -2
  497. package/dist/otlp-BDvFrLnc.cjs.map +0 -1
  498. package/dist/otlp-BTJdIa6F.js.map +0 -1
  499. package/dist/platform-C2Ez5kDc.cjs.map +0 -1
  500. package/dist/platform-DkcuXwe-.js.map +0 -1
  501. package/dist/remote-rules-Cfb4K-Nl.js +0 -98
  502. package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
  503. package/dist/remote-rules-vzvk7aKf.cjs +0 -2
  504. package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
  505. package/dist/reports-Dk2YhKIh.cjs +0 -2
  506. package/dist/reports-Dk2YhKIh.cjs.map +0 -1
  507. package/dist/reports-TA-zInnq.js.map +0 -1
  508. package/dist/resource-timing-BLv3EA2A.js.map +0 -1
  509. package/dist/resource-timing-Cysw1S1f.cjs +0 -2
  510. package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
  511. package/dist/sampling-C4VV-1MS.js +0 -60
  512. package/dist/sampling-C4VV-1MS.js.map +0 -1
  513. package/dist/sampling-Ckh2yW9k.cjs +0 -2
  514. package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
  515. package/dist/sanitize-6ymPlVvP.js.map +0 -1
  516. package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
  517. package/dist/select-ZF4by-lF.cjs +0 -3
  518. package/dist/select-ZF4by-lF.cjs.map +0 -1
  519. package/dist/select-xtQaenIi.js +0 -270
  520. package/dist/select-xtQaenIi.js.map +0 -1
  521. package/dist/sender-CiMHC9YG.js +0 -856
  522. package/dist/sender-CiMHC9YG.js.map +0 -1
  523. package/dist/sender-D5wBoXA8.cjs +0 -2
  524. package/dist/sender-D5wBoXA8.cjs.map +0 -1
  525. package/dist/storage-BA9RqRO-.cjs +0 -2
  526. package/dist/storage-BA9RqRO-.cjs.map +0 -1
  527. package/dist/storage-DZwed89z.js +0 -16
  528. package/dist/storage-DZwed89z.js.map +0 -1
  529. package/dist/storm-CYi9Swpx.cjs +0 -2
  530. package/dist/storm-CYi9Swpx.cjs.map +0 -1
  531. package/dist/storm-VR024_QN.js +0 -9
  532. package/dist/storm-VR024_QN.js.map +0 -1
  533. package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
  534. package/dist/unclean-exit-DFUN57wY.cjs +0 -2
  535. package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
  536. package/dist/user-timing-C9kfRq3J.cjs +0 -2
  537. package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
  538. package/dist/user-timing-_jZIhDKI.js.map +0 -1
  539. package/dist/utils/timer.d.ts +0 -19
  540. package/dist/web-socket-BWUoqBh8.cjs +0 -2
  541. package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
  542. package/dist/web-socket-CV7yIMnm.js.map +0 -1
  543. package/dist/web-vitals-Bq4WFHQo.js +0 -52
  544. package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
  545. package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
  546. package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
  547. package/dist/worker-protocol-Bai7GAIA.cjs +0 -2
  548. package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
  549. package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
  550. package/dist/worker-server-BrIYkfoa.cjs +0 -2
  551. package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
  552. package/dist/worker-server-Dp5HYm4b.js +0 -83
  553. package/dist/worker-server-Dp5HYm4b.js.map +0 -1
  554. package/dist/worker-transport-Bwej4N2e.cjs +0 -2
  555. package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
  556. package/dist/worker-transport-D6jtgpqN.js +0 -199
  557. package/dist/worker-transport-D6jtgpqN.js.map +0 -1
@@ -0,0 +1,63 @@
1
+ import { Ot as e, a as t, cr as n, f as r, g as i, kt as a, nt as o, ot as s, st as c, zt as l } from "./constants-CUyd9cTZ.js";
2
+ import { t as u } from "./fixed-window-Dq3MLUUv.js";
3
+ import { t as d } from "./defineProperty-s2S8BXUc.js";
4
+ // src/core/sampling.ts
5
+ function f(e) {
6
+ let t = s;
7
+ for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, c);
8
+ return t >>> 0;
9
+ }
10
+ function p(e, t) {
11
+ let n = e.attributes[t];
12
+ return typeof n == "string" ? n : "";
13
+ }
14
+ function m(e, t) {
15
+ let n;
16
+ for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
17
+ value: i,
18
+ length: r.length
19
+ });
20
+ return n;
21
+ }
22
+ function h(e, t) {
23
+ return m(e, t.minLevels)?.value ?? t.minLevel;
24
+ }
25
+ function g(e, t, n) {
26
+ let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = m(e, r), s = n ? m(e, n.rates) : void 0;
27
+ return s && s.length >= (o?.length ?? -1) ? Math.min(s.value, a) : o ? o.value : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
28
+ }
29
+ function _(e, t) {
30
+ return a[e] >= a[t];
31
+ }
32
+ function v(e, t) {
33
+ return t >= 1 ? !0 : t <= 0 ? !1 : f(e) / n < t;
34
+ }
35
+ function y(t, n, r) {
36
+ if (t.aggregated === !0 || t.type === "span" || _(t.level, n.sampling.alwaysSampleFrom) || n.sampling.alwaysSampleTypes.includes(t.type)) return !0;
37
+ let i = g(t.namespace, n, r), o = h(t.namespace, n), s = a[t.level] < a[o];
38
+ return r && s && !e.includes(t.type) && (i = Math.min(i, n.sampling.remoteMaxRate)), v(t.journeyId || t.traceId, i);
39
+ }
40
+ function b(e, n, a = null) {
41
+ return y({
42
+ level: e.severityText,
43
+ type: p(e, i),
44
+ namespace: p(e, t),
45
+ journeyId: p(e, r),
46
+ traceId: e.traceId,
47
+ aggregated: p(e, "log.type") === "metric" && p(e, l.start) !== ""
48
+ }, n, a);
49
+ }
50
+ var x = class {
51
+ constructor() {
52
+ d(this, "window", {
53
+ start: 0,
54
+ count: 0
55
+ });
56
+ }
57
+ allow(e, t = 500, n = o, r = "ERROR") {
58
+ return !_(e.severityText, r) || t === null || u(this.window, t, n);
59
+ }
60
+ };
61
+ export { b as a, v as i, h as n, y as o, m as r, x as t };
62
+
63
+ //# sourceMappingURL=sampling-BlrI8jor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-BlrI8jor.js","names":["LEVEL_BYPASS_TYPES","ATTR_APP_NAMESPACE","UINT32_MAX","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","LEVEL_ORDER","ERROR_STORM_WINDOW_MS","FNV_OFFSET_BASIS","FNV_PRIME","METRIC_KEYS","countInWindow","_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":";;;;AAgCA,SAASY,EAAK,GAAuB;CACnC,IAAIC,IAAIN;CAER,KAAK,IAAIO,IAAI,GAAGA,IAAIC,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWD,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGL,CAAS;CAG5B,OAAOK,MAAM;AACf;AASA,SAASG,EAAS,GAAmB,GAAqB;CACxD,IAAMD,IAAiBE,EAAO,WAAWC;CACzC,OAAO,OAAOH,KAAU,WAAWA,IAAQ;AAC7C;AAiBA,SAAgBI,EACd,GACA,GAC4B;CAC5B,IAAIC;CAEJ,KAAK,IAAM,CAACC,GAAQN,MAAU,OAAO,QAAQO,CAAM,GAGjD,CAFgBC,MAAcF,KAAUE,EAAU,WAAW,GAAGF,EAAO,EAAE,MAE1DA,EAAO,UAAUD,GAAM,UAAU,QAC9C,IAAO;EAAE;EAAO,QAAQC,EAAO;CAAO;CAI1C,OAAOD;AACT;AASA,SAAgBI,EAAS,GAAmB,GAAkC;CAC5E,OAAOL,EAAcI,GAAWE,EAAO,SAAS,CAAC,EAAE,SAASA,EAAO;AACrE;AAUA,SAASC,EAAQ,GAAmB,GAAwB,GAAoC;CAC9F,IAAM,EAAE,UAAO,gBAAa,qBAAkBD,EAAO,UAC/CE,IAAQR,EAAcI,GAAWK,CAAK,GACtCC,IAAaC,IAASX,EAAcI,GAAWO,EAAO,KAAK,IAAI,KAAA;CAYrE,OARID,KAAcA,EAAW,WAAWF,GAAO,UAAU,MAChD,KAAK,IAAIE,EAAW,OAAOE,CAAa,IAG7CJ,IACKA,E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MT,OALA,CAAK2B,EAAUhB,EAAO,cAAckB,CAAI,KAKjCS,MAAU,QAAQlC,EAAc,KAAK,QAAQkC,GAAOC,CAAQ;CACrE;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-CqdJhTxH.cjs"),t=require("./fixed-window-CvESpFYV.cjs"),n=require("./defineProperty-X1c4tIPD.cjs");function r(t){let n=e.ot;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.st);return n>>>0}function i(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function a(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={value:i,length:r.length});return n}function o(e,t){return a(e,t.minLevels)?.value??t.minLevel}function s(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:o}=t.sampling,s=a(e,r),c=n?a(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.value,o):s?s.value:n?.defaultRate===void 0?i:Math.min(n.defaultRate,o)}function c(t,n){return e.kt[t]>=e.kt[n]}function l(t,n){return n>=1?!0:n<=0?!1:r(t)/e.cr<n}function u(t,n,r){if(t.aggregated===!0||t.type===`span`||c(t.level,n.sampling.alwaysSampleFrom)||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=s(t.namespace,n,r),a=o(t.namespace,n),u=e.kt[t.level]<e.kt[a];return r&&u&&!e.Ot.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),l(t.journeyId||t.traceId,i)}function d(t,n,r=null){return u({level:t.severityText,type:i(t,e.g),namespace:i(t,e.a),journeyId:i(t,e.f),traceId:t.traceId,aggregated:i(t,`log.type`)===`metric`&&i(t,e.zt.start)!==``},n,r)}var f=class{constructor(){n.t(this,`window`,{start:0,count:0})}allow(n,r=500,i=e.nt,a=`ERROR`){return!c(n.severityText,a)||r===null||t.t(this.window,r,i)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return f}});
2
+ //# sourceMappingURL=sampling-mXt4dstx.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-mXt4dstx.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","UINT32_MAX","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","require_defineProperty","hash","h","i","value","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","atOrAbove","level","from","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/core/sampling.ts"],"sourcesContent":["// src/core/sampling.ts\n//\n// Samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key, so a whole journey is kept or dropped together and\n// the result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. Returns an empty string for an absent\n * or non-string value, because a forwarded record has only passed a shape check.\n * @param record Log record to read from.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** The prefix's value, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds a namespace's minimum level in the config. The longest matching prefix in\n * `minLevels` wins, and a namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The namespace's minimum level.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate at the point where sampling reads it, so a configure() that lowers the\n // cap takes effect immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Checks whether a level is at or above a threshold level.\n * @param level The record's level. A forwarded record can hold any string.\n * @param from Threshold level.\n * @returns True for a known level that isn't below the threshold.\n */\nfunction atOrAbove(level: string, from: LogLevel): boolean {\n return LEVEL_ORDER[level as LogLevel] >= LEVEL_ORDER[from];\n}\n\n/**\n * Decides whether sampling keeps a key at a rate. The same key always gets the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. Empty when no journey is running. */\n journeyId: string;\n /** Trace ID. Used as the sampling key when no journey is running. */\n traceId: string;\n /** True for a counter or histogram point. Sampling a sum would give a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides whether sampling keeps an entry. Reads fields, not a record, so the caller can\n * drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Records at or above alwaysSampleFrom and aggregated points bypass sampling filters. The\n // runtime samples a span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n atOrAbove(input.level, config.sampling.alwaysSampleFrom)\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type as LogType)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level lets in records below the namespace's config level. Cap those too, or they\n // ship at the config rate. The level doesn't apply to an action or a metric, so don't cap\n // them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Fall back to the trace ID when there is no journey ID. It still groups one operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides whether sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Current remote rules, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Puts a fixed-window limit on the records that bypass sampling because of their level.\n *\n * ErrorCapture already limits auto-captured errors. This class covers what is left, for\n * example application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Records at or above the threshold level admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. Only records at or above `from` are counted.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. 0 allows none, and null means no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @param from Lowest level that bypasses sampling.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit: number | null = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n from: LogLevel = \"ERROR\",\n ): boolean {\n if (!atOrAbove(record.severityText, from)) {\n return true;\n }\n\n // Use a fixed window, not a sliding one, so a quiet period adds no allowance.\n return limit === null || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":"A,gIAgCA,SAASc,EAAK,EAAuB,CACnC,IAAIC,EAAIf,EAAAA,GAER,IAAK,IAAIgB,EAAI,EAAGA,EAAIC,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWD,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGd,EAAAA,EAAS,EAG5B,OAAOc,IAAM,CACf,CASA,SAASG,EAAS,EAAmB,EAAqB,CACxD,IAAMD,EAAiBE,EAAO,WAAWC,GACzC,OAAO,OAAOH,GAAU,SAAWA,EAAQ,EAC7C,CAiBA,SAAgBI,EACd,EACA,EAC4B,CAC5B,IAAIC,EAEJ,IAAK,GAAM,CAACC,EAAQN,KAAU,OAAO,QAAQO,CAAM,GACjCC,IAAcF,GAAUE,EAAU,WAAW,GAAGF,EAAO,EAAE,IAE1DA,EAAO,QAAUD,GAAM,QAAU,MAC9C,EAAO,CAAE,QAAO,OAAQC,EAAO,MAAO,GAI1C,OAAOD,CACT,CASA,SAAgBI,EAAS,EAAmB,EAAkC,CAC5E,OAAOL,EAAcI,EAAWE,EAAO,SAAS,CAAC,EAAE,OAASA,EAAO,QACrE,CAUA,SAASC,EAAQ,EAAmB,EAAwB,EAAoC,CAC9F,GAAM,CAAE,QA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,EAAAA,CAAe,EAC3C,QAASY,EAAO,QAChB,WACED,EAASC,EAAA,UAAqB,IAAM,UAAYD,EAASC,EAAQX,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAmB,EACAK,CACF,CACF,CAQA,IAAaa,EAAb,KAA0B,C,cAExBhC,EAAA,EAAA,KAAA,SAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,CAAA,C,CAU5D,MACE,EACA,EAAA,IACA,EAAWJ,EAAAA,GACX,EAAiB,QACR,CAMT,MALA,CAAK0B,EAAUhB,EAAO,aAAckB,CAAI,GAKjCS,IAAU,MAAQpC,EAAAA,EAAc,KAAK,OAAQoC,EAAOC,CAAQ,CACrE,CACF,E"}
@@ -1,4 +1,4 @@
1
- import "./constants-zyrqveN4.js";
1
+ import "./constants-CUyd9cTZ.js";
2
2
  import { n as e, t } from "./error-like-B11pB4aL.js";
3
3
  // src/utils/sanitize.ts
4
4
  function n(e, t) {
@@ -109,4 +109,4 @@ function l(e) {
109
109
  }
110
110
  export { n as i, a as n, o as r, l as t };
111
111
 
112
- //# sourceMappingURL=sanitize-6ymPlVvP.js.map
112
+ //# sourceMappingURL=sanitize-Ba0KqU06.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize-Ba0KqU06.js","names":["set","toJson","isDataField","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","ERROR_OWN_KEYS","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. Counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The input text, unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively, replacing cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind, or a repeated sibling would show\n // up as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":";;;AA2CA,SAAgBG,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT,IAAME,IAAMC,EAAgBH,EAAM,WAAWC,IAAM,CAAC,CAAC,IAAIA,IAAM,IAAIA;CACnE,OAAO,GAAGD,EAAM,MAAM,GAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,SAASE,CAAG,EAAE;AAC1E;AAOA,SAASC,EAAgB,GAAuB;CAC9C,OAAOC,KAAA,SAA8BA,KAAA;AACvC;AAcA,SAASC,EAAa,GAAwB;CAO5C,OAAO,aANMC,EAAK,YAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,KAAK,IAAIA,EAAK,OAAO,KAEnC,OAAOA,EAAK,aAAc,YAAYA,EAAK,YACvC,IAAIA,EAAK,UAAU,KA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,KAAS1B,EAAO,mBAAmB;IACrC,EAAI,OAAOI,EAAQ,IAAI,OAAOqB,EAAK,SAASC,CAAK,EAAE,cAAcxB,CAAK;IACtE;GACF;GAGA,AAFA,KACA,EAAM,SAASG,EAAcO,CAAG,IAAA,GAChC,EAAIA,KAAOT,EAAKqB,EAAOZ,IAAMZ,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAC7D;EACA,OAAOc;CACT,SAASP,GAAO;EAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,GAEzCE,EAAQ,oBADFK,aAAiB,QAAQA,EAAM,OAAO,QACX,IAAIP,CAAK;CACnD,UAAU;EAGR,EAAK,OAAOX,CAAK;CACnB;AACF;AAOA,SAAgBc,EAAc,GAAuB;CACnD,IAAIsB,IAAQ;CACZ,KAAK,IAAIC,IAAI,GAAGA,IAAIrC,EAAM,QAAQ,KAAK;EACrC,IAAMI,IAAOJ,EAAM,WAAWqC,CAAC;EAC/B,AAAIjC,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAOgC;AACT"}
@@ -1,2 +1,2 @@
1
- require("./constants-DqKJH_MP.cjs");const e=require("./error-like-gGRx2s36.cjs");function t(e,t){if(e.length<=t)return e;let r=n(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,r)}… [truncated ${String(e.length-r)} chars]`}function n(e){return e>=55296&&e<=56319}function r(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function i(e,t,n){return a(e,t,n).value}function a(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:s(e,t,new WeakSet,0,r),bytes:r.bytes}}function o(e,t){return t.bytes+=c(e)+2,e}function s(n,i,a,l,u){if(u.nodes++,u.nodes>i.maxNodes)return o(`[MaxNodes]`,u);if(n==null)return u.bytes+=4,n;if(typeof n==`string`)return o(t(n,i.maxAttributeChars),u);if(typeof n==`number`)return u.bytes+=8,Number.isFinite(n)?n:String(n);if(typeof n==`boolean`)return u.bytes+=5,n;if(typeof n==`bigint`)return o(`${n.toString()}n`,u);if(typeof n==`symbol`)return o(n.toString(),u);if(typeof n==`function`)return o(`[Function ${n.name===``?`anonymous`:n.name}]`,u);if(l>=i.maxDepth)return o(`[MaxDepth]`,u);if(a.has(n))return o(`[Circular]`,u);a.add(n),u.bytes+=2;try{if(n instanceof Error||Object.prototype.toString.call(n)===`[object Error]`){let r=n,c={},d=0;for(let t of Object.keys(r)){let n=r[t];!e.t.has(t)&&e.n(n)&&(c[t]=n,d++)}return{name:o(r.name,u),message:o(t(r.message,i.maxAttributeChars),u),stack:r.stack?o(t(r.stack,i.maxStackChars),u):void 0,cause:r.cause?s(r.cause,i,a,l+1,u):void 0,data:d>0?s(c,i,a,l+1,u):void 0}}if(n instanceof Date)return o(n.toISOString(),u);if(n instanceof RegExp)return o(n.toString(),u);if(n instanceof Map){let e=n,t={},r=0;for(let[n,d]of e){if(r>=i.maxArrayLength){t[`…`]=o(`[${String(e.size-i.maxArrayLength)} more entries]`,u);break}r++;let f=String(n);u.bytes+=c(f)+4,t[f]=s(d,i,a,l+1,u)}return t}if(n instanceof Set)return s([...n].slice(0,i.maxArrayLength),i,a,l,u);if(ArrayBuffer.isView(n)){let e=n.length??0;return o(`[${n.constructor.name}(${String(e)})]`,u)}if(n instanceof Promise)return o(`[Promise]`,u);if(typeof Node<`u`&&n instanceof Node)return o(r(n),u);if(Array.isArray(n)){let e=n,t=e.slice(0,i.maxArrayLength).map(e=>s(e,i,a,l+1,u));return e.length>i.maxArrayLength&&t.push(o(`[${String(e.length-i.maxArrayLength)} more items]`,u)),t}let d=n.toJSON;if(typeof d==`function`)return s(d.call(n),i,a,l+1,u);let f=n,p=Object.keys(f),m={},h=0;for(let e of p){if(h>=i.maxAttributeCount){m[`…`]=o(`[${String(p.length-h)} more keys]`,u);break}h++,u.bytes+=c(e)+4,m[e]=s(f[e],i,a,l+1,u)}return m}catch(e){return u.diagnostics.count(`record.sanitize_failed`),o(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,u)}finally{a.delete(n)}}function c(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}});
2
- //# sourceMappingURL=sanitize-BAWzkZt0.cjs.map
1
+ require("./constants-CqdJhTxH.cjs");const e=require("./error-like-gGRx2s36.cjs");function t(e,t){if(e.length<=t)return e;let r=n(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,r)}… [truncated ${String(e.length-r)} chars]`}function n(e){return e>=55296&&e<=56319}function r(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function i(e,t,n){return a(e,t,n).value}function a(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:s(e,t,new WeakSet,0,r),bytes:r.bytes}}function o(e,t){return t.bytes+=c(e)+2,e}function s(n,i,a,l,u){if(u.nodes++,u.nodes>i.maxNodes)return o(`[MaxNodes]`,u);if(n==null)return u.bytes+=4,n;if(typeof n==`string`)return o(t(n,i.maxAttributeChars),u);if(typeof n==`number`)return u.bytes+=8,Number.isFinite(n)?n:String(n);if(typeof n==`boolean`)return u.bytes+=5,n;if(typeof n==`bigint`)return o(`${n.toString()}n`,u);if(typeof n==`symbol`)return o(n.toString(),u);if(typeof n==`function`)return o(`[Function ${n.name===``?`anonymous`:n.name}]`,u);if(l>=i.maxDepth)return o(`[MaxDepth]`,u);if(a.has(n))return o(`[Circular]`,u);a.add(n),u.bytes+=2;try{if(n instanceof Error||Object.prototype.toString.call(n)===`[object Error]`){let r=n,c={},d=0;for(let t of Object.keys(r)){let n=r[t];!e.t.has(t)&&e.n(n)&&(c[t]=n,d++)}return{name:o(r.name,u),message:o(t(r.message,i.maxAttributeChars),u),stack:r.stack?o(t(r.stack,i.maxStackChars),u):void 0,cause:r.cause?s(r.cause,i,a,l+1,u):void 0,data:d>0?s(c,i,a,l+1,u):void 0}}if(n instanceof Date)return o(n.toISOString(),u);if(n instanceof RegExp)return o(n.toString(),u);if(n instanceof Map){let e=n,t={},r=0;for(let[n,d]of e){if(r>=i.maxArrayLength){t[`…`]=o(`[${String(e.size-i.maxArrayLength)} more entries]`,u);break}r++;let f=String(n);u.bytes+=c(f)+4,t[f]=s(d,i,a,l+1,u)}return t}if(n instanceof Set)return s([...n].slice(0,i.maxArrayLength),i,a,l,u);if(ArrayBuffer.isView(n)){let e=n.length??0;return o(`[${n.constructor.name}(${String(e)})]`,u)}if(n instanceof Promise)return o(`[Promise]`,u);if(typeof Node<`u`&&n instanceof Node)return o(r(n),u);if(Array.isArray(n)){let e=n,t=e.slice(0,i.maxArrayLength).map(e=>s(e,i,a,l+1,u));return e.length>i.maxArrayLength&&t.push(o(`[${String(e.length-i.maxArrayLength)} more items]`,u)),t}let d=n.toJSON;if(typeof d==`function`)return s(d.call(n),i,a,l+1,u);let f=n,p=Object.keys(f),m={},h=0;for(let e of p){if(h>=i.maxAttributeCount){m[`…`]=o(`[${String(p.length-h)} more keys]`,u);break}h++,u.bytes+=c(e)+4,m[e]=s(f[e],i,a,l+1,u)}return m}catch(e){return u.diagnostics.count(`record.sanitize_failed`),o(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,u)}finally{a.delete(n)}}function c(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}});
2
+ //# sourceMappingURL=sanitize-DQyiI_KY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize-DQyiI_KY.cjs","names":["ERROR_OWN_KEYS","isDataField","set","toJson","require_error_like","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures, detecting cycles and estimating the byte\n// size. Never throws and never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to a maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns The truncated string, with a suffix that gives the dropped character count.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Don't split a UTF-16 surrogate pair at the cut. slice works in code units, and half a\n // pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Checks whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if the character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. Counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. Counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds a string's length plus quote overhead to the size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns The input text, unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively, replacing cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits don't bound a wide tree: 128 keys over 6 levels is 128^6 values, and\n // the walk would visit all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof, but its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n // The build's ES2021 types don't declare cause, so the type adds it.\n const error = value as Error & { cause?: unknown };\n // Keep the error's own fields, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute, not the\n // whole record. Count the fault, because a report for every attribute would be noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind, or a repeated sibling would show\n // up as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":"A,iFA2CA,SAAgBK,EAAS,EAAe,EAAqB,CAC3D,GAAIC,EAAM,QAAUC,EAClB,OAAOD,EAKT,IAAME,EAAMC,EAAgBH,EAAM,WAAWC,EAAM,CAAC,CAAC,EAAIA,EAAM,EAAIA,EACnE,MAAO,GAAGD,EAAM,MAAM,EAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,OAASE,CAAG,EAAE,QAC1E,CAOA,SAASC,EAAgB,EAAuB,CAC9C,OAAOC,GAAA,OAA8BA,GAAA,KACvC,CAcA,SAASC,EAAa,EAAwB,CAO5C,MAAO,aANMC,EAAK,UAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,GAAK,IAAIA,EAAK,KAAO,KAEnC,OAAOA,EAAK,WAAc,UAAYA,EAAK,UACvC,IAAIA,EAAK,UAAU,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAAG,IAC9E,GAC4B,EACpC,CA2BA,SAAgBC,EACd,EACA,EACA,EACS,CACT,OAAOC,EAAiBR,EAAOS,EAAQC,CAAW,CAAC,CAAC,KACtD,CASA,SAAgBF,EACd,EACA,EACA,EACgB,CAChB,IAAMG,EAAmB,CAAE,MAAO,EAAG,MAAO,EAAG,aAAY,EAE3D,MAAO,CAAE,MADMC,EAAKZ,EAAOS,EAAQ,IAAI,QAAW,EAAGE,CACrC,EAAQ,MAAOA,EAAM,KAAM,CAC7C,CAQA,SAASE,EAAQ,EAAc,EAA0B,CAEvD,MADA,GAAM,OAASC,EAAcC,CAAI,EAAA,EAC1BA,CACT,CAYA,SAASH,EACP,EACA,EACA,EACA,EACA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IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWoC,CAAC,EAC3BhC,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT,C"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-CqdJhTxH.cjs"),t=require("./factory-hRrH32v5.cjs"),n=require("./deadline-CUGbto-y.cjs"),r=require("./library-request-D7OvTxZV.cjs"),i=require("./openfin-DtH2f7zX.cjs"),a=require("./sanitize-DQyiI_KY.cjs"),o=require("./library-console-CPW6bvZH.cjs"),s=require("./response-body-YdNl-HkR.cjs"),c=require("./defineProperty-X1c4tIPD.cjs"),l=require("./platform-CfA3-7sJ.cjs"),u=require("./unref-CU9Nyz_9.cjs"),d=require("./compression-CvED_Jel.cjs"),f=require("./batch-mmPigCpi.cjs"),p=require("./log-record-CkivuiEl.cjs"),m=require("./identity-DlWRIuwy.cjs"),h=require("./sampling-mXt4dstx.cjs"),g=require("./remote-rules-_tY0zj5o.cjs");async function _(e){let t=globalThis.navigator?.storage;return typeof t?.persist==`function`?await e.guardAsync(`storage.unavailable`,`The browser rejected the request for persistent storage.`,()=>t.persist())===!0?`granted`:`denied`:`unsupported`}function v(e){let t=typeof e==`string`?Date.parse(e):NaN;return Number.isNaN(t)?void 0:Math.round(t+500-Date.now())}var y=class{stop(){this.cancellation.abort()}assertContext(e){if(this.cancellation.signal.aborted||this.config.securityContext.isolation&&this.config.securityContext.id&&e.routingContextId!==this.config.securityContext.id)throw this.diagnostics.count(`security.context_mismatch`),new s.f(`permanent`,`The delivery context is inactive or does not match the batch.`)}async untilCancelled(e){if(this.cancellation.signal.aborted)throw new s.f(`permanent`,`The delivery context retired.`);let t,n=new Promise((e,n)=>{t=()=>{n(new s.f(`permanent`,`The delivery context retired.`))},this.cancellation.signal.addEventListener(`abort`,t,{once:!0})});try{return await Promise.race([e,n])}finally{this.cancellation.signal.removeEventListener(`abort`,t)}}constructor(e,t,n=()=>void 0,r=()=>void 0,i=()=>void 0){c.t(this,`config`,void 0),c.t(this,`diagnostics`,void 0),c.t(this,`onSampling`,void 0),c.t(this,`onLoss`,void 0),c.t(this,`onClock`,void 0),c.t(this,`cancellation`,new AbortController),c.t(this,`throttledUntil`,{logs:0,metrics:0,traces:0}),c.t(this,`acceptedAt`,null),this.config=e,this.diagnostics=t,this.onSampling=n,this.onLoss=r,this.onClock=i}throttledForMs(e){return Math.max(0,this.throttledUntil[s.o(e,this.config)]-Date.now())}throttleEnd(){let e=Math.max(...Object.values(this.throttledUntil));return e>Date.now()?e:null}lastSendAt(){return this.acceptedAt}serialize(e){let t=s.c(this.config,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`);return t||this.onLoss(`unserializable`,e.records,[e.id]),t}accept(e,t,n){this.throttledUntil[e]=0,this.acceptedAt=Date.now(),this.config.sampling.remote&&t!=null&&this.onSampling(t);let r=v(n);r!==void 0&&this.onClock(r)}reportPartial(e,t,n){let r=this.diagnostics.guard(`transport.http_error`,`The library could not read the body of the 2xx response.`,()=>s.i(n,t));if(!r)return 0;let i=s.s(t,this.config),a=Math.min(r.rejected,e.records.length);if(a===0)return this.diagnostics.report(`transport.partial_success`,`The server accepted the batch with a warning.`,{endpoint:i,serverMessage:r.message}),0;this.onLoss(`partially_rejected`,[],[e.id],a);let o=String(e.records.length);return this.diagnostics.report(`transport.partial_success`,`The server rejected ${String(a)} of ${o} records in the batch. The library does not send them again.`,{endpoint:i,rejected:a,serverMessage:r.message}),a}reject(e,t,n,r){let i=String(e);if(e===401||e===403){let t=r.advice===void 0?``:` ${r.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${i}.${t}`,{status:e,endpoint:s.s(n,this.config)}),new s.f(`permanent`,`The server rejected the batch with ${i}.`,e)}if(e===413)return new s.f(`too_large`,`The payload is too large.`,e,void 0,r.maxBytes);if(e===429||e===503){let t=e===429,i=r.retryAfterMs===void 0?void 0:Math.min(r.retryAfterMs,this.config.delivery.retryMaxDelayMs);return this.throttledUntil[n]=Date.now()+(i??this.config.delivery.retryBaseDelayMs),t&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:i}),new s.f(`throttled`,t?`The server throttles the requests.`:`The service is not available.`,e,i)}return e===408||e>=500?new s.f(`transient`,`The server returned the error ${i}.`,e):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${i}. The library dropped it.`,{batchId:t,status:e}),new s.f(`permanent`,`The server rejected the batch with ${i}.`,e))}};function b(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records,routingContextId:e.routingContextId}}function x(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isInteger(t)&&t>=100&&t<=599}function S(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var C=class extends y{async send(e){this.assertContext(e);let{transport:t}=this.config;if(!t||e.records.length===0)return e.records.length;let i=this.serialize(e);if(!i)return e.records.length;let a=s.o(e,this.config),c=b(e,i,a);c.signal=this.cancellation.signal;let l;try{l=await n.n(this.untilCancelled(r.i(()=>r.r(()=>o.n(()=>t(c))))),this.config.delivery.requestTimeoutMs)}catch(e){let t=e instanceof n.t?e:void 0,r=t?`timeout`:`transient`,i=t?.message??`The custom transport failed.`;throw new s.f(r,i,void 0,void 0,void 0,e)}if(this.assertContext(e),!x(l))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:e.id}),new s.f(`transient`,`The custom transport returned no valid status.`);let{status:u}=l;if(u>=200&&u<300)return this.accept(a,l.sampling,l.date),0;throw this.reject(u,e.id,a,{retryAfterMs:S(l.retryAfterMs),maxBytes:S(l.maxBytes)})}},w=class{constructor(e){c.t(this,`deps`,void 0),c.t(this,`installed`,!1),c.t(this,`keepaliveBytes`,0),c.t(this,`onVisibility`,()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)}),c.t(this,`onPageHide`,()=>{this.flush(`pagehide`)}),c.t(this,`onFreeze`,()=>{this.flush(`freeze`)}),c.t(this,`onOpenFinClose`,()=>{this.flush(`openfin-close`)}),this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=i.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=i.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(e){let{config:t,diagnostics:n}=this.deps;if(n.guard(`pipeline.crashed`,`The metric points before the exit flush failed.`,()=>{this.deps.beforeExit?.()}),e===`hidden`){this.flushAlive();return}if(t.transport){this.flushCustom(e,t.transportOnExit);return}let r=this.endpointUrl();if(r!==null){this.keepaliveBytes=this.deps.keepaliveInFlight()??0;for(let i of this.deps.drainForExit()){let a=s.o(i,t),o=a===`logs`?r.href:s.s(a,t);o?this.flushBatch(i,e,new URL(o)):n.count(`record.dropped_no_destination`)}}}flushBatch(t,n,r){let{config:i}=this.deps;if(t.records.length===0)return;let o=this.serialize(t,n);if(!o)return;let s=a.t(o.body);if(s>6e4){this.park(t);return}r.searchParams.set(e.nn,t.id),r.searchParams.set(e.rn,n);let c=r.toString(),l=this.deps.exitHeaders(),u=()=>{let n=new Headers(l);return n.set(e.ft,o.contentType),n.set(e.ut,t.id),n};if(l){this.keepaliveFetch(c,t,o.body,s,n,u);return}if(i.headers){this.park(t);return}if(this.isSameOrigin(r)){this.keepaliveFetch(c,t,o.body,s,n,u);return}let d=()=>new Headers({[e.ft]:e.V});if(i.credentials!==`include`){this.keepaliveFetch(c,t,o.body,s,n,d);return}let f=this.beacon(c,o.body);f===`sent`?this.keepaliveBytes+=s:f===`refused`?(this.keepaliveBytes=e.D,this.park(t)):this.keepaliveFetch(c,t,o.body,s,n,d)}isSameOrigin(e){if(typeof location>`u`)return!1;let t=e.origin===`null`,n=e.origin===globalThis.origin,r=e.origin===location.origin;return!t&&n&&r}flushAlive(){let{diagnostics:e}=this.deps,t=`The flush of the hidden document failed.`;e.guard(`pipeline.crashed`,t,()=>{Promise.resolve(this.deps.flushAlive()).catch(n=>{e.report(`pipeline.crashed`,t,void 0,n)})})}flushCustom(e,t){let{config:n,diagnostics:i}=this.deps;for(let a of this.deps.drainForExit()){let o=this.serialize(a,e);if(!o)continue;let c=b(a,o,s.o(a,n));(t===void 0||i.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>r.r(()=>t(c)))!==!0)&&this.park(a)}}park(e){let{config:n,diagnostics:r,onLoss:i}=this.deps,{backend:a}=n.storage;a===`memory`||a===`none`?i?.(`not_stored`,e.records,[e.id]):t.l(e,r,i)}serialize(e,t){let n=s.c(this.deps.config,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`);return n||this.deps.onLoss?.(`unserializable`,e.records,[e.id]),n}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`The sendBeacon call failed.`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(e,t,n,i,a,o){let{config:s,diagnostics:c}=this.deps,l=()=>{this.park(t)};this.keepaliveBytes+i>6e4?l():(this.keepaliveBytes+=i,c.guard(`transport.http_error`,`The keepalive fetch failed.`,()=>(r.r(()=>fetch(e,{method:`POST`,body:n,headers:o(),credentials:s.credentials,keepalive:!0})).catch(e=>{c.report(`transport.http_error`,`The exit flush failed.`,{reason:a},e),l()}),!0))!==!0&&l())}},T=new WeakMap;function E(e,t){let{headers:n}=t;if(!n)return;if(typeof n!=`function`)return n;let r=T.get(e);return r?.source===n&&r.endpoint===t.endpoint&&r.metricsEndpoint===t.metricsEndpoint&&r.tracesEndpoint===t.tracesEndpoint?r.headers:void 0}async function D(e,t,n){let{headers:r}=t;if(!r)return{};if(typeof r!=`function`)return r;let{endpoint:i,metricsEndpoint:a,tracesEndpoint:o}=t,s=await n.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(r()));return s&&T.set(e,{source:r,endpoint:i,metricsEndpoint:a,tracesEndpoint:o,headers:s}),s??{}}function O(e){T.delete(e)}var k=`In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,A=class extends y{constructor(...e){super(...e),c.t(this,`keepaliveBytes`,0)}async send(e,t){this.assertContext(e);let{config:n}=this,r=s.o(e,n),i=s.s(r,n);return i?e.records.length===0?0:this.post(e,r,i,t):(this.diagnostics.count(`record.dropped_no_destination`),e.records.length)}lastHeaders(){return E(this,this.config)}keepaliveInFlight(){return this.keepaliveBytes}async post(t,n,r,i){let a=this.serialize(t);if(!a)return t.records.length;let o=s.t(n,this.config.serializer),c=await this.attempt(t,r,a,o,i);this.assertContext(t),this.rejectsCredentials(c.response.status)&&typeof this.config.headers==`function`&&(O(this),c=await this.attempt(t,r,a,o,i),this.assertContext(t));let{response:l,body:u}=c;if(l.ok){let{headers:r}=l;return this.accept(n,r.get(e.ht),r.get(e.pt)),u===void 0?0:this.reportPartial(t,n,u)}let d=l.status,f=s.p(l.headers.get(e.mt)),p=d===413&&u!==void 0?this.readMaxBytes(u):void 0;throw this.reject(d,t.id,n,{retryAfterMs:f,maxBytes:p,advice:k})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i,o){let s=Date.now()+this.config.delivery.requestTimeoutMs,c=new Headers(await this.before(this.resolveHeaders(),s,n));c.set(e.ft,r.contentType),c.set(e.ut,t.id),c.set(e.lt,String(t.attempts));let l=await this.before(this.encodeBody(r.body),s,n);this.assertContext(t),typeof l!=`string`&&c.set(e.dt,e.tt);let u=typeof l==`string`?a.t(l):l.byteLength;if(!this.keepalive(u))return this.dispatch(n,c,l,s,!1,i);o?.(),this.keepaliveBytes+=u;try{return await this.dispatch(n,c,l,s,!0,i)}finally{this.keepaliveBytes-=u}}async before(e,t,r){try{return await n.n(this.untilCancelled(e),Math.max(0,t-Date.now()))}catch{throw this.cancellation.signal.aborted?new s.f(`permanent`,`The delivery context retired.`):this.timeout(r)}}timeout(e){let t=`The request took longer than ${String(this.config.delivery.requestTimeoutMs)} ms.`;return this.diagnostics.report(`transport.timeout`,t,{endpoint:e}),new s.f(`timeout`,t)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||a.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>d.t(e))??e}async dispatch(e,t,n,i,a,o){let{config:c}=this,d=new AbortController,f=()=>{d.abort()};this.cancellation.signal.addEventListener(`abort`,f,{once:!0}),this.cancellation.signal.aborted&&d.abort();let p=setTimeout(()=>{d.abort()},Math.max(0,i-Date.now()));u.t(p);try{let i=await r.r(()=>fetch(e,{method:`POST`,headers:t,body:n,credentials:c.credentials,signal:d.signal,cache:`no-store`,keepalive:a,priority:a?`auto`:c.delivery.priority}));return s.r(i,o)?{response:i,body:await s.a(i,d.signal,this.diagnostics)}:{response:i}}catch{throw this.cancellation.signal.aborted?new s.f(`permanent`,`The delivery context retired.`):d.signal.aborted?this.timeout(e):new s.f(l.r()?`transient`:`offline`,`A network error occurred.`)}finally{this.cancellation.signal.removeEventListener(`abort`,f),clearTimeout(p)}}keepalive(e){return globalThis.document?.visibilityState===`hidden`&&e<=6e4}readMaxBytes(e){return this.diagnostics.guard(`transport.http_error`,`The library could not read the body of the 413 response.`,()=>s.n(e))}async resolveHeaders(){return D(this,this.config,this.diagnostics)}},j=class{constructor(e,n,r,i,a=20,o=()=>void 0){c.t(this,`storage`,void 0),c.t(this,`transport`,void 0),c.t(this,`diagnostics`,void 0),c.t(this,`config`,void 0),c.t(this,`batchesPerDrain`,void 0),c.t(this,`onLoss`,void 0),c.t(this,`timer`,null),c.t(this,`attempt`,0),c.t(this,`draining`,!1),c.t(this,`stopped`,!1),c.t(this,`maxAttempts`,void 0),c.t(this,`onOnline`,()=>{this.attempt=0,this.schedule(0)}),this.storage=e,this.transport=n,this.diagnostics=r,this.config=i,this.batchesPerDrain=a,this.onLoss=o,this.maxAttempts=t.p(i.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.kn)}nudge(){this.draining||this.schedule(this.config.delivery.retryBaseDelayMs)}async storeFailed(e,t){let n=this.toStorable(e,t);if(n.length===0)return{outcome:`rejected`,stored:0};let r=0,i=0;for(let e of n)await this.bounded(this.storage.save(e))&&(r++,i+=e.records.length);return r>0&&this.nudge(),r<n.length?{outcome:`not_stored`,stored:i}:{outcome:n.length>1?`split`:`stored`,stored:i}}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}async flush(){this.stopped=!1;try{await this.drain()}finally{this.stop()}}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,u.t(t)}bounded(t){return n.n(t,e.Wn)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let e=Math.min(this.config.delivery.retryBaseDelayMs*2**this.attempt,this.config.delivery.retryMaxDelayMs);return Math.random()*e}async drain(){if(!this.draining){this.draining=!0;try{let n=t.u(e.X,this.config.storage.namespace);await t.d(n,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.kn)}finally{this.draining=!1}}}async drainLocked(){try{if(!l.r())return this.schedule(e.kn),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.kn),!0;let n=new Set,r=0;for(let e of t){if(this.stopped)return!0;let t=s.o(e,this.config);if(n.has(t))continue;let i=await this.deliver(e);if(i===`stop`)return!0;i!==`next`&&(n.add(t),r=Math.max(r,i))}return n.size>0?this.schedule(r):this.schedule(t.length===this.batchesPerDrain?0:e.kn),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${t.attempts.toString()} attempts.`,{batchId:t.id,records:t.records.length}),this.onLoss(`max_attempts`,t.records,[t.id]),await this.bounded(this.storage.remove(t.id)),`next`;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,`next`}catch(n){if(this.stopped)return`stop`;let r=n instanceof s.f?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),`next`):r?.kind===`offline`?(this.schedule(e.kn),`stop`):r?.kind===`throttled`?(this.attempt++,r.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,r?.retryAfterMs??this.backoffMs())}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof s.f?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=f.a(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),this.onLoss(`rejected`,e.records,[e.id]),[])}},M=[`metrics`,`logs`,`traces`];function N(t){let n=t.attributes[e.g];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}function P(e,t){return{accepted:0,stored:e,dropped:t-e}}var F={stored:`The send failed. The library stored the batch and sends it again later.`,split:`The send failed. The library stored the batch in two parts and sends them again later.`,rejected:`The send failed, and another send would fail too. The library drops the batch.`,not_stored:`The send failed, and storage did not keep the batch. The library drops the records that are not in storage.`,unknown:`The send failed. The library could not confirm that storage kept the batch. The library sends again only the records that are in storage.`},I={stored:`The server throttles requests. The pipeline stored the batch and did not send it.`,not_stored:`The server throttles requests, and storage did not keep the batch. The library drops the batch.`,unknown:`The server throttles requests. The library could not confirm that storage kept the batch. The library sends the batch later only if it is in storage.`},L=class{constructor(e,t){c.t(this,`options`,void 0),c.t(this,`onFlush`,void 0),c.t(this,`pending`,[]),c.t(this,`timer`,null),this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}get size(){return this.pending.length}get records(){return this.pending}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,u.t(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},R=class{release(e){for(let t of e)this.heldBytes-=this.held.get(t)??0,this.held.delete(t)}evict(){let e=this.queue.shift();if(e)return this.open.delete(e),this.unconfirmed.delete(e.batch.id),this.release(e.batch.records),e.end={accepted:0,stored:0,dropped:e.batch.records.length},e.resolve(),this.onLoss(`buffer_full`,e.batch.records,[e.batch.id]),!0;for(let e of Object.values(this.streams)){let t=e.take();if(t.length)return this.release(t),this.onLoss(`buffer_full`,t),!0}return!1}admit(e){if(!this.policy)return!0;let{maxPendingRecords:t,maxPendingBytes:n,overflow:r}=this.policy.buffering,i;try{i=a.t(JSON.stringify(e))}catch{return this.onLoss(`unserializable`,[e]),!1}let o=()=>t!==null&&this.held.size>=t||n!==null&&this.heldBytes+i>n,s=n===null||i<=n;for(;s&&o()&&r===`drop-oldest`&&this.evict(););if(o()){if(r===`persist`&&!this.persisting){this.persisting=!0;let t=this.toBatch([e]);this.diagnostics.guardAsync(`storage.degraded`,`Could not persist an overflow record.`,async()=>{try{await this.storage.save(t)&&this.retry.nudge()}finally{this.persisting=!1}})}else this.onLoss(`buffer_full`,[e]);return!1}return this.held.set(e,i),this.heldBytes+=i,!0}constructor(e,t,n,r,i,a,o,s=()=>void 0,l=()=>void 0){c.t(this,`transport`,void 0),c.t(this,`storage`,void 0),c.t(this,`retry`,void 0),c.t(this,`diagnostics`,void 0),c.t(this,`routingContextId`,void 0),c.t(this,`policy`,void 0),c.t(this,`onLoss`,void 0),c.t(this,`clockOffset`,void 0),c.t(this,`streams`,void 0),c.t(this,`unconfirmed`,new Map),c.t(this,`queue`,[]),c.t(this,`open`,new Set),c.t(this,`ceiling`,new h.t),c.t(this,`inFlight`,0),c.t(this,`pumpScheduled`,!1),c.t(this,`stopped`,!1),c.t(this,`paused`,!1),c.t(this,`waiters`,new Set),c.t(this,`held`,new Map),c.t(this,`heldBytes`,0),c.t(this,`persisting`,!1),this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r,this.routingContextId=a,this.policy=o,this.onLoss=s,this.clockOffset=l;let u=e=>{this.claim(e)};this.streams={logs:new L(i.logs,u),metrics:new L(i.metrics,u),traces:new L(i.traces,u)}}push(e){if(this.stopped)return;e.observedTimeUnixNano=p.r();let t={...e};this.admit(t)&&this.route(t)}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.held.clear(),this.heldBytes=0,M.map(t=>this.toBatch([...e.filter(e=>N(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(e){if(this.paused)return[];if(!this.stopped)for(let e of M)this.claim(this.streams[e]);let t=[...this.open],n,r=new Promise(e=>{n=e});this.waiters.add(n);try{let n=Promise.all(t.map(e=>e.done));await Promise.race(e?[n,r,e]:[n,r])}finally{this.waiters.delete(n)}return t}async flushUntil(e){let t=await this.flushPending(e),n={accepted:0,stored:0,dropped:0,pending:0};for(let{batch:e,end:r}of t)r?(n.accepted+=r.accepted,n.stored+=r.stored,n.dropped+=r.dropped):n.pending+=e.records.length;return n}counts(){let e=e=>{let t=0;for(let n of e)t+=n.batch.records.length;return t},t=e(this.queue);return{pending:M.reduce((e,t)=>e+this.streams[t].size,0)+t,inFlight:e(this.open)-t}}hold(e){if(this.paused=e,e)for(let e of this.waiters)e();else{for(let e of M)this.claim(this.streams[e]);this.schedulePump()}}isHeld(){return this.paused}records(){return[...[...this.unconfirmed.values()].flatMap(e=>e.records),...M.flatMap(e=>this.streams[e].records)]}discard(){for(let e of this.queue)e.end=P(0,e.batch.records.length);let e=this.queue.flatMap(e=>e.batch.records),t=M.flatMap(e=>this.streams[e].take());return this.destroy(),[...e,...t]}destroy(){this.stopped=!0,this.held.clear(),this.heldBytes=0;for(let e of M)this.streams[e].stop();this.queue.length=0;for(let e of this.open)e.resolve();this.open.clear()}toBatch(e){return e.length===0?null:{id:m.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0,routingContextId:this.routingContextId?.(),persistenceNamespace:this.policy?.storage.namespace}}route(t){try{let n=N(t),r=this.streams[n];if(n===`logs`&&!this.ceiling.allow(t,this.policy?.sampling.errorCeiling,this.policy?.sampling.errorCeilingWindowMs,this.policy?.sampling.alwaysSampleFrom)){this.release([t]),this.diagnostics.count(`record.dropped_by_ceiling`);return}let i=this.clockOffset();i!==void 0&&n!==`metrics`&&(t.attributes={...t.attributes,[e.l]:i}),r.add(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){this.paused||this.enqueue(this.toBatch(e.take()))}enqueue(e){if(!e)return;let t,n={batch:e,done:new Promise(e=>{t=e}),resolve:t};this.unconfirmed.set(e.id,e),this.open.add(n),this.queue.push(n),this.schedulePump()}schedulePump(){this.pumpScheduled||(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){if(!(this.stopped||this.paused))for(;this.inFlight<(this.policy?.delivery.maxConcurrentRequests??2);){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){let{batch:t}=e;try{e.end=await this.dispatch(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:t.id},e)}finally{this.release(t.records),this.inFlight--,this.open.delete(e),e.resolve(),this.pump()}}async dispatch(e){let t=e.records.length;try{let n=this.transport.throttledForMs(e);if(n>0){let r=await this.store(e);return this.diagnostics.report(`transport.throttled`,I[r],{batchId:e.id,records:t,throttledMs:n}),r===`unknown`?void 0:P(r===`stored`?t:0,t)}try{let n=await this.transport.send(e,()=>{this.unconfirmed.delete(e.id)});return{accepted:t-n,stored:0,dropped:n}}catch(n){if(this.stopped)return;let r=await this.storeFailed({...e,attempts:e.attempts+1},n);return this.diagnostics.report(`transport.http_error`,F[r?.outcome??`unknown`],{batchId:e.id,records:t},n),r?P(r.stored,t):void 0}}finally{this.unconfirmed.delete(e.id)}}storeFailed(e,t){return this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,()=>this.retry.storeFailed(e,t))}async store(t){let r=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{let r=await n.n(this.storage.save(t),e.Wn);return r&&this.retry.nudge(),r});return r===void 0?`unknown`:r?`stored`:`not_stored`}},z=class{constructor(e,t=()=>void 0){c.t(this,`transport`,void 0),c.t(this,`onSent`,void 0),c.t(this,`failures`,0),c.t(this,`failedAt`,null),this.transport=e,this.onSent=t}async send(e,t){let n=this.transport.lastSendAt(),r;try{r=await this.transport.send(e,t)}catch(e){throw this.failures++,this.failedAt=Date.now(),e}let i=this.transport.lastSendAt();return i!==null&&i!==n&&(this.failures=0,this.onSent(i)),r}throttledForMs(e){return this.transport.throttledForMs(e)}stats(){return{lastFailureAt:this.failedAt,consecutiveFailures:this.failures}}},B=class e{constructor(e,t,n,r,i,a,o){c.t(this,`storage`,void 0),c.t(this,`retry`,void 0),c.t(this,`pipeline`,void 0),c.t(this,`exitFlush`,void 0),c.t(this,`diagnostics`,void 0),c.t(this,`transport`,void 0),c.t(this,`outcomes`,void 0),c.t(this,`retired`,!1),c.t(this,`emergencyImport`,Promise.resolve()),this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i,this.transport=a,this.outcomes=o}static async create(n){let{config:r,diagnostics:i}=n,a=n.storage??await t.t(r.storage.backend,t.n(r.storage.namespace),t.p(r.retention),i,n.onGap,r.storage.namespace);n.onStorage?.(a),r.storage.requestPersistent&&(a.name===`indexeddb`||a.name===`localstorage`)&&(n.onPersistence?.(`pending`),_(i).then(n.onPersistence));let o=new t.f(a,r.securityContext,r.storage.namespace),s=e=>{let t=g.n(e,i);t&&g.t(n.remote,r,t)},c,l=e=>{c=e},{onLoss:u}=n,d=!r.transport&&r.transportWorker?await i.guardAsync(`transport.http_error`,`The transport worker module did not load. The library uses HTTP.`,async()=>(await Promise.resolve().then(()=>require("./worker-transport-CRAX-09c.cjs"))).createWorkerTransport(r,i,s,u,l)):void 0,f=r.transport!==void 0||d!==void 0?void 0:new A(r,i,s,u,l),p=d?.transport??f??new C(r,i,s,u,l),m=new z(p,n.onSent),h=new j(o,m,i,r,void 0,u),{batching:v}=r,y=new R(m,o,h,i,{logs:{flushIntervalMs:v.logFlushIntervalMs,batchSize:v.logBatchSize},metrics:{get flushIntervalMs(){return r.metrics.intervalMs},batchSize:v.metricBatchSize},traces:{flushIntervalMs:v.logFlushIntervalMs,batchSize:v.logBatchSize}},()=>r.securityContext.id||void 0,r,u,()=>r.metadata.clockOffset?c:void 0),b=new w({config:r,diagnostics:i,drainForExit:()=>y.drainForExit(),flushAlive:()=>y.flushPending(),exitHeaders:()=>d?d.exitHeaders():f?.lastHeaders(),keepaliveInFlight:()=>d?d.keepaliveInFlight():f?.keepaliveInFlight(),onLoss:u,beforeExit:n.beforeExit}),x=!1;try{b.install(),h.start(),x=!0}finally{x||(b.uninstall(),h.stop())}let S=new e(o,h,y,b,i,p,m);return S.emergencyImport=S.importEmergency(),S}push(e){this.pipeline.push(e)}hold(e){this.pipeline.hold(e),e?(this.exitFlush.uninstall(),this.retry.stop()):(this.exitFlush.install(),this.retry.start())}records(){return this.pipeline.records()}async flush(){await this.pipeline.flushPending()}flushUntil(e){return this.pipeline.flushUntil(e)}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}stats(){return{...this.pipeline.counts(),...this.outcomes.stats(),throttledUntil:this.transport.throttleEnd()}}async destroy(){await this.diagnostics.guardAsync(`pipeline.crashed`,`The flush before shutdown failed.`,()=>this.flush()),this.pipeline.isHeld()||this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.transport.stop(),this.pipeline.destroy(),await this.storage.close()}async discard(){this.retired=!0,this.exitFlush.uninstall(),this.retry.stop(),this.transport.stop();let e=this.pipeline.discard();return await this.emergencyImport,await this.storage.retire(!1),e}async pause(e){this.retired=!0,this.exitFlush.uninstall(),this.retry.stop(),this.transport.stop();let t=this.pipeline.drainForExit();this.pipeline.destroy(),await this.emergencyImport,await this.keep(t,e)}async keep(e,t){for(let n of e)await this.storage.save({...n,routingContextId:t,persistenceNamespace:this.storage.namespace})}async retire(e,r,i){if(this.retired=!0,this.exitFlush.uninstall(),this.retry.stop(),e===`flush`&&!this.pipeline.isHeld())try{await n.n(Promise.all([this.flush(),this.retry.flush()]),r)}catch(e){this.diagnostics.report(`transport.timeout`,`The flush of the old security context did not complete before its time limit.`,void 0,e)}this.retry.stop(),this.transport.stop();let a=this.pipeline.drainForExit(),o=a.flatMap(e=>e.records);this.pipeline.destroy(),await this.emergencyImport;let s=await this.storage.take(2**53-1);e===`retain`&&await this.keep(a,i);let c=e===`discard`||e===`flush`;return await this.storage.retire(c),c&&t.s(i,this.diagnostics,this.storage.namespace),{buffered:o,stored:s}}async adopt(e,t){for(let n of e)await this.storage.save({...n,attempts:0,routingContextId:t,persistenceNamespace:this.storage.namespace});e.length>0&&this.retry.nudge()}async importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>t.c(this.storage,this.diagnostics,e=>this.storage.accepts(e),this.storage.namespace));!this.retired&&e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=B,exports.a=y,exports.i=D,exports.n=A,exports.r=O,exports.t=k;
2
+ //# sourceMappingURL=sender-BdRuNVhF.cjs.map