@utk09/ui-observability 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/{batch-D3NHhF9L.js → batch-120Kc9jr.js} +3 -3
  3. package/dist/{batch-D3NHhF9L.js.map → batch-120Kc9jr.js.map} +1 -1
  4. package/dist/{batch-DnYRJqhU.cjs → batch-C3uNp5kU.cjs} +2 -2
  5. package/dist/{batch-DnYRJqhU.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
  6. package/dist/bus/bus.d.cts +5 -0
  7. package/dist/bus/bus.d.ts +5 -0
  8. package/dist/bus-Dj8IEVcC.cjs +2 -0
  9. package/dist/bus-Dj8IEVcC.cjs.map +1 -0
  10. package/dist/{bus-dw7T92sO.js → bus-DyNafxZN.js} +104 -94
  11. package/dist/bus-DyNafxZN.js.map +1 -0
  12. package/dist/capture/errors.d.cts +10 -0
  13. package/dist/capture/errors.d.ts +10 -0
  14. package/dist/capture/replay.d.cts +1 -1
  15. package/dist/capture/replay.d.ts +1 -1
  16. package/dist/capture/types.d.cts +5 -0
  17. package/dist/capture/types.d.ts +5 -0
  18. package/dist/capture/web-vitals.d.cts +1 -0
  19. package/dist/capture/web-vitals.d.ts +1 -0
  20. package/dist/{compression-SHPAvS4U.js → compression-BWkDWY3v.js} +2 -2
  21. package/dist/{compression-SHPAvS4U.js.map → compression-BWkDWY3v.js.map} +1 -1
  22. package/dist/{compression-C0hUHKR-.cjs → compression-CEVe7NPX.cjs} +2 -2
  23. package/dist/{compression-C0hUHKR-.cjs.map → compression-CEVe7NPX.cjs.map} +1 -1
  24. package/dist/config-C0PtemvC.cjs +2 -0
  25. package/dist/config-C0PtemvC.cjs.map +1 -0
  26. package/dist/{config-CSNcS7OZ.js → config-DK1Zf7jn.js} +83 -85
  27. package/dist/config-DK1Zf7jn.js.map +1 -0
  28. package/dist/{console-BsM-fSCQ.js → console-CAyCQOpm.js} +5 -5
  29. package/dist/{console-BsM-fSCQ.js.map → console-CAyCQOpm.js.map} +1 -1
  30. package/dist/{console-Dkxs6IVQ.cjs → console-Dk6GH4yj.cjs} +2 -2
  31. package/dist/{console-Dkxs6IVQ.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
  32. package/dist/{constants-BwJDXzj6.js → constants-CEHN6KuY.js} +42 -21
  33. package/dist/constants-CEHN6KuY.js.map +1 -0
  34. package/dist/constants-NtiQDWL_.cjs +2 -0
  35. package/dist/constants-NtiQDWL_.cjs.map +1 -0
  36. package/dist/constants.d.cts +11 -0
  37. package/dist/constants.d.ts +11 -0
  38. package/dist/core/config.d.cts +9 -3
  39. package/dist/core/config.d.ts +9 -3
  40. package/dist/core/diagnostics.d.cts +1 -1
  41. package/dist/core/diagnostics.d.ts +1 -1
  42. package/dist/core/pipeline.d.cts +11 -0
  43. package/dist/core/pipeline.d.ts +11 -0
  44. package/dist/core/record.d.cts +2 -2
  45. package/dist/core/record.d.ts +2 -2
  46. package/dist/core/sender.d.cts +3 -2
  47. package/dist/core/sender.d.ts +3 -2
  48. package/dist/{debug-bundle-B2v6Cym-.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
  49. package/dist/{debug-bundle-B2v6Cym-.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
  50. package/dist/{debug-bundle-Cs_YWzTa.js → debug-bundle-w78W46zr.js} +4 -4
  51. package/dist/{debug-bundle-Cs_YWzTa.js.map → debug-bundle-w78W46zr.js.map} +1 -1
  52. package/dist/doctor.cjs +1 -1
  53. package/dist/doctor.js +22 -22
  54. package/dist/doctor.js.map +1 -1
  55. package/dist/errors-07pmZ7VY.cjs +3 -0
  56. package/dist/errors-07pmZ7VY.cjs.map +1 -0
  57. package/dist/{errors-Q3Ng1ciC.js → errors-C-LYbqyB.js} +27 -24
  58. package/dist/errors-C-LYbqyB.js.map +1 -0
  59. package/dist/{factory-DV17sm2p.js → factory-BHYrcSaU.js} +42 -31
  60. package/dist/factory-BHYrcSaU.js.map +1 -0
  61. package/dist/factory-DsaNdcXp.cjs +2 -0
  62. package/dist/factory-DsaNdcXp.cjs.map +1 -0
  63. package/dist/{identity-BgtHyY4u.js → identity-Byh3gCdT.js} +11 -11
  64. package/dist/{identity-BgtHyY4u.js.map → identity-Byh3gCdT.js.map} +1 -1
  65. package/dist/{identity-CvuyqZk7.cjs → identity-BzAzdQyv.cjs} +2 -2
  66. package/dist/{identity-CvuyqZk7.cjs.map → identity-BzAzdQyv.cjs.map} +1 -1
  67. package/dist/index.cjs +1 -1
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.js +539 -534
  70. package/dist/index.js.map +1 -1
  71. package/dist/{indexeddb-storage-e-13ZLWm.js → indexeddb-storage-BYywz-v6.js} +4 -4
  72. package/dist/{indexeddb-storage-e-13ZLWm.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
  73. package/dist/{indexeddb-storage-D4KVcqdD.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
  74. package/dist/{indexeddb-storage-D4KVcqdD.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
  75. package/dist/{interactions-OK85T-Dk.cjs → interactions-BXzEel4F.cjs} +2 -2
  76. package/dist/interactions-BXzEel4F.cjs.map +1 -0
  77. package/dist/{interactions-Byxf1C82.js → interactions-DdKPMWIN.js} +12 -12
  78. package/dist/interactions-DdKPMWIN.js.map +1 -0
  79. package/dist/{journey-nMbob3OB.cjs → journey-BUmsrgaw.cjs} +2 -2
  80. package/dist/{journey-nMbob3OB.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
  81. package/dist/{journey-C93FTYcs.js → journey-Nu655gEO.js} +3 -3
  82. package/dist/{journey-C93FTYcs.js.map → journey-Nu655gEO.js.map} +1 -1
  83. package/dist/{library-console-DJUQzcgM.cjs → library-console-DdIlzzph.cjs} +2 -2
  84. package/dist/{library-console-DJUQzcgM.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
  85. package/dist/{library-console-DklSmucS.js → library-console-amePMnP8.js} +2 -2
  86. package/dist/{library-console-DklSmucS.js.map → library-console-amePMnP8.js.map} +1 -1
  87. package/dist/{library-request-UGEwOHpf.js → library-request-Cv7C05jf.js} +2 -2
  88. package/dist/{library-request-UGEwOHpf.js.map → library-request-Cv7C05jf.js.map} +1 -1
  89. package/dist/{library-request-kY9iTpIF.cjs → library-request-DO3Ec7KE.cjs} +2 -2
  90. package/dist/{library-request-kY9iTpIF.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
  91. package/dist/{lifecycle-DaMdH_X7.cjs → lifecycle-B5yfH5is.cjs} +2 -2
  92. package/dist/{lifecycle-DaMdH_X7.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
  93. package/dist/{lifecycle-B2PlIuQu.js → lifecycle-CMHz2Zbs.js} +2 -2
  94. package/dist/{lifecycle-B2PlIuQu.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
  95. package/dist/{log-record-DSt2P-Sr.js → log-record-B_nSqxoe.js} +2 -2
  96. package/dist/{log-record-DSt2P-Sr.js.map → log-record-B_nSqxoe.js.map} +1 -1
  97. package/dist/{log-record-Bmx6etMh.cjs → log-record-Bdywwg0k.cjs} +2 -2
  98. package/dist/{log-record-Bmx6etMh.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
  99. package/dist/{long-frames-Bamjs1WV.js → long-frames-6NGl1-uN.js} +3 -3
  100. package/dist/{long-frames-Bamjs1WV.js.map → long-frames-6NGl1-uN.js.map} +1 -1
  101. package/dist/{long-frames-lhtONgGt.cjs → long-frames-D9DfSWqv.cjs} +2 -2
  102. package/dist/{long-frames-lhtONgGt.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
  103. package/dist/models/config.d.cts +4 -3
  104. package/dist/models/config.d.ts +4 -3
  105. package/dist/{network-BCn8Gn47.cjs → network-BNHBI0Fc.cjs} +2 -2
  106. package/dist/{network-BCn8Gn47.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
  107. package/dist/{network-Cg1L2w2r.js → network-Cc3tSB7e.js} +13 -13
  108. package/dist/{network-Cg1L2w2r.js.map → network-Cc3tSB7e.js.map} +1 -1
  109. package/dist/{observed-windows-BrwaJNlj.js → observed-windows-8JtCsIr1.js} +3 -3
  110. package/dist/{observed-windows-BrwaJNlj.js.map → observed-windows-8JtCsIr1.js.map} +1 -1
  111. package/dist/{observed-windows-B3gJkdql.cjs → observed-windows-BlE25nrn.cjs} +2 -2
  112. package/dist/{observed-windows-B3gJkdql.cjs.map → observed-windows-BlE25nrn.cjs.map} +1 -1
  113. package/dist/openfin-Bxelt0yg.js.map +1 -1
  114. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  115. package/dist/{otlp-D6dRZyB8.js → otlp-Btix3EBa.js} +7 -7
  116. package/dist/{otlp-D6dRZyB8.js.map → otlp-Btix3EBa.js.map} +1 -1
  117. package/dist/{otlp-CrAWkQdO.cjs → otlp-CFSW-Dno.cjs} +2 -2
  118. package/dist/{otlp-CrAWkQdO.cjs.map → otlp-CFSW-Dno.cjs.map} +1 -1
  119. package/dist/patch-DlcKzIi-.cjs +2 -0
  120. package/dist/patch-DlcKzIi-.cjs.map +1 -0
  121. package/dist/patch-Sr1wKg7W.js +9 -0
  122. package/dist/patch-Sr1wKg7W.js.map +1 -0
  123. package/dist/platform-BZjp9wp1.cjs +2 -0
  124. package/dist/platform-BZjp9wp1.cjs.map +1 -0
  125. package/dist/{platform-8DLhjddo.js → platform-Dba6R3Hp.js} +22 -9
  126. package/dist/platform-Dba6R3Hp.js.map +1 -0
  127. package/dist/{profiler-BaXSqCfz.js → profiler-DNKcqu09.js} +19 -19
  128. package/dist/{profiler-BaXSqCfz.js.map → profiler-DNKcqu09.js.map} +1 -1
  129. package/dist/{profiler-BvWW2kNM.cjs → profiler-DpoPi1hH.cjs} +2 -2
  130. package/dist/{profiler-BvWW2kNM.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
  131. package/dist/{profiler-frames-DeaBiB-5.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
  132. package/dist/{profiler-frames-DeaBiB-5.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
  133. package/dist/{profiler-frames-C4ySHN0X.js → profiler-frames-CGXZeZ_3.js} +4 -4
  134. package/dist/{profiler-frames-C4ySHN0X.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
  135. package/dist/{remote-rules-Dq9xe7Qn.js → remote-rules-DNK96vLa.js} +15 -15
  136. package/dist/{remote-rules-Dq9xe7Qn.js.map → remote-rules-DNK96vLa.js.map} +1 -1
  137. package/dist/{remote-rules-D7L6D_D2.cjs → remote-rules-DuMFRlit.cjs} +2 -2
  138. package/dist/{remote-rules-D7L6D_D2.cjs.map → remote-rules-DuMFRlit.cjs.map} +1 -1
  139. package/dist/replay-Cab-lSit.cjs +2 -0
  140. package/dist/replay-Cab-lSit.cjs.map +1 -0
  141. package/dist/{replay-B0M8kWz_.js → replay-Dy6OiaOZ.js} +89 -62
  142. package/dist/replay-Dy6OiaOZ.js.map +1 -0
  143. package/dist/{reports-ojuMKGO7.cjs → reports-CGK9YQch.cjs} +2 -2
  144. package/dist/{reports-ojuMKGO7.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
  145. package/dist/{reports--8APRLa-.js → reports-CX57-S9s.js} +3 -3
  146. package/dist/{reports--8APRLa-.js.map → reports-CX57-S9s.js.map} +1 -1
  147. package/dist/{resource-timing-BzR05rE-.js → resource-timing-CWVDCbrY.js} +4 -4
  148. package/dist/{resource-timing-BzR05rE-.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
  149. package/dist/{resource-timing-pAG3ZhB5.cjs → resource-timing-DalulXiR.cjs} +2 -2
  150. package/dist/{resource-timing-pAG3ZhB5.cjs.map → resource-timing-DalulXiR.cjs.map} +1 -1
  151. package/dist/response-body-Cpz5__4g.cjs +3 -0
  152. package/dist/response-body-Cpz5__4g.cjs.map +1 -0
  153. package/dist/{response-body-BWvwKQ2p.js → response-body-yi92Rpvo.js} +100 -100
  154. package/dist/response-body-yi92Rpvo.js.map +1 -0
  155. package/dist/{rotation-BylN1B9e.js → rotation-ChBbNDE2.js} +24 -24
  156. package/dist/rotation-ChBbNDE2.js.map +1 -0
  157. package/dist/rotation-fTnNJcfH.cjs +2 -0
  158. package/dist/rotation-fTnNJcfH.cjs.map +1 -0
  159. package/dist/{sampling-zXA6r-Nw.js → sampling-DZTOD28D.js} +6 -6
  160. package/dist/{sampling-zXA6r-Nw.js.map → sampling-DZTOD28D.js.map} +1 -1
  161. package/dist/{sampling-B46LW0cy.cjs → sampling-wAVJIZXp.cjs} +2 -2
  162. package/dist/{sampling-B46LW0cy.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
  163. package/dist/{sanitize-DjnR6RXR.js → sanitize-B2GKlSFp.js} +2 -2
  164. package/dist/{sanitize-DjnR6RXR.js.map → sanitize-B2GKlSFp.js.map} +1 -1
  165. package/dist/{sanitize-Qj6LuZqp.cjs → sanitize-BZdhoghq.cjs} +2 -2
  166. package/dist/{sanitize-Qj6LuZqp.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
  167. package/dist/{sender-Bdp-TAS4.js → sender-BRSpc7R8.js} +175 -161
  168. package/dist/sender-BRSpc7R8.js.map +1 -0
  169. package/dist/sender-CFu98DAB.cjs +2 -0
  170. package/dist/sender-CFu98DAB.cjs.map +1 -0
  171. package/dist/storage/emergency-queue.d.cts +3 -1
  172. package/dist/storage/emergency-queue.d.ts +3 -1
  173. package/dist/storage/stored-context.d.cts +3 -2
  174. package/dist/storage/stored-context.d.ts +3 -2
  175. package/dist/stored-context-CPLlzgpm.cjs +2 -0
  176. package/dist/stored-context-CPLlzgpm.cjs.map +1 -0
  177. package/dist/{stored-context-CSttrAsw.js → stored-context-df1dEnht.js} +10 -8
  178. package/dist/stored-context-df1dEnht.js.map +1 -0
  179. package/dist/{storm-DKlpv0FL.js → storm-U3_ek1nA.js} +2 -2
  180. package/dist/{storm-DKlpv0FL.js.map → storm-U3_ek1nA.js.map} +1 -1
  181. package/dist/{storm-BHgI12iS.cjs → storm-qiE_AMC7.cjs} +2 -2
  182. package/dist/{storm-BHgI12iS.cjs.map → storm-qiE_AMC7.cjs.map} +1 -1
  183. package/dist/transport/exit-flush.d.cts +23 -0
  184. package/dist/transport/exit-flush.d.ts +23 -0
  185. package/dist/transport/http-transport.d.cts +3 -2
  186. package/dist/transport/http-transport.d.ts +3 -2
  187. package/dist/transport/retry-engine.d.cts +11 -3
  188. package/dist/transport/retry-engine.d.ts +11 -3
  189. package/dist/types-BAerHgCq.js.map +1 -1
  190. package/dist/types-C7WNpnG1.cjs.map +1 -1
  191. package/dist/{unclean-exit-BcOB8A2e.js → unclean-exit-Bj6gYHeL.js} +2 -2
  192. package/dist/{unclean-exit-BcOB8A2e.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
  193. package/dist/{unclean-exit-BYPYYkQ5.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
  194. package/dist/{unclean-exit-BYPYYkQ5.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
  195. package/dist/{user-timing-BsU2wQKE.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
  196. package/dist/{user-timing-BsU2wQKE.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
  197. package/dist/{user-timing-4KIJ74Vi.js → user-timing-Duz0d-OA.js} +2 -2
  198. package/dist/{user-timing-4KIJ74Vi.js.map → user-timing-Duz0d-OA.js.map} +1 -1
  199. package/dist/utils/lock.d.cts +3 -2
  200. package/dist/utils/lock.d.ts +3 -2
  201. package/dist/utils/openfin.d.cts +18 -6
  202. package/dist/utils/openfin.d.ts +18 -6
  203. package/dist/utils/patch.d.cts +1 -1
  204. package/dist/utils/patch.d.ts +1 -1
  205. package/dist/utils/platform.d.cts +6 -0
  206. package/dist/utils/platform.d.ts +6 -0
  207. package/dist/{web-socket-Zg0hj1LB.js → web-socket-CE_9Q22z.js} +5 -5
  208. package/dist/{web-socket-Zg0hj1LB.js.map → web-socket-CE_9Q22z.js.map} +1 -1
  209. package/dist/{web-socket-Cs1ZbmmN.cjs → web-socket-sm3rD-A_.cjs} +2 -2
  210. package/dist/{web-socket-Cs1ZbmmN.cjs.map → web-socket-sm3rD-A_.cjs.map} +1 -1
  211. package/dist/{web-vitals-4pWACwaR.js → web-vitals-CGwXGF-M.js} +4 -4
  212. package/dist/web-vitals-CGwXGF-M.js.map +1 -0
  213. package/dist/web-vitals-Df4Wsfx9.cjs +2 -0
  214. package/dist/web-vitals-Df4Wsfx9.cjs.map +1 -0
  215. package/dist/{worker-protocol-DFYXIFus.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
  216. package/dist/{worker-protocol-DFYXIFus.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
  217. package/dist/{worker-protocol-CYpAbrVl.js → worker-protocol-h4-tRWqy.js} +6 -6
  218. package/dist/{worker-protocol-CYpAbrVl.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
  219. package/dist/{worker-server--yGTadTA.cjs → worker-server-CF1yatXq.cjs} +2 -2
  220. package/dist/{worker-server--yGTadTA.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
  221. package/dist/worker-server-FYfKHQhJ.js +94 -0
  222. package/dist/{worker-server-BokySIII.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
  223. package/dist/{worker-transport-BdEvh_-a.cjs → worker-transport-COgY4RX8.cjs} +2 -2
  224. package/dist/{worker-transport-BdEvh_-a.cjs.map → worker-transport-COgY4RX8.cjs.map} +1 -1
  225. package/dist/{worker-transport-JK-Fby9J.js → worker-transport-jzX1IusG.js} +34 -34
  226. package/dist/{worker-transport-JK-Fby9J.js.map → worker-transport-jzX1IusG.js.map} +1 -1
  227. package/llms.txt +1 -2
  228. package/package.json +1 -1
  229. package/dist/bus-B__467mL.cjs +0 -2
  230. package/dist/bus-B__467mL.cjs.map +0 -1
  231. package/dist/bus-dw7T92sO.js.map +0 -1
  232. package/dist/config-CSNcS7OZ.js.map +0 -1
  233. package/dist/config-CybPP5VM.cjs +0 -2
  234. package/dist/config-CybPP5VM.cjs.map +0 -1
  235. package/dist/constants-BwJDXzj6.js.map +0 -1
  236. package/dist/constants-CtF52hIV.cjs +0 -2
  237. package/dist/constants-CtF52hIV.cjs.map +0 -1
  238. package/dist/errors-DP2RUm4V.cjs +0 -3
  239. package/dist/errors-DP2RUm4V.cjs.map +0 -1
  240. package/dist/errors-Q3Ng1ciC.js.map +0 -1
  241. package/dist/factory-DV17sm2p.js.map +0 -1
  242. package/dist/factory-K8O6gpux.cjs +0 -2
  243. package/dist/factory-K8O6gpux.cjs.map +0 -1
  244. package/dist/interactions-Byxf1C82.js.map +0 -1
  245. package/dist/interactions-OK85T-Dk.cjs.map +0 -1
  246. package/dist/patch-BX8KrPCT.cjs +0 -2
  247. package/dist/patch-BX8KrPCT.cjs.map +0 -1
  248. package/dist/patch-UdPz1ea8.js +0 -8
  249. package/dist/patch-UdPz1ea8.js.map +0 -1
  250. package/dist/platform-8DLhjddo.js.map +0 -1
  251. package/dist/platform-BqRc-7RO.cjs +0 -2
  252. package/dist/platform-BqRc-7RO.cjs.map +0 -1
  253. package/dist/replay-B0M8kWz_.js.map +0 -1
  254. package/dist/replay-QOFBpAXh.cjs +0 -2
  255. package/dist/replay-QOFBpAXh.cjs.map +0 -1
  256. package/dist/response-body-BWvwKQ2p.js.map +0 -1
  257. package/dist/response-body-CKEJ5itk.cjs +0 -3
  258. package/dist/response-body-CKEJ5itk.cjs.map +0 -1
  259. package/dist/rotation-BylN1B9e.js.map +0 -1
  260. package/dist/rotation-E2eKClIs.cjs +0 -2
  261. package/dist/rotation-E2eKClIs.cjs.map +0 -1
  262. package/dist/sender-Bdp-TAS4.js.map +0 -1
  263. package/dist/sender-DR7ZycZY.cjs +0 -2
  264. package/dist/sender-DR7ZycZY.cjs.map +0 -1
  265. package/dist/stored-context-BOu54M8Y.cjs +0 -2
  266. package/dist/stored-context-BOu54M8Y.cjs.map +0 -1
  267. package/dist/stored-context-CSttrAsw.js.map +0 -1
  268. package/dist/web-vitals-4pWACwaR.js.map +0 -1
  269. package/dist/web-vitals-__X7t4pj.cjs +0 -2
  270. package/dist/web-vitals-__X7t4pj.cjs.map +0 -1
  271. package/dist/worker-server-BokySIII.js +0 -94
@@ -1 +0,0 @@
1
- {"version":3,"file":"response-body-BWvwKQ2p.js","names":["ECS_VERSION","CONTENT_TYPE_NDJSON","METRIC_KEYS","RESOURCE_SERVICE_NAME","SPAN_KEYS","NANOS_PER_MILLI","MILLIS_PER_SECOND","ECS_LEVEL_NAMES","SERIALIZER_NAME_OTLP","NANOS_PATTERN","RESOURCE_BROWSER_USER_AGENT","ATTR_APP_NAMESPACE","ATTR_LOG_TYPE","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","CONTENT_TYPE_JSON","METRIC_FIELD_KEYS","isObject","_defineProperty","truncate","attributeOf","toKeyValues","groupByScope","otlpSerializer","groupByResource","TransportError","message","kind","status","retryAfterMs","maxBytes","cause","parseRetryAfter","header","seconds","date","ERROR_FIELDS","MAPPED_KEYS","toMillis","timeUnixNano","toLabelValue","value","pushLabel","existing","labels","key","flattenLabel","scalar","seen","item","name","entry","toLabels","source","errorOf","fields","field","attributes","unmapped","ecsSerializer","records","millis","record","logger","DELTA","numberOf","isNumbers","pointAttributes","keys","out","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","start","values","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","entries","group","type","named","unit","found","SPAN_KIND","STATUS_ERROR","STATUS_UNSET","FIELD_KEYS","stringOf","spanOf","parent","linkTraceId","linkSpanId","otlpTracesSerializer","resourceSpans","scope","serializerFor","choice","batchKind","only","batch","config","endpointFor","SIGNAL_SERIALIZERS","serializeBatch","error","REJECTED_FIELDS","isOtlpBatch","serializer","needsBody","response","otlp","readOptionalBody","diagnostics","readBodyText","signal","reader","abort","aborted","readChunk","decoder","text","size","chunk","maxBytesOf","parsed","hint","partialSuccessOf","partial","rejected","countOf"],"sources":["../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/otlp-traces.ts","../src/transport/serializers/select.ts","../src/transport/response-body.ts"],"sourcesContent":["// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind decides whether the engine retries, backs off or drops. Transient, offline\n * and timeout failures are retried with backoff. A throttled failure waits for the server's\n * delay, and a too_large failure splits the batch. A permanent failure is dropped, because the\n * server will never accept that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** A failed transport attempt, with its failure kind and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message);\n this.name = \"TransportError\";\n\n // Older browsers ignore the ES2022 (message, { cause }) option, so set the property the way\n // the native one does: own, writable and not enumerable.\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, writable: true, configurable: true });\n }\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. A date in the past gives a negative delay,\n * which is clamped to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n ECS_VERSION,\n LOG_TYPE_METRIC,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** The ECS field for each error attribute. */\nconst ERROR_FIELDS = {\n \"error.type\": \"type\",\n \"error.message\": \"message\",\n \"error.stack_trace\": \"stack_trace\",\n} as const;\n\n/** Attribute keys whose string value moves to an ECS field, and so leaves labels. */\nconst MAPPED_KEYS = new Set<string>([ATTR_APP_NAMESPACE, ...Object.keys(ERROR_FIELDS)]);\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the bus has only\n * passed a shape check, and BigInt throws a SyntaxError on a non-numeric string. That error\n * would lose the whole batch, not just one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input isn't numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, and that error would lose the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field, and an array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map, and a\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. Stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind, otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype, so an attribute named `__proto__` becomes a key and not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/**\n * Builds the ECS error field from the error attributes.\n * @param attributes Record attributes.\n * @returns The field, or undefined for a record without a string error attribute.\n */\nfunction errorOf(attributes: Record<string, unknown>): Record<string, string> | undefined {\n const fields: [string, string][] = [];\n\n for (const [key, field] of Object.entries(ERROR_FIELDS)) {\n const value = attributes[key];\n if (typeof value === \"string\") {\n fields.push([field, value]);\n }\n }\n\n return fields.length > 0 ? Object.fromEntries(fields) : undefined;\n}\n\n/**\n * Removes the attributes that have an ECS field. A label copy of a stack trace would double\n * the size.\n * @param attributes Record attributes.\n * @returns The attributes that go to labels.\n */\nfunction unmapped(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(attributes).filter(\n ([key, value]) => !(MAPPED_KEYS.has(key) && typeof value === \"string\"),\n ),\n );\n}\n\n/** Writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n const { attributes } = record;\n const logger = attributes[ATTR_APP_NAMESPACE];\n\n // JSON.stringify leaves out an undefined field.\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n ecs: { version: ECS_VERSION },\n log: {\n level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase(),\n logger: typeof logger === \"string\" ? logger : undefined,\n },\n event: { kind: attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC ? \"metric\" : \"event\" },\n error: errorOf(attributes),\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // A captured network event's request URL takes precedence over the page URL.\n url: {\n full: attributes[ATTR_URL_FULL] ?? attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last, so a record attribute overrides a resource key with the\n // same name.\n labels: { ...toLabels(record.resource), ...toLabels(unmapped(attributes)) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp-metrics.ts\n//\n// Serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport only\n// uses it for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_FIELD_KEYS,\n METRIC_KEYS,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** The OTLP field for each metric type. Anything that isn't a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Checks whether a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the app passed in its call. The record's context attributes\n * stay out, because a session id on every point would create a new series for every session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key from the app's call can have the same name as a metric field, and that field\n // holds the library's value. Any other metric. key, such as the web-vitals rating, is the\n // caller's own.\n const named = typeof key === \"string\" && !METRIC_FIELD_KEYS.includes(key);\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds a point's histogram fields.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut short.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A single-value histogram record, for example a long frame, has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // The library always builds complete lists, but a record from elsewhere can have lists that\n // don't line up, and a point built from those would report bogus buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // Per OTLP, a histogram with a negative value sets no sum, because a backend reads the sum\n // as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A single-value record has no interval, so its point starts and ends at its own time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A counter record from another context can hold a negative value. A monotonic sum must not\n // decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** Writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. Drops any record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/otlp-traces.ts\n//\n// Serializes span records as an OTLP/JSON ExportTraceServiceRequest. The transport\n// uses it for a batch of span records.\n\nimport { ATTR_LOG_TYPE, CONTENT_TYPE_JSON, SERIALIZER_NAME_OTLP, SPAN_KEYS } from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, groupByScope, toKeyValues } from \"./otlp\";\n\n/** The OTLP SpanKind for each of the library's span kinds. */\nconst SPAN_KIND = { internal: 1, client: 3 } as const;\n\n/** OTLP StatusCode ERROR. */\nconst STATUS_ERROR = 2;\n\n/** OTLP StatusCode UNSET. */\nconst STATUS_UNSET = 0;\n\n/** Attribute keys that hold span fields, and so aren't span attributes. */\nconst FIELD_KEYS = new Set<string>([ATTR_LOG_TYPE, ...Object.values(SPAN_KEYS)]);\n\n/**\n * Reads a string attribute.\n * @param record Span record.\n * @param key Attribute key.\n * @returns The string, or undefined.\n */\nfunction stringOf(record: LogRecord, key: string): string | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Builds one OTLP span. A record that lost a time field starts and ends at its record time.\n * @param record Span record.\n * @returns The OTLP span.\n */\nfunction spanOf(record: LogRecord): Record<string, unknown> {\n const attributes = Object.fromEntries(\n Object.entries(record.attributes).filter(([key]) => !FIELD_KEYS.has(key)),\n );\n const parent = stringOf(record, SPAN_KEYS.parentId);\n const linkTraceId = stringOf(record, SPAN_KEYS.linkTraceId);\n const linkSpanId = stringOf(record, SPAN_KEYS.linkSpanId);\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n // A root span has no parent, so leave the field out.\n ...(parent ? { parentSpanId: parent } : {}),\n ...(linkTraceId && linkSpanId\n ? {\n links: [{ traceId: linkTraceId, spanId: linkSpanId }],\n }\n : {}),\n name: record.body,\n kind: stringOf(record, SPAN_KEYS.kind) === \"client\" ? SPAN_KIND.client : SPAN_KIND.internal,\n startTimeUnixNano: stringOf(record, SPAN_KEYS.start) ?? record.timeUnixNano,\n endTimeUnixNano: stringOf(record, SPAN_KEYS.end) ?? record.timeUnixNano,\n attributes: toKeyValues(attributes),\n status: {\n code: stringOf(record, SPAN_KEYS.status) === \"error\" ? STATUS_ERROR : STATUS_UNSET,\n },\n };\n}\n\n/** Writes span records as an OTLP/JSON ExportTraceServiceRequest. */\nexport const otlpTracesSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource.\n * @param records Span records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceSpans = groupByResource(records).map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeSpans: groupByScope(group.records).map((scope) => ({\n scope: { name: scope.name },\n spans: scope.records.map(spanOf),\n })),\n }));\n\n return {\n body: JSON.stringify({ resourceSpans }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this module,\n// and config.ts keeps just the name, so the main chunk contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\nimport { otlpTracesSerializer } from \"./otlp-traces\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Returns the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A batch\n * of span records is always \"traces\" and must not go to endpoint as log records. A stored\n * record can be corrupt, and then it is neither a metric nor a span.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, \"traces\" for only span\n * records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const only = (type: string): boolean =>\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === type);\n\n if (config.metricsEndpoint !== null && only(\"metric\")) {\n return \"metrics\";\n }\n\n return only(\"span\") ? \"traces\" : \"logs\";\n}\n\n/**\n * Returns the endpoint for a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, tracesEndpoint for a traces batch, else\n * endpoint. null or \"\" means the batch has no destination.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n if (kind === \"metrics\") {\n return config.metricsEndpoint;\n }\n\n return kind === \"traces\" ? config.tracesEndpoint : config.endpoint;\n}\n\n/** Serializers for the batch kinds that don't use the configured serializer. */\nconst SIGNAL_SERIALIZERS: Partial<Record<BatchKind, LogSerializer>> = {\n metrics: otlpMetricsSerializer,\n traces: otlpTracesSerializer,\n};\n\n/**\n * Serializes a batch. Reports a serializer that throws, and the caller then drops the batch.\n * A metrics batch gets the OTLP metrics format, and a traces batch the OTLP traces format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n SIGNAL_SERIALIZERS[batchKind(batch, config)] ?? serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/response-body.ts\n//\n// Reads the small JSON answer of an ingest server on the main thread and in the worker. The\n// read stops at the request's abort signal and at RESPONSE_BODY_LIMIT_BYTES, otherwise a server\n// that sends the headers and then stalls or streams forever holds the dispatch slot.\n\nimport {\n HEADER_CONTENT_TYPE,\n HTTP_PAYLOAD_TOO_LARGE,\n RESPONSE_BODY_LIMIT_BYTES,\n SERVER_MESSAGE_MAX_CHARS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { BatchKind, SerializerChoice } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { truncate } from \"../utils/sanitize\";\n\n/** What an OTLP server rejected or warned about in a batch it accepted. */\nexport interface PartialSuccess {\n /** Number of records the server rejected. 0 means a warning only. */\n rejected: number;\n /** The server's errorMessage, cut to SERVER_MESSAGE_MAX_CHARS. Empty when it sent none. */\n message: string;\n}\n\n/** OTLP names the rejected count after the signal. */\nconst REJECTED_FIELDS: Record<BatchKind, string> = {\n logs: \"rejectedLogRecords\",\n metrics: \"rejectedDataPoints\",\n traces: \"rejectedSpans\",\n};\n\n/**\n * Checks whether a batch goes out in an OTLP format. Metrics and traces always do.\n * @param kind Kind of the batch.\n * @param serializer The log serializer option.\n * @returns True for an OTLP batch.\n */\nexport function isOtlpBatch(kind: BatchKind, serializer: SerializerChoice): boolean {\n return kind !== \"logs\" || serializer === \"otlp\";\n}\n\n/**\n * Checks whether the library reads a response's body. A 413 can carry a size hint, and an OTLP\n * answer in JSON can carry a partialSuccess.\n * @param response Response whose headers have arrived.\n * @param otlp True when the batch went out in an OTLP format.\n * @returns True when the body has something the library uses.\n */\nexport function needsBody(response: Response, otlp: boolean): boolean {\n if (response.status === HTTP_PAYLOAD_TOO_LARGE) {\n return true;\n }\n\n const type = response.headers.get(HEADER_CONTENT_TYPE) ?? \"\";\n return otlp && response.ok && type.includes(\"json\");\n}\n\n/**\n * Reads a body that only adds detail to the status. A body that fails or runs out of time gives\n * undefined, because the server has answered and a retry would send an accepted batch again.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @param diagnostics Reports a read that fails.\n * @returns The text, or undefined when the read fails or the body is larger than the limit.\n */\nexport function readOptionalBody(\n response: Response,\n signal: AbortSignal,\n diagnostics: Diagnostics,\n): Promise<string | undefined> {\n return diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the response body. It uses the status code alone.\",\n () => readBodyText(response, signal),\n );\n}\n\n/**\n * Reads a response body as text, up to RESPONSE_BODY_LIMIT_BYTES.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @returns The text, or undefined when the body is larger than the limit.\n * @throws Error when the signal aborts or the body stream fails.\n */\nasync function readBodyText(response: Response, signal: AbortSignal): Promise<string | undefined> {\n const reader = response.body?.getReader();\n if (!reader) {\n return \"\";\n }\n\n // A browser's fetch abort also fails the stream, but a body that a service worker or a test\n // builds doesn't know the signal, so race each read against it too.\n let abort!: () => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => {\n reject(new Error(\"The request ended before its body arrived.\"));\n };\n });\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n\n const readChunk = () => Promise.race([reader.read(), aborted]);\n const decoder = new TextDecoder();\n let text = \"\";\n let size = 0;\n try {\n let chunk = await readChunk();\n while (!chunk.done) {\n size += chunk.value.byteLength;\n if (size > RESPONSE_BODY_LIMIT_BYTES) {\n // Release the connection instead of downloading the rest.\n await reader.cancel();\n return undefined;\n }\n\n text += decoder.decode(chunk.value, { stream: true });\n chunk = await readChunk();\n }\n\n return text + decoder.decode();\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n}\n\n/**\n * Reads the optional size hint of a 413 body, for example {\"maxBytes\":65536}.\n * @param text The body text.\n * @returns The hint when it's a positive safe integer, otherwise undefined.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function maxBytesOf(text: string): number | undefined {\n const parsed: unknown = JSON.parse(text);\n const hint = isObject(parsed) ? parsed.maxBytes : undefined;\n\n return typeof hint === \"number\" && Number.isSafeInteger(hint) && hint > 0 ? hint : undefined;\n}\n\n/**\n * Reads the partialSuccess of an OTLP export answer, for example\n * {\"partialSuccess\":{\"rejectedLogRecords\":\"2\",\"errorMessage\":\"...\"}}.\n * @param text The answer's body text.\n * @param kind Kind of the batch, which names the count's field.\n * @returns What the server rejected or warned about, or undefined for a full success.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function partialSuccessOf(text: string, kind: BatchKind): PartialSuccess | undefined {\n // OTLP allows an empty body for a full success.\n if (text.trim() === \"\") {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(text);\n const partial = isObject(parsed) ? parsed.partialSuccess : undefined;\n if (!isObject(partial)) {\n return undefined;\n }\n\n const rejected = countOf(partial[REJECTED_FIELDS[kind]]);\n const message =\n typeof partial.errorMessage === \"string\"\n ? truncate(partial.errorMessage, SERVER_MESSAGE_MAX_CHARS)\n : \"\";\n if (rejected === 0 && message === \"\") {\n return undefined;\n }\n\n return { rejected, message };\n}\n\n/**\n * Reads an OTLP int64 count, which JSON gives as a digit string or as a number.\n * @param value The count field.\n * @returns The count, or 0 for anything that isn't a whole number above 0.\n */\nfunction countOf(value: unknown): number {\n // Up to 15 digits always fits in a safe integer.\n if (typeof value === \"string\" && /^\\d{1,15}$/.test(value)) {\n return Number(value);\n }\n\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n"],"mappings":";;;;;;;AAgBA,IAAa2B,KAAb,cAAoC,MAAM;CASxC,YACE,GACA,GACA,GACA,GACA,GACA,GACA;EAMA,AALA,MAAMC,CAAO,GAPGR,EAAA,MAAA,QAAA,KAAA,CAAA,GAEAA,EAAA,MAAA,UAAA,KAAA,CAAA,GACAA,EAAA,MAAA,gBAAA,KAAA,CAAA,GACAA,EAAA,MAAA,YAAA,KAAA,CAAA,GAJA,KAAA,OAAAS,GAEA,KAAA,SAAAC,GACA,KAAA,eAAAC,GACA,KAAA,WAAAC,GAIhB,KAAK,OAAO,kBAIRC,MAAU,KAAA,KACZ,OAAO,eAAe,MAAM,SAAS;GAAE,OAAOA;GAAO,UAAU;GAAM,cAAc;EAAK,CAAC;CAE7F;AACF;AASA,SAAgBC,EAAgB,GAA2C;CACzE,IAAI,CAACC,GACH;CAGF,IAAMC,IAAU,OAAOD,CAAM;CAC7B,IAAI,OAAO,SAASC,CAAO,GACzB,OAAO,KAAK,IAAI,GAAGA,IAAU9B,CAAiB;CAGhD,IAAM+B,IAAO,KAAK,MAAMF,CAAM;CAC9B,OAAO,OAAO,MAAME,CAAI,IAAI,KAAA,IAAY,KAAK,IAAI,GAAGA,IAAO,KAAK,IAAI,CAAC;AACvE;;ACtCA,IAAMC,IAAe;CACnB,cAAc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GF,IAAMI,IAAkB,KAAK,MAAMJ,CAAI,GACjCO,IAAUtH,EAASmH,CAAM,IAAIA,EAAO,iBAAiB,KAAA;CAC3D,IAAI,CAACnH,EAASsH,CAAO,GACnB;CAGF,IAAMC,IAAWC,GAAQF,EAAQtB,GAAgBtF,GAAM,GACjDD,IACJ,OAAO6G,EAAQ,gBAAiB,WAC5BpH,EAASoH,EAAQ,cAAA,GAAsC,IACvD;CACN,IAAIC,MAAa,KAAK9G,MAAY,IAIlC,OAAO;EAAE;EAAU;CAAQ;AAC7B;AAOA,SAAS+G,GAAQ,GAAwB;CAMvC,OAJI,OAAOhG,KAAU,YAAY,aAAa,KAAKA,CAAK,IAC/C,OAAOA,CAAK,IAGd,OAAOA,KAAU,YAAY,OAAO,cAAcA,CAAK,KAAKA,IAAQ,IAAIA,IAAQ;AACzF"}
@@ -1,3 +0,0 @@
1
- const e=require("./constants-CtF52hIV.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./defineProperty-X1c4tIPD.cjs"),r=require("./sanitize-Qj6LuZqp.cjs"),i=require("./batch-DnYRJqhU.cjs"),a=require("./otlp-CrAWkQdO.cjs");var o=class extends Error{constructor(e,t,r,i,a,o){super(t),n.t(this,`kind`,void 0),n.t(this,`status`,void 0),n.t(this,`retryAfterMs`,void 0),n.t(this,`maxBytes`,void 0),this.kind=e,this.status=r,this.retryAfterMs=i,this.maxBytes=a,this.name=`TransportError`,o!==void 0&&Object.defineProperty(this,"cause",{value:o,writable:!0,configurable:!0})}};function s(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.Ht);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var c={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},l=new Set([e.a,...Object.keys(c)]);function u(t){return e.Wt.test(t)?Number(BigInt(t)/e.Gt):Date.now()}function d(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function f(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function p(e,t,n,r){let i=d(n);if(i!==null)f(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)p(e,t,i,r);else for(let[i,a]of Object.entries(n))p(e,`${t}.${i}`,a,r);r.delete(n)}}function m(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))p(t,r,i,n);return t}function h(e){let t=[];for(let[n,r]of Object.entries(c)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function g(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(l.has(e)&&typeof t==`string`)))}var _={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=u(t.timeUnixNano),{attributes:r}=t,i=r[e.a];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.$},log:{level:e.Q[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:h(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Cn],version:t.resource[e.wn],environment:t.resource[e.yn]},user_agent:{original:t.resource[e._n]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...m(t.resource),...m(g(r))}})}).join(`
2
- `)}\n`,contentType:e.B}}},v=1;function y(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function b(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function x(t){let n=t.attributes[e.Bt.attributeKeys],r={};if(!Array.isArray(n))return r;for(let i of n){let n=typeof i==`string`&&!e.zt.includes(i)?t.attributes[i]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[i]=n)}return r}function S(t){let n=y(t,e.Bt.count);if(n===void 0){let e=y(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.Bt.bounds],i=t.attributes[e.Bt.buckets];if(!b(r)||!b(i)||i.length!==r.length+1)return null;let a=y(t,e.Bt.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:y(t,e.Bt.sum),min:a,max:y(t,e.Bt.max),bucketCounts:i.map(String),explicitBounds:r}}function C(e){let t=y(e,`metric.value`);return t===void 0?null:{asDouble:t}}function w(t,n){let r=t.attributes[e.Bt.start],i=n===`histogram`?S(t):C(t);return i===null?null:{attributes:a.i(x(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function T({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:v,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var E={name:e.Rn,serialize(t){let n=a.t(t).map(t=>{let n=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],r=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=w(e,r);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:r,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=n.get(c)??s;l.points.push(i),n.set(c,l)}return{resource:{attributes:a.i(t.resource)},scopeMetrics:[{scope:{name:e.nr,version:e.rr},metrics:[...n.values()].map(T)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.z}}},D={internal:1,client:3},O=2,k=0,A=new Set([e.g,...Object.values(e.Gn)]);function j(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function M(t){let n=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!A.has(e))),r=j(t,e.Gn.parentId),i=j(t,e.Gn.linkTraceId),o=j(t,e.Gn.linkSpanId);return{traceId:t.traceId,spanId:t.spanId,...r?{parentSpanId:r}:{},...i&&o?{links:[{traceId:i,spanId:o}]}:{},name:t.body,kind:j(t,e.Gn.kind)===`client`?D.client:D.internal,startTimeUnixNano:j(t,e.Gn.start)??t.timeUnixNano,endTimeUnixNano:j(t,e.Gn.end)??t.timeUnixNano,attributes:a.i(n),status:{code:j(t,e.Gn.status)===`error`?O:k}}}var N={name:e.Rn,serialize(t){let n=a.t(t).map(e=>({resource:{attributes:a.i(e.resource)},scopeSpans:a.n(e.records).map(e=>({scope:{name:e.name},spans:e.records.map(M)}))}));return{body:JSON.stringify({resourceSpans:n}),contentType:e.z}}};function P(e){return e===`otlp`?a.r:e===`ecs`?_:e}function F(e,t){let n=t=>e.records.length>0&&e.records.every(e=>i.t(e,`log.type`)===t);return t.metricsEndpoint!==null&&n(`metric`)?`metrics`:n(`span`)?`traces`:`logs`}function I(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var L={metrics:E,traces:N};function R(e,t,n,r){try{return(L[F(t,e)]??P(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var z={logs:`rejectedLogRecords`,metrics:`rejectedDataPoints`,traces:`rejectedSpans`};function B(e,t){return e!==`logs`||t===`otlp`}function V(e,t){if(e.status===413)return!0;let n=e.headers.get(`Content-Type`)??``;return t&&e.ok&&n.includes(`json`)}function H(e,t,n){return n.guardAsync(`transport.http_error`,`The library could not read the response body. It uses the status code alone.`,()=>U(e,t))}async function U(e,t){let n=e.body?.getReader();if(!n)return``;let r,i=new Promise((e,t)=>{r=()=>{t(Error(`The request ended before its body arrived.`))}});t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r();let a=()=>Promise.race([n.read(),i]),o=new TextDecoder,s=``,c=0;try{let e=await a();for(;!e.done;){if(c+=e.value.byteLength,c>16384){await n.cancel();return}s+=o.decode(e.value,{stream:!0}),e=await a()}return s+o.decode()}finally{t.removeEventListener(`abort`,r)}}function W(e){let n=JSON.parse(e),r=t.n(n)?n.maxBytes:void 0;return typeof r==`number`&&Number.isSafeInteger(r)&&r>0?r:void 0}function G(e,n){if(e.trim()===``)return;let i=JSON.parse(e),a=t.n(i)?i.partialSuccess:void 0;if(!t.n(a))return;let o=K(a[z[n]]),s=typeof a.errorMessage==`string`?r.i(a.errorMessage,256):``;if(o!==0||s!==``)return{rejected:o,message:s}}function K(e){return typeof e==`string`&&/^\d{1,15}$/.test(e)?Number(e):typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:0}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return N}});
3
- //# sourceMappingURL=response-body-CKEJ5itk.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"response-body-CKEJ5itk.cjs","names":["MILLIS_PER_SECOND","ATTR_APP_NAMESPACE","NANOS_PATTERN","NANOS_PER_MILLI","ECS_VERSION","ECS_LEVEL_NAMES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_BROWSER_USER_AGENT","CONTENT_TYPE_NDJSON","METRIC_KEYS","METRIC_FIELD_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","CONTENT_TYPE_JSON","ATTR_LOG_TYPE","SPAN_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","groupByScope","CONTENT_TYPE_JSON","otlpSerializer","attributeOf","isObject","truncate","require_constants","require_guards","require_defineProperty","require_sanitize","require_batch","require_otlp","TransportError","message","kind","status","retryAfterMs","maxBytes","cause","parseRetryAfter","header","seconds","date","ERROR_FIELDS","MAPPED_KEYS","toMillis","timeUnixNano","toLabelValue","value","pushLabel","existing","labels","key","flattenLabel","scalar","seen","item","name","entry","toLabels","source","errorOf","fields","field","attributes","unmapped","ecsSerializer","records","millis","record","logger","DELTA","numberOf","isNumbers","pointAttributes","keys","out","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","start","values","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","entries","group","type","named","unit","found","SPAN_KIND","STATUS_ERROR","STATUS_UNSET","FIELD_KEYS","stringOf","spanOf","parent","linkTraceId","linkSpanId","otlpTracesSerializer","resourceSpans","scope","serializerFor","choice","batchKind","only","batch","config","endpointFor","SIGNAL_SERIALIZERS","serializeBatch","error","diagnostics","REJECTED_FIELDS","isOtlpBatch","serializer","needsBody","response","otlp","readOptionalBody","readBodyText","signal","reader","abort","aborted","reject","readChunk","decoder","text","size","chunk","maxBytesOf","parsed","hint","partialSuccessOf","partial","rejected","countOf"],"sources":["../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/otlp-traces.ts","../src/transport/serializers/select.ts","../src/transport/response-body.ts"],"sourcesContent":["// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind decides whether the engine retries, backs off or drops. Transient, offline\n * and timeout failures are retried with backoff. A throttled failure waits for the server's\n * delay, and a too_large failure splits the batch. A permanent failure is dropped, because the\n * server will never accept that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** A failed transport attempt, with its failure kind and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message);\n this.name = \"TransportError\";\n\n // Older browsers ignore the ES2022 (message, { cause }) option, so set the property the way\n // the native one does: own, writable and not enumerable.\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, writable: true, configurable: true });\n }\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. A date in the past gives a negative delay,\n * which is clamped to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n ECS_VERSION,\n LOG_TYPE_METRIC,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** The ECS field for each error attribute. */\nconst ERROR_FIELDS = {\n \"error.type\": \"type\",\n \"error.message\": \"message\",\n \"error.stack_trace\": \"stack_trace\",\n} as const;\n\n/** Attribute keys whose string value moves to an ECS field, and so leaves labels. */\nconst MAPPED_KEYS = new Set<string>([ATTR_APP_NAMESPACE, ...Object.keys(ERROR_FIELDS)]);\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the bus has only\n * passed a shape check, and BigInt throws a SyntaxError on a non-numeric string. That error\n * would lose the whole batch, not just one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input isn't numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, and that error would lose the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field, and an array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map, and a\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. Stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind, otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype, so an attribute named `__proto__` becomes a key and not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/**\n * Builds the ECS error field from the error attributes.\n * @param attributes Record attributes.\n * @returns The field, or undefined for a record without a string error attribute.\n */\nfunction errorOf(attributes: Record<string, unknown>): Record<string, string> | undefined {\n const fields: [string, string][] = [];\n\n for (const [key, field] of Object.entries(ERROR_FIELDS)) {\n const value = attributes[key];\n if (typeof value === \"string\") {\n fields.push([field, value]);\n }\n }\n\n return fields.length > 0 ? Object.fromEntries(fields) : undefined;\n}\n\n/**\n * Removes the attributes that have an ECS field. A label copy of a stack trace would double\n * the size.\n * @param attributes Record attributes.\n * @returns The attributes that go to labels.\n */\nfunction unmapped(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(attributes).filter(\n ([key, value]) => !(MAPPED_KEYS.has(key) && typeof value === \"string\"),\n ),\n );\n}\n\n/** Writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n const { attributes } = record;\n const logger = attributes[ATTR_APP_NAMESPACE];\n\n // JSON.stringify leaves out an undefined field.\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n ecs: { version: ECS_VERSION },\n log: {\n level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase(),\n logger: typeof logger === \"string\" ? logger : undefined,\n },\n event: { kind: attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC ? \"metric\" : \"event\" },\n error: errorOf(attributes),\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // A captured network event's request URL takes precedence over the page URL.\n url: {\n full: attributes[ATTR_URL_FULL] ?? attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last, so a record attribute overrides a resource key with the\n // same name.\n labels: { ...toLabels(record.resource), ...toLabels(unmapped(attributes)) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp-metrics.ts\n//\n// Serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport only\n// uses it for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_FIELD_KEYS,\n METRIC_KEYS,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** The OTLP field for each metric type. Anything that isn't a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Checks whether a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the app passed in its call. The record's context attributes\n * stay out, because a session id on every point would create a new series for every session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key from the app's call can have the same name as a metric field, and that field\n // holds the library's value. Any other metric. key, such as the web-vitals rating, is the\n // caller's own.\n const named = typeof key === \"string\" && !METRIC_FIELD_KEYS.includes(key);\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds a point's histogram fields.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut short.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A single-value histogram record, for example a long frame, has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // The library always builds complete lists, but a record from elsewhere can have lists that\n // don't line up, and a point built from those would report bogus buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // Per OTLP, a histogram with a negative value sets no sum, because a backend reads the sum\n // as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A single-value record has no interval, so its point starts and ends at its own time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A counter record from another context can hold a negative value. A monotonic sum must not\n // decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** Writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. Drops any record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/otlp-traces.ts\n//\n// Serializes span records as an OTLP/JSON ExportTraceServiceRequest. The transport\n// uses it for a batch of span records.\n\nimport { ATTR_LOG_TYPE, CONTENT_TYPE_JSON, SERIALIZER_NAME_OTLP, SPAN_KEYS } from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, groupByScope, toKeyValues } from \"./otlp\";\n\n/** The OTLP SpanKind for each of the library's span kinds. */\nconst SPAN_KIND = { internal: 1, client: 3 } as const;\n\n/** OTLP StatusCode ERROR. */\nconst STATUS_ERROR = 2;\n\n/** OTLP StatusCode UNSET. */\nconst STATUS_UNSET = 0;\n\n/** Attribute keys that hold span fields, and so aren't span attributes. */\nconst FIELD_KEYS = new Set<string>([ATTR_LOG_TYPE, ...Object.values(SPAN_KEYS)]);\n\n/**\n * Reads a string attribute.\n * @param record Span record.\n * @param key Attribute key.\n * @returns The string, or undefined.\n */\nfunction stringOf(record: LogRecord, key: string): string | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Builds one OTLP span. A record that lost a time field starts and ends at its record time.\n * @param record Span record.\n * @returns The OTLP span.\n */\nfunction spanOf(record: LogRecord): Record<string, unknown> {\n const attributes = Object.fromEntries(\n Object.entries(record.attributes).filter(([key]) => !FIELD_KEYS.has(key)),\n );\n const parent = stringOf(record, SPAN_KEYS.parentId);\n const linkTraceId = stringOf(record, SPAN_KEYS.linkTraceId);\n const linkSpanId = stringOf(record, SPAN_KEYS.linkSpanId);\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n // A root span has no parent, so leave the field out.\n ...(parent ? { parentSpanId: parent } : {}),\n ...(linkTraceId && linkSpanId\n ? {\n links: [{ traceId: linkTraceId, spanId: linkSpanId }],\n }\n : {}),\n name: record.body,\n kind: stringOf(record, SPAN_KEYS.kind) === \"client\" ? SPAN_KIND.client : SPAN_KIND.internal,\n startTimeUnixNano: stringOf(record, SPAN_KEYS.start) ?? record.timeUnixNano,\n endTimeUnixNano: stringOf(record, SPAN_KEYS.end) ?? record.timeUnixNano,\n attributes: toKeyValues(attributes),\n status: {\n code: stringOf(record, SPAN_KEYS.status) === \"error\" ? STATUS_ERROR : STATUS_UNSET,\n },\n };\n}\n\n/** Writes span records as an OTLP/JSON ExportTraceServiceRequest. */\nexport const otlpTracesSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource.\n * @param records Span records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceSpans = groupByResource(records).map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeSpans: groupByScope(group.records).map((scope) => ({\n scope: { name: scope.name },\n spans: scope.records.map(spanOf),\n })),\n }));\n\n return {\n body: JSON.stringify({ resourceSpans }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this module,\n// and config.ts keeps just the name, so the main chunk contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\nimport { otlpTracesSerializer } from \"./otlp-traces\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Returns the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A batch\n * of span records is always \"traces\" and must not go to endpoint as log records. A stored\n * record can be corrupt, and then it is neither a metric nor a span.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, \"traces\" for only span\n * records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const only = (type: string): boolean =>\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === type);\n\n if (config.metricsEndpoint !== null && only(\"metric\")) {\n return \"metrics\";\n }\n\n return only(\"span\") ? \"traces\" : \"logs\";\n}\n\n/**\n * Returns the endpoint for a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, tracesEndpoint for a traces batch, else\n * endpoint. null or \"\" means the batch has no destination.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n if (kind === \"metrics\") {\n return config.metricsEndpoint;\n }\n\n return kind === \"traces\" ? config.tracesEndpoint : config.endpoint;\n}\n\n/** Serializers for the batch kinds that don't use the configured serializer. */\nconst SIGNAL_SERIALIZERS: Partial<Record<BatchKind, LogSerializer>> = {\n metrics: otlpMetricsSerializer,\n traces: otlpTracesSerializer,\n};\n\n/**\n * Serializes a batch. Reports a serializer that throws, and the caller then drops the batch.\n * A metrics batch gets the OTLP metrics format, and a traces batch the OTLP traces format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n SIGNAL_SERIALIZERS[batchKind(batch, config)] ?? serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/response-body.ts\n//\n// Reads the small JSON answer of an ingest server on the main thread and in the worker. The\n// read stops at the request's abort signal and at RESPONSE_BODY_LIMIT_BYTES, otherwise a server\n// that sends the headers and then stalls or streams forever holds the dispatch slot.\n\nimport {\n HEADER_CONTENT_TYPE,\n HTTP_PAYLOAD_TOO_LARGE,\n RESPONSE_BODY_LIMIT_BYTES,\n SERVER_MESSAGE_MAX_CHARS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { BatchKind, SerializerChoice } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { truncate } from \"../utils/sanitize\";\n\n/** What an OTLP server rejected or warned about in a batch it accepted. */\nexport interface PartialSuccess {\n /** Number of records the server rejected. 0 means a warning only. */\n rejected: number;\n /** The server's errorMessage, cut to SERVER_MESSAGE_MAX_CHARS. Empty when it sent none. */\n message: string;\n}\n\n/** OTLP names the rejected count after the signal. */\nconst REJECTED_FIELDS: Record<BatchKind, string> = {\n logs: \"rejectedLogRecords\",\n metrics: \"rejectedDataPoints\",\n traces: \"rejectedSpans\",\n};\n\n/**\n * Checks whether a batch goes out in an OTLP format. Metrics and traces always do.\n * @param kind Kind of the batch.\n * @param serializer The log serializer option.\n * @returns True for an OTLP batch.\n */\nexport function isOtlpBatch(kind: BatchKind, serializer: SerializerChoice): boolean {\n return kind !== \"logs\" || serializer === \"otlp\";\n}\n\n/**\n * Checks whether the library reads a response's body. A 413 can carry a size hint, and an OTLP\n * answer in JSON can carry a partialSuccess.\n * @param response Response whose headers have arrived.\n * @param otlp True when the batch went out in an OTLP format.\n * @returns True when the body has something the library uses.\n */\nexport function needsBody(response: Response, otlp: boolean): boolean {\n if (response.status === HTTP_PAYLOAD_TOO_LARGE) {\n return true;\n }\n\n const type = response.headers.get(HEADER_CONTENT_TYPE) ?? \"\";\n return otlp && response.ok && type.includes(\"json\");\n}\n\n/**\n * Reads a body that only adds detail to the status. A body that fails or runs out of time gives\n * undefined, because the server has answered and a retry would send an accepted batch again.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @param diagnostics Reports a read that fails.\n * @returns The text, or undefined when the read fails or the body is larger than the limit.\n */\nexport function readOptionalBody(\n response: Response,\n signal: AbortSignal,\n diagnostics: Diagnostics,\n): Promise<string | undefined> {\n return diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the response body. It uses the status code alone.\",\n () => readBodyText(response, signal),\n );\n}\n\n/**\n * Reads a response body as text, up to RESPONSE_BODY_LIMIT_BYTES.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @returns The text, or undefined when the body is larger than the limit.\n * @throws Error when the signal aborts or the body stream fails.\n */\nasync function readBodyText(response: Response, signal: AbortSignal): Promise<string | undefined> {\n const reader = response.body?.getReader();\n if (!reader) {\n return \"\";\n }\n\n // A browser's fetch abort also fails the stream, but a body that a service worker or a test\n // builds doesn't know the signal, so race each read against it too.\n let abort!: () => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => {\n reject(new Error(\"The request ended before its body arrived.\"));\n };\n });\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n\n const readChunk = () => Promise.race([reader.read(), aborted]);\n const decoder = new TextDecoder();\n let text = \"\";\n let size = 0;\n try {\n let chunk = await readChunk();\n while (!chunk.done) {\n size += chunk.value.byteLength;\n if (size > RESPONSE_BODY_LIMIT_BYTES) {\n // Release the connection instead of downloading the rest.\n await reader.cancel();\n return undefined;\n }\n\n text += decoder.decode(chunk.value, { stream: true });\n chunk = await readChunk();\n }\n\n return text + decoder.decode();\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n}\n\n/**\n * Reads the optional size hint of a 413 body, for example {\"maxBytes\":65536}.\n * @param text The body text.\n * @returns The hint when it's a positive safe integer, otherwise undefined.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function maxBytesOf(text: string): number | undefined {\n const parsed: unknown = JSON.parse(text);\n const hint = isObject(parsed) ? parsed.maxBytes : undefined;\n\n return typeof hint === \"number\" && Number.isSafeInteger(hint) && hint > 0 ? hint : undefined;\n}\n\n/**\n * Reads the partialSuccess of an OTLP export answer, for example\n * {\"partialSuccess\":{\"rejectedLogRecords\":\"2\",\"errorMessage\":\"...\"}}.\n * @param text The answer's body text.\n * @param kind Kind of the batch, which names the count's field.\n * @returns What the server rejected or warned about, or undefined for a full success.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function partialSuccessOf(text: string, kind: BatchKind): PartialSuccess | undefined {\n // OTLP allows an empty body for a full success.\n if (text.trim() === \"\") {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(text);\n const partial = isObject(parsed) ? parsed.partialSuccess : undefined;\n if (!isObject(partial)) {\n return undefined;\n }\n\n const rejected = countOf(partial[REJECTED_FIELDS[kind]]);\n const message =\n typeof partial.errorMessage === \"string\"\n ? truncate(partial.errorMessage, SERVER_MESSAGE_MAX_CHARS)\n : \"\";\n if (rejected === 0 && message === \"\") {\n return undefined;\n }\n\n return { rejected, message };\n}\n\n/**\n * Reads an OTLP int64 count, which JSON gives as a digit string or as a number.\n * @param value The count field.\n * @returns The count, or 0 for anything that isn't a whole number above 0.\n */\nfunction countOf(value: unknown): number {\n // Up to 15 digits always fits in a safe integer.\n if (typeof value === \"string\" && /^\\d{1,15}$/.test(value)) {\n return Number(value);\n }\n\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n"],"mappings":"A,kOAgBA,IAAaoC,EAA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,EACjDD,EACJ,OAAO8G,EAAQ,cAAiB,SAC5BtH,EAAAA,EAASsH,EAAQ,aAAA,GAAsC,EACvD,GACN,GAAIC,IAAa,GAAK/G,IAAY,GAIlC,MAAO,CAAE,WAAU,SAAQ,CAC7B,CAOA,SAASgH,EAAQ,EAAwB,CAMvC,OAJI,OAAOjG,GAAU,UAAY,aAAa,KAAKA,CAAK,EAC/C,OAAOA,CAAK,EAGd,OAAOA,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,EAAQ,EAAIA,EAAQ,CACzF,C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rotation-BylN1B9e.js","names":["ROUTING_KEYS","ROUTING_RESET","newId","resolveEndpoint","resolveDestination","applyResolvedConfig","resolveConfig","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","validOptions","isObject","update","pending","timeoutMs","planRotation","host","options","previous","runtime","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","clearStored","keepStored","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Runs the plan and holds the diagnostic records it raises until endRotation(), because the\n * logger drops every call during a rotation and these records belong to the next context.\n * @param plan Checks the next context's settings. It's synchronous, so nothing else is held.\n * @returns The plan's result.\n */\n holdRecords(plan: () => RotationPlan): RotationPlan;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again and writes the held diagnostic records. If a later rotation\n * waits, records stay blocked and the held ones are dropped, because they describe this context.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * It stays synchronous, because holdRecords() holds only what runs before the plan returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It throws for a setting it can't apply.\n */\nfunction planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): RotationPlan {\n const { runtime } = host;\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n plan = host.holdRecords(() => planRotation(host, update, options));\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n\n // shutdown() ran during the new sender's load, and that load stopped itself. Carry's live\n // records aren't routed yet, so they're lost. The other rules reported or stored theirs above.\n if (runtime.isDestroyed()) {\n if (rule === \"carry\") {\n host.drop(live);\n // The id is already the new one, so only these ids let a clearStorage find the old batches.\n await host.adopt(stored);\n }\n throw new Error(\"The runtime has stopped.\");\n }\n\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":";;;;;;AA2BA,IAAMO,IAAmC;CAAC;CAAW;CAAS;CAAU;AAAO,GAGzEC,IAAU,OAAO,SAAS;AA4FhC,SAASC,EACP,GACA,GACA,GACU;CACV,OAAOT,EAAa,QAAQ,MAAQ;EAClC,IAAMU,IAAiBC,EAAMC,IACvBC,IAAmBC,EAAKF;EAiB9B,OAdIF,MAAU,KAAA,IACL,KAILE,MAAQ,aACHT,EAAgBO,GAAOF,GAASO,CAAK,MAAMF,IAGhDD,MAAQ,qBAAqBA,MAAQ,mBA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AMR,EAAK,MAAMS,CAAM,IAEf,MAAM,0BAA0B;CAO5C,IAFAT,EAAK,YAAY2B,CAAG,GAEhB9B,MAAY,SAAS;EACvB,KAAK,IAAM+B,KAAUpB,GACnB,EAAK,MAAMoB,CAAM;EAInB,MAAM5B,EAAK,MAAMS,CAAM;CACzB;CAEA,EAAQ,YAAY,OAAO,oBAAoB,6CAA6C,EAC1F,WACF,CAAC;AACH"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CtF52hIV.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./identity-CvuyqZk7.cjs"),r=require("./config-CybPP5VM.cjs"),i=require("./stored-context-BOu54M8Y.cjs");var a=[`discard`,`flush`,`retain`,`carry`],o=Symbol(`refused`);function s(t,n,i){return e.Nn.filter(e=>{let a=t[e],s=n[e];return a===void 0?!1:e===`endpoint`?r.a(a,o,i)!==s:e===`metricsEndpoint`||e===`tracesEndpoint`?r.i(e,a,o,i)!==s:a===null?s!==void 0:s!==a})}function c(t,n){let r={...e.Pn};for(let i of Object.keys(t))if(e.Nn.includes(i)){let e=Reflect.get(t,i);Object.assign(r,{[i]:e})}else n.diagnostics.report(`config.invalid`,`rotateSecurityContext() ignores routing.${i}. A rotation changes only the routing settings.`);return r}function l(e,n,r){return t.n(e)&&t.n(e.routing)&&t.n(e.context??{})&&a.includes(n)&&Number.isFinite(r)&&r>=0&&r<=6e5&&(e.id===void 0||typeof e.id==`string`&&e.id.length>0)}function u(t,i,a){let{runtime:o}=t,u=a.pending??`discard`,d=a.timeoutMs??5e3;if(!l(i,u,d))throw Error(`Invalid security-context rotation options.`);let f=o.config.securityContext.id,p=i.id??n.i(o.diagnostics);if(p===f)throw Error(`A rotation requires a different security-context id.`);let m=t.allowed({...c(i.routing,o),securityContext:{id:p}}),h=r.r(m,o.diagnostics,{...o.config,...e.Pn});if(s(m,h,t.quiet).length>0)throw Error(`Invalid routing settings for the next security context.`);return{next:h,context:i.context?Object.fromEntries(Object.entries(i.context)):void 0,pending:u,timeoutMs:d,previous:f}}function d(e,t,n,r){return e===`retain`?t:e===`carry`?n:[...n,...r.flatMap(e=>e.records)]}async function f(e,t,n,a){let{runtime:o}=e,{config:s}=o,c;try{await e.senderLoaded(),c=e.holdRecords(()=>u(e,t,n))}catch(t){throw await e.closeDelivery(),t}if(o.isDestroyed())throw Error(`The runtime has stopped.`);let{next:l,context:f,pending:p,timeoutMs:m,previous:h}=c,g=new Set([s.endpoint,s.metricsEndpoint,s.tracesEndpoint]),_=new Set([l.endpoint,l.metricsEndpoint,l.tracesEndpoint]);l.capture.ignoreUrls=l.capture.ignoreUrls.filter(e=>!g.has(e)||_.has(e)),e.closeContext();let{held:v,sender:y,closed:b,carried:x}=e.takeOld(),S=b&&p===`flush`?`discard`:p,C=await y?.retire(S,m,h)??{buffered:[],stored:[]},w=[...v,...C.buffered],T=[...x,...C.stored];if(o.isDestroyed())throw e.drop(d(S,v,w,C.stored)),await e.adopt(x),Error(`The runtime has stopped.`);S!==`retain`&&S!==`carry`&&e.drop([...w,...T.flatMap(e=>e.records)]);let{diagnostics:E}=o;if(!y&&(S===`discard`||S===`flush`)){let t=x.map(e=>e.id);await E.guardAsync(`storage.degraded`,`The library could not remove the stored batches of the old context.`,()=>i.clearStored(e.storeAccess(),`context`,t))}if(S===`retain`&&(v.length>0||x.length>0)&&await E.guardAsync(`storage.degraded`,`The library could not store the records of the old context.`,()=>i.keepStored(e.storeAccess(),v,x)),o.isDestroyed())throw Error(`The runtime has stopped.`);if(l.lockConfiguration=s.lockConfiguration,r.n(s,l),e.advanceIdentity(),o.context.clear(),f&&o.context.merge(f),o.breadcrumbs.clear(),o.newSession(),o.builder.invalidateResource(),await e.openDelivery(),o.isDestroyed())throw S===`carry`&&(e.drop(w),await e.adopt(T)),Error(`The runtime has stopped.`);if(e.endRotation(a),p===`carry`){for(let t of w)e.route(t);await e.adopt(T)}o.diagnostics.report(`security.rotated`,`The runtime rotated its security context.`,{pending:p})}exports.rotateContext=f;
2
- //# sourceMappingURL=rotation-E2eKClIs.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rotation-E2eKClIs.cjs","names":["ROUTING_KEYS","resolveEndpoint","resolveDestination","ROUTING_RESET","isObject","newId","resolveConfig","clearStored","keepStored","require_constants","require_guards","require_identity","require_config","require_stored_context","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","runtime","validOptions","update","pending","timeoutMs","planRotation","host","options","previous","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Runs the plan and holds the diagnostic records it raises until endRotation(), because the\n * logger drops every call during a rotation and these records belong to the next context.\n * @param plan Checks the next context's settings. It's synchronous, so nothing else is held.\n * @returns The plan's result.\n */\n holdRecords(plan: () => RotationPlan): RotationPlan;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again and writes the held diagnostic records. If a later rotation\n * waits, records stay blocked and the held ones are dropped, because they describe this context.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * It stays synchronous, because holdRecords() holds only what runs before the plan returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It throws for a setting it can't apply.\n */\nfunction planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): RotationPlan {\n const { runtime } = host;\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n plan = host.holdRecords(() => planRotation(host, update, options));\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n\n // shutdown() ran during the new sender's load, and that load stopped itself. Carry's live\n // records aren't routed yet, so they're lost. The other rules reported or stored theirs above.\n if (runtime.isDestroyed()) {\n if (rule === \"carry\") {\n host.drop(live);\n // The id is already the new one, so only these ids let a clearStorage find the old batches.\n await host.adopt(stored);\n }\n throw new Error(\"The runtime has stopped.\");\n }\n\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":"A,kMA2BA,IAAMc,EAAmC,CAAC,UAAW,QAAS,SAAU,OAAO,EAGzEC,EAAU,OAAO,SAAS,EA4FhC,SAASC,EACP,EACA,EACA,EACU,CACV,OAAOhB,EAAAA,GAAa,OAAQ,GAAQ,CAClC,IAAMiB,EAAiBC,EAAMC,GACvBC,EAAmBC,EAAKF,GAiB9B,OAdIF,IAAU,IAAA,GACL,GAILE,IAAQ,WACHlB,EAAAA,EAAgBgB,EAAOF,EAASO,CAAK,IAAMF,EAGhDD,IAAQ,mBAAqBA,IAAQ,iBAChCjB,EAAAA,EAAmBiB,EAAKF,EAAOF,EAASO,CAAK,IAAMF,EAIrDH,IAAU,KAAOG,IAAY,IAAA,GAAYA,IAAYH,CAC9D,CAAC,CACH,CASA,SAASM,EACP,EACA,EAC8B,CAC9B,IAAMC,EAAqC,CAAE,GAAGrB,EAAAA,EAAc,EAE9D,IAAK,IAAMgB,KAAO,OAAO,KAAKM,CAAO,EACnC,GAAKzB,EAAAA,GAAmC,SAASm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