@utk09/ui-observability 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +69 -219
  2. package/README.md +24 -26
  3. package/dist/{batch-CXmPmTse.js → batch-D3NHhF9L.js} +3 -3
  4. package/dist/{batch-CXmPmTse.js.map → batch-D3NHhF9L.js.map} +1 -1
  5. package/dist/{batch-mmPigCpi.cjs → batch-DnYRJqhU.cjs} +2 -2
  6. package/dist/{batch-mmPigCpi.cjs.map → batch-DnYRJqhU.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +26 -2
  8. package/dist/bus/bus.d.ts +26 -2
  9. package/dist/bus-B__467mL.cjs +2 -0
  10. package/dist/bus-B__467mL.cjs.map +1 -0
  11. package/dist/{bus-C39wspFV.js → bus-dw7T92sO.js} +37 -24
  12. package/dist/bus-dw7T92sO.js.map +1 -0
  13. package/dist/capture/interactions.d.cts +35 -3
  14. package/dist/capture/interactions.d.ts +35 -3
  15. package/dist/capture/observed-windows.d.cts +51 -0
  16. package/dist/capture/observed-windows.d.ts +51 -0
  17. package/dist/{compression-CvED_Jel.cjs → compression-C0hUHKR-.cjs} +2 -2
  18. package/dist/{compression-CvED_Jel.cjs.map → compression-C0hUHKR-.cjs.map} +1 -1
  19. package/dist/{compression-tVtXwVjX.js → compression-SHPAvS4U.js} +2 -2
  20. package/dist/{compression-tVtXwVjX.js.map → compression-SHPAvS4U.js.map} +1 -1
  21. package/dist/{config-SgQcCP1_.js → config-CSNcS7OZ.js} +194 -196
  22. package/dist/config-CSNcS7OZ.js.map +1 -0
  23. package/dist/config-CybPP5VM.cjs +2 -0
  24. package/dist/config-CybPP5VM.cjs.map +1 -0
  25. package/dist/{console-BGgGnjSi.js → console-BsM-fSCQ.js} +4 -4
  26. package/dist/{console-BGgGnjSi.js.map → console-BsM-fSCQ.js.map} +1 -1
  27. package/dist/{console-CSZ5_Vx5.cjs → console-Dkxs6IVQ.cjs} +2 -2
  28. package/dist/{console-CSZ5_Vx5.cjs.map → console-Dkxs6IVQ.cjs.map} +1 -1
  29. package/dist/{constants-CUyd9cTZ.js → constants-BwJDXzj6.js} +23 -23
  30. package/dist/constants-BwJDXzj6.js.map +1 -0
  31. package/dist/constants-CtF52hIV.cjs +2 -0
  32. package/dist/constants-CtF52hIV.cjs.map +1 -0
  33. package/dist/constants.d.cts +12 -0
  34. package/dist/constants.d.ts +12 -0
  35. package/dist/core/diagnostics.d.cts +1 -1
  36. package/dist/core/diagnostics.d.ts +1 -1
  37. package/dist/core/rotation.d.cts +26 -2
  38. package/dist/core/rotation.d.ts +26 -2
  39. package/dist/core/runtime.d.cts +9 -0
  40. package/dist/core/runtime.d.ts +9 -0
  41. package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-B2v6Cym-.cjs} +2 -2
  42. package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-B2v6Cym-.cjs.map} +1 -1
  43. package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-Cs_YWzTa.js} +4 -4
  44. package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-Cs_YWzTa.js.map} +1 -1
  45. package/dist/doctor.cjs +1 -1
  46. package/dist/doctor.js +31 -31
  47. package/dist/doctor.js.map +1 -1
  48. package/dist/{errors-CNPbesMs.cjs → errors-DP2RUm4V.cjs} +2 -2
  49. package/dist/{errors-CNPbesMs.cjs.map → errors-DP2RUm4V.cjs.map} +1 -1
  50. package/dist/{errors-BE_EZV7Q.js → errors-Q3Ng1ciC.js} +3 -3
  51. package/dist/{errors-BE_EZV7Q.js.map → errors-Q3Ng1ciC.js.map} +1 -1
  52. package/dist/{factory-CTi0Is3F.js → factory-DV17sm2p.js} +22 -22
  53. package/dist/{factory-CTi0Is3F.js.map → factory-DV17sm2p.js.map} +1 -1
  54. package/dist/{factory-hRrH32v5.cjs → factory-K8O6gpux.cjs} +2 -2
  55. package/dist/{factory-hRrH32v5.cjs.map → factory-K8O6gpux.cjs.map} +1 -1
  56. package/dist/{identity-DdhKgrpk.js → identity-BgtHyY4u.js} +38 -27
  57. package/dist/identity-BgtHyY4u.js.map +1 -0
  58. package/dist/identity-CvuyqZk7.cjs +2 -0
  59. package/dist/identity-CvuyqZk7.cjs.map +1 -0
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +1 -0
  63. package/dist/index.d.ts +1 -0
  64. package/dist/index.js +600 -569
  65. package/dist/index.js.map +1 -1
  66. package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-D4KVcqdD.cjs} +2 -2
  67. package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-D4KVcqdD.cjs.map} +1 -1
  68. package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-e-13ZLWm.js} +17 -17
  69. package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-e-13ZLWm.js.map} +1 -1
  70. package/dist/interactions-Byxf1C82.js +207 -0
  71. package/dist/interactions-Byxf1C82.js.map +1 -0
  72. package/dist/interactions-OK85T-Dk.cjs +2 -0
  73. package/dist/interactions-OK85T-Dk.cjs.map +1 -0
  74. package/dist/{journey-D2_sia57.js → journey-C93FTYcs.js} +14 -14
  75. package/dist/{journey-D2_sia57.js.map → journey-C93FTYcs.js.map} +1 -1
  76. package/dist/{journey-B4Adltjm.cjs → journey-nMbob3OB.cjs} +2 -2
  77. package/dist/{journey-B4Adltjm.cjs.map → journey-nMbob3OB.cjs.map} +1 -1
  78. package/dist/{library-console-CPW6bvZH.cjs → library-console-DJUQzcgM.cjs} +2 -2
  79. package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DJUQzcgM.cjs.map} +1 -1
  80. package/dist/{library-console-Btrzt814.js → library-console-DklSmucS.js} +2 -2
  81. package/dist/{library-console-Btrzt814.js.map → library-console-DklSmucS.js.map} +1 -1
  82. package/dist/{library-request-BJ9PLRaD.js → library-request-UGEwOHpf.js} +2 -2
  83. package/dist/{library-request-BJ9PLRaD.js.map → library-request-UGEwOHpf.js.map} +1 -1
  84. package/dist/{library-request-D7OvTxZV.cjs → library-request-kY9iTpIF.cjs} +2 -2
  85. package/dist/{library-request-D7OvTxZV.cjs.map → library-request-kY9iTpIF.cjs.map} +1 -1
  86. package/dist/{lifecycle-22CUCrc9.js → lifecycle-B2PlIuQu.js} +2 -2
  87. package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-B2PlIuQu.js.map} +1 -1
  88. package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-DaMdH_X7.cjs} +2 -2
  89. package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-DaMdH_X7.cjs.map} +1 -1
  90. package/dist/{log-record-CkivuiEl.cjs → log-record-Bmx6etMh.cjs} +2 -2
  91. package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bmx6etMh.cjs.map} +1 -1
  92. package/dist/{log-record-BNiLfqtL.js → log-record-DSt2P-Sr.js} +2 -2
  93. package/dist/{log-record-BNiLfqtL.js.map → log-record-DSt2P-Sr.js.map} +1 -1
  94. package/dist/{long-frames-DNFaRnC3.js → long-frames-Bamjs1WV.js} +3 -3
  95. package/dist/{long-frames-DNFaRnC3.js.map → long-frames-Bamjs1WV.js.map} +1 -1
  96. package/dist/{long-frames-BUUbXd-B.cjs → long-frames-lhtONgGt.cjs} +2 -2
  97. package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-lhtONgGt.cjs.map} +1 -1
  98. package/dist/models/bus.d.cts +6 -1
  99. package/dist/models/bus.d.ts +6 -1
  100. package/dist/models/config.d.cts +23 -8
  101. package/dist/models/config.d.ts +23 -8
  102. package/dist/models/serializer.d.cts +3 -1
  103. package/dist/models/serializer.d.ts +3 -1
  104. package/dist/{network-CGMLQ-mA.cjs → network-BCn8Gn47.cjs} +2 -2
  105. package/dist/{network-CGMLQ-mA.cjs.map → network-BCn8Gn47.cjs.map} +1 -1
  106. package/dist/{network-on2zZT6H.js → network-Cg1L2w2r.js} +12 -12
  107. package/dist/{network-on2zZT6H.js.map → network-Cg1L2w2r.js.map} +1 -1
  108. package/dist/observed-windows-B3gJkdql.cjs +2 -0
  109. package/dist/observed-windows-B3gJkdql.cjs.map +1 -0
  110. package/dist/observed-windows-BrwaJNlj.js +64 -0
  111. package/dist/observed-windows-BrwaJNlj.js.map +1 -0
  112. package/dist/{otlp-BENHf3g9.cjs → otlp-CrAWkQdO.cjs} +2 -2
  113. package/dist/{otlp-BENHf3g9.cjs.map → otlp-CrAWkQdO.cjs.map} +1 -1
  114. package/dist/{otlp-DimfrRor.js → otlp-D6dRZyB8.js} +6 -6
  115. package/dist/{otlp-DimfrRor.js.map → otlp-D6dRZyB8.js.map} +1 -1
  116. package/dist/{platform-BaaFIPCU.js → platform-8DLhjddo.js} +7 -7
  117. package/dist/{platform-BaaFIPCU.js.map → platform-8DLhjddo.js.map} +1 -1
  118. package/dist/{platform-CfA3-7sJ.cjs → platform-BqRc-7RO.cjs} +2 -2
  119. package/dist/{platform-CfA3-7sJ.cjs.map → platform-BqRc-7RO.cjs.map} +1 -1
  120. package/dist/{profiler-BAZoh7A4.js → profiler-BaXSqCfz.js} +59 -59
  121. package/dist/{profiler-BAZoh7A4.js.map → profiler-BaXSqCfz.js.map} +1 -1
  122. package/dist/{profiler-D4tJpDRc.cjs → profiler-BvWW2kNM.cjs} +2 -2
  123. package/dist/{profiler-D4tJpDRc.cjs.map → profiler-BvWW2kNM.cjs.map} +1 -1
  124. package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-C4ySHN0X.js} +16 -16
  125. package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-C4ySHN0X.js.map} +1 -1
  126. package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-DeaBiB-5.cjs} +2 -2
  127. package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-DeaBiB-5.cjs.map} +1 -1
  128. package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-D7L6D_D2.cjs} +2 -2
  129. package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-D7L6D_D2.cjs.map} +1 -1
  130. package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-Dq9xe7Qn.js} +22 -22
  131. package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-Dq9xe7Qn.js.map} +1 -1
  132. package/dist/{replay-Ds-ANH34.js → replay-B0M8kWz_.js} +24 -24
  133. package/dist/{replay-Ds-ANH34.js.map → replay-B0M8kWz_.js.map} +1 -1
  134. package/dist/{replay-B3gFXIZd.cjs → replay-QOFBpAXh.cjs} +2 -2
  135. package/dist/{replay-B3gFXIZd.cjs.map → replay-QOFBpAXh.cjs.map} +1 -1
  136. package/dist/{reports-C-thq-bk.js → reports--8APRLa-.js} +3 -3
  137. package/dist/{reports-C-thq-bk.js.map → reports--8APRLa-.js.map} +1 -1
  138. package/dist/{reports-BDSe4dFH.cjs → reports-ojuMKGO7.cjs} +2 -2
  139. package/dist/{reports-BDSe4dFH.cjs.map → reports-ojuMKGO7.cjs.map} +1 -1
  140. package/dist/{resource-timing-eUl2dNgC.js → resource-timing-BzR05rE-.js} +4 -4
  141. package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-BzR05rE-.js.map} +1 -1
  142. package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-pAG3ZhB5.cjs} +2 -2
  143. package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-pAG3ZhB5.cjs.map} +1 -1
  144. package/dist/{response-body-eoSQpLiH.js → response-body-BWvwKQ2p.js} +106 -106
  145. package/dist/{response-body-eoSQpLiH.js.map → response-body-BWvwKQ2p.js.map} +1 -1
  146. package/dist/{response-body-YdNl-HkR.cjs → response-body-CKEJ5itk.cjs} +3 -3
  147. package/dist/{response-body-YdNl-HkR.cjs.map → response-body-CKEJ5itk.cjs.map} +1 -1
  148. package/dist/{rotation-Cwct4ckk.js → rotation-BylN1B9e.js} +10 -11
  149. package/dist/rotation-BylN1B9e.js.map +1 -0
  150. package/dist/rotation-E2eKClIs.cjs +2 -0
  151. package/dist/rotation-E2eKClIs.cjs.map +1 -0
  152. package/dist/{sampling-mXt4dstx.cjs → sampling-B46LW0cy.cjs} +2 -2
  153. package/dist/{sampling-mXt4dstx.cjs.map → sampling-B46LW0cy.cjs.map} +1 -1
  154. package/dist/{sampling-BlrI8jor.js → sampling-zXA6r-Nw.js} +16 -16
  155. package/dist/{sampling-BlrI8jor.js.map → sampling-zXA6r-Nw.js.map} +1 -1
  156. package/dist/{sanitize-Ba0KqU06.js → sanitize-DjnR6RXR.js} +2 -2
  157. package/dist/{sanitize-Ba0KqU06.js.map → sanitize-DjnR6RXR.js.map} +1 -1
  158. package/dist/{sanitize-DQyiI_KY.cjs → sanitize-Qj6LuZqp.cjs} +2 -2
  159. package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-Qj6LuZqp.cjs.map} +1 -1
  160. package/dist/{sender-Dv8rAmpV.js → sender-Bdp-TAS4.js} +71 -71
  161. package/dist/{sender-Dv8rAmpV.js.map → sender-Bdp-TAS4.js.map} +1 -1
  162. package/dist/{sender-BdRuNVhF.cjs → sender-DR7ZycZY.cjs} +2 -2
  163. package/dist/{sender-BdRuNVhF.cjs.map → sender-DR7ZycZY.cjs.map} +1 -1
  164. package/dist/{stored-context-CXt7eHZL.cjs → stored-context-BOu54M8Y.cjs} +2 -2
  165. package/dist/{stored-context-CXt7eHZL.cjs.map → stored-context-BOu54M8Y.cjs.map} +1 -1
  166. package/dist/{stored-context-B2EzVuYm.js → stored-context-CSttrAsw.js} +6 -6
  167. package/dist/{stored-context-B2EzVuYm.js.map → stored-context-CSttrAsw.js.map} +1 -1
  168. package/dist/{storm-C-zYSdDX.cjs → storm-BHgI12iS.cjs} +2 -2
  169. package/dist/{storm-C-zYSdDX.cjs.map → storm-BHgI12iS.cjs.map} +1 -1
  170. package/dist/{storm-DjKetLKZ.js → storm-DKlpv0FL.js} +2 -2
  171. package/dist/{storm-DjKetLKZ.js.map → storm-DKlpv0FL.js.map} +1 -1
  172. package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-BYPYYkQ5.cjs} +2 -2
  173. package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-BYPYYkQ5.cjs.map} +1 -1
  174. package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-BcOB8A2e.js} +2 -2
  175. package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-BcOB8A2e.js.map} +1 -1
  176. package/dist/{user-timing-BePqb1uN.js → user-timing-4KIJ74Vi.js} +2 -2
  177. package/dist/{user-timing-BePqb1uN.js.map → user-timing-4KIJ74Vi.js.map} +1 -1
  178. package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BsU2wQKE.cjs} +2 -2
  179. package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BsU2wQKE.cjs.map} +1 -1
  180. package/dist/utils/identity.d.cts +5 -0
  181. package/dist/utils/identity.d.ts +5 -0
  182. package/dist/{web-socket-CoIUBM3C.cjs → web-socket-Cs1ZbmmN.cjs} +2 -2
  183. package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-Cs1ZbmmN.cjs.map} +1 -1
  184. package/dist/{web-socket-DSHgDiZ6.js → web-socket-Zg0hj1LB.js} +4 -4
  185. package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-Zg0hj1LB.js.map} +1 -1
  186. package/dist/{worker-protocol-x074Rpet.js → worker-protocol-CYpAbrVl.js} +4 -4
  187. package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-CYpAbrVl.js.map} +1 -1
  188. package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-DFYXIFus.cjs} +2 -2
  189. package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-DFYXIFus.cjs.map} +1 -1
  190. package/dist/{worker-server-CFe4nvos.cjs → worker-server--yGTadTA.cjs} +2 -2
  191. package/dist/{worker-server-CFe4nvos.cjs.map → worker-server--yGTadTA.cjs.map} +1 -1
  192. package/dist/{worker-server-iUVSjH8L.js → worker-server-BokySIII.js} +25 -25
  193. package/dist/{worker-server-iUVSjH8L.js.map → worker-server-BokySIII.js.map} +1 -1
  194. package/dist/worker-transport-BdEvh_-a.cjs +2 -0
  195. package/dist/worker-transport-BdEvh_-a.cjs.map +1 -0
  196. package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-JK-Fby9J.js} +23 -19
  197. package/dist/worker-transport-JK-Fby9J.js.map +1 -0
  198. package/llms.txt +13 -10
  199. package/package.json +13 -5
  200. package/dist/bus-C39wspFV.js.map +0 -1
  201. package/dist/bus-_EaOVPGq.cjs +0 -2
  202. package/dist/bus-_EaOVPGq.cjs.map +0 -1
  203. package/dist/config-DUs7uHHt.cjs +0 -2
  204. package/dist/config-DUs7uHHt.cjs.map +0 -1
  205. package/dist/config-SgQcCP1_.js.map +0 -1
  206. package/dist/constants-CUyd9cTZ.js.map +0 -1
  207. package/dist/constants-CqdJhTxH.cjs +0 -2
  208. package/dist/constants-CqdJhTxH.cjs.map +0 -1
  209. package/dist/identity-DdhKgrpk.js.map +0 -1
  210. package/dist/identity-DlWRIuwy.cjs +0 -2
  211. package/dist/identity-DlWRIuwy.cjs.map +0 -1
  212. package/dist/interactions-CUkzK8sR.cjs +0 -2
  213. package/dist/interactions-CUkzK8sR.cjs.map +0 -1
  214. package/dist/interactions-DiFvCosX.js +0 -111
  215. package/dist/interactions-DiFvCosX.js.map +0 -1
  216. package/dist/rotation-Cwct4ckk.js.map +0 -1
  217. package/dist/rotation-D4qUAHAu.cjs +0 -2
  218. package/dist/rotation-D4qUAHAu.cjs.map +0 -1
  219. package/dist/worker-transport-CRAX-09c.cjs +0 -2
  220. package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
  221. package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
package/dist/doctor.js CHANGED
@@ -1,13 +1,13 @@
1
- import { V as e, Vn as t, dt as n, ft as r, ht as i, lt as a, mt as o, nn as s, pn as c, pt as l, rn as u, tt as d, ut as f, z as p } from "./constants-CUyd9cTZ.js";
2
- import { t as m } from "./compression-tVtXwVjX.js";
3
- import { r as h } from "./otlp-DimfrRor.js";
1
+ import { V as e, Wn as t, an as n, dt as r, ft as i, gn as a, gt as o, ht as s, mt as c, nt as l, on as u, pt as d, ut as f, z as p } from "./constants-BwJDXzj6.js";
2
+ import { t as m } from "./compression-SHPAvS4U.js";
3
+ import { r as h } from "./otlp-D6dRZyB8.js";
4
4
  // src/doctor.ts
5
5
  var g = 1e4, _ = 0, v = 1, y = 2, b = "Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.", x = "--header", S = "--replay", C = "--credentials", w = "include", T = 5e6, ee = 5, E = "uiobs-doctor", te = /^([\w!#$%&'*+.^`|~-]+): *([\x20-\x7e]+)$/, ne = "<hidden>", D = "Access-Control-Expose-Headers", O = "Access-Control-Allow-Origin", k = "Access-Control-Allow-Headers", A = "Access-Control-Allow-Credentials", j = "A browser refuses * with credentials: \"include\".", M = "A browser does not read * as a wildcard with credentials: \"include\".", re = "A browser never lets * cover authorization.", ie = "Add --credentials include to check that case.", N = [
6
+ d,
7
+ i,
6
8
  r,
7
- n,
8
- f,
9
- a
10
- ].map((e) => e.toLowerCase()), ae = [...N, "origin"], P = [i, l].map((e) => e.toLowerCase()), F = "authorization", I = [o.toLowerCase()], oe = [...I, ...P];
9
+ f
10
+ ].map((e) => e.toLowerCase()), ae = [...N, "origin"], P = [o, c].map((e) => e.toLowerCase()), F = "authorization", I = [s.toLowerCase()], oe = [...I, ...P];
11
11
  function se() {
12
12
  let e = crypto.randomUUID().replaceAll("-", "");
13
13
  return {
@@ -101,38 +101,38 @@ function Y(e, t) {
101
101
  return `${k} must include ${n.join(", ")}.${r}${i}`;
102
102
  })];
103
103
  }
104
- function X({ url: e, origin: t, custom: n }, i, o) {
105
- return (s, c, l, u = {}) => L(e, {
104
+ function X({ url: e, origin: t, custom: n }, i, a) {
105
+ return (o, s, c, l = {}) => L(e, {
106
106
  method: "POST",
107
107
  headers: {
108
108
  ...n,
109
109
  Origin: t,
110
- [r]: i,
111
- [f]: s,
112
- [a]: String(c),
113
- ...u
110
+ [d]: i,
111
+ [r]: o,
112
+ [f]: String(s),
113
+ ...l
114
114
  },
115
- body: l
116
- }, o);
115
+ body: c
116
+ }, a);
117
117
  }
118
- async function Z(e, t, r) {
119
- let i = await m(r);
120
- return i ? e(t, 0, i, { [n]: d }) : "This Node version has no CompressionStream.";
118
+ async function Z(e, t, n) {
119
+ let r = await m(n);
120
+ return r ? e(t, 0, r, { [i]: l }) : "This Node version has no CompressionStream.";
121
121
  }
122
- async function Q(t, n, i = {}, a = !1) {
123
- let o = H(t, n, i, a), c = U(o), l = await J(o), { body: d, contentType: f } = h.serialize([se()]), p = X(o, f), m = crypto.randomUUID(), g = await p(m, 0, d), _ = await p(m, 1, d), v = await Z(p, crypto.randomUUID(), d), y = new URL(t);
124
- y.searchParams.set(s, crypto.randomUUID()), y.searchParams.set(u, "pagehide");
122
+ async function Q(t, r, i = {}, a = !1) {
123
+ let o = H(t, r, i, a), s = U(o), c = await J(o), { body: l, contentType: f } = h.serialize([se()]), p = X(o, f), m = crypto.randomUUID(), g = await p(m, 0, l), _ = await p(m, 1, l), v = await Z(p, crypto.randomUUID(), l), y = new URL(t);
124
+ y.searchParams.set(n, crypto.randomUUID()), y.searchParams.set(u, "pagehide");
125
125
  let b = o.requestHeaders.length > N.length ? void 0 : await L(y.toString(), {
126
126
  method: "POST",
127
127
  headers: {
128
- Origin: n,
129
- [r]: e
128
+ Origin: r,
129
+ [d]: e
130
130
  },
131
- body: d
131
+ body: l
132
132
  }), x = typeof g == "string" ? [] : z(g, D, P, !o.credentials), S = x.length > 0 ? ` Optional headers stay hidden: ${x.join(", ")}.` : "", C = G(q(g, D, oe), o, M);
133
133
  return [
134
- ...Y(l, o),
135
- V("test batch", g, `The server accepted a test batch.${G(W(g) === "*", o)}`, B, c),
134
+ ...Y(c, o),
135
+ V("test batch", g, `The server accepted a test batch.${G(W(g) === "*", o)}`, B, s),
136
136
  V("exposed headers", g, `The server exposes Retry-After.${S}${C}`, (e) => z(e, D, I, !o.credentials).length === 0 ? void 0 : `${D} must include retry-after.${K(e, D, o)}`),
137
137
  V("gzip", v, "The server accepted a gzip batch.", B),
138
138
  V("deduplication", _, "The server accepted a repeated batch id. A client cannot see if it stored the batch again.", B),
@@ -144,8 +144,8 @@ async function Q(t, n, i = {}, a = !1) {
144
144
  ];
145
145
  }
146
146
  async function $(e, t, n = {}, r = !1) {
147
- let i = H(e, t, n, r), a = U(i), o = await J(i), s = crypto.randomUUID(), l = {
148
- "replay.id": s,
147
+ let i = H(e, t, n, r), o = U(i), s = await J(i), c = crypto.randomUUID(), l = {
148
+ "replay.id": c,
149
149
  "session.id": crypto.randomUUID(),
150
150
  "tab.id": crypto.randomUUID(),
151
151
  "service.name": E
@@ -164,10 +164,10 @@ async function $(e, t, n = {}, r = !1) {
164
164
  bytes: JSON.stringify(n).length,
165
165
  events: n
166
166
  });
167
- }, d = (e) => `${s}-${String(e)}`, f = X(i, p), m = u(0, "uiobs doctor test event"), h = await f(d(0), 0, m), g = await f(d(0), 1, m), _ = await Z(f, d(1), u(1, "uiobs doctor gzip event")), v = await X(i, p, c)(d(2), 0, u(2, "x".repeat(T)));
167
+ }, d = (e) => `${c}-${String(e)}`, f = X(i, p), m = u(0, "uiobs doctor test event"), h = await f(d(0), 0, m), g = await f(d(0), 1, m), _ = await Z(f, d(1), u(1, "uiobs doctor gzip event")), v = await X(i, p, a)(d(2), 0, u(2, "x".repeat(T)));
168
168
  return [
169
- ...Y(o, i),
170
- V("test segment", h, `The server accepted a test segment.${G(W(h) === "*", i)}`, B, a),
169
+ ...Y(s, i),
170
+ V("test segment", h, `The server accepted a test segment.${G(W(h) === "*", i)}`, B, o),
171
171
  V("gzip", _, "The server accepted a gzip segment.", B),
172
172
  V("large segment", v, `The server accepted a segment of ${String(T)} bytes without gzip.`, (e) => e.ok ? void 0 : `The server returned ${String(e.status)} for a segment of ${String(T)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`),
173
173
  V("deduplication", g, "The server accepted a repeated batch id. A client cannot see if it stored the segment again.", B)
@@ -1 +1 @@
1
- {"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","CONTENT_TYPE_TEXT_PLAIN","SEVERITY_NUMBER","HEADER_CONTENT_ENCODING","HEADER_CONTENT_TYPE","HEADER_SAMPLING","HEADER_ATTEMPT","HEADER_RETRY_AFTER","QUERY_PARAM_BATCH_ID","REQUEST_TIMEOUT_MS$1","HEADER_DATE","QUERY_PARAM_EXIT_REASON","ENCODING_GZIP","HEADER_BATCH_ID","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtBnC;CACAD;CACAU;CACAP;AACF,CAAC,CAAC,KAAK,MAASkC,EAAK,YAAY,CAAC,GAG5BC,KAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACrC,GAAiBK,CAAW,CAAC,CAAC,KAAK,MAAS8B,EAAK,YAAY,CAAC,GAGlFG,IAAsB,iBA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,aAAa,KAAK,UAAUhB,EAAK,IAAIM,EAAa,CAAC,GAAG,GACrDlH;CAGT,IAAM,EAAE,YAAS,mBAAgB2H,GAC3BE,IAAU,OAAOH,IAAS3B,IAAkBX,EAAA,CAAWvD,GAAK4B,GAAQqE,GAAStE,CAAW;CAE9F,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYqE,GACnC,EAAM,GAAGE,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOJ,EAAQ,OAAO,EAAE,cAAWE,CAAI,IAAIjI,IAAYC;AACzD"}
1
+ {"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","CONTENT_TYPE_TEXT_PLAIN","SEVERITY_NUMBER","QUERY_PARAM_BATCH_ID","HEADER_BATCH_ID","HEADER_CONTENT_ENCODING","REQUEST_TIMEOUT_MS$1","HEADER_SAMPLING","HEADER_RETRY_AFTER","HEADER_DATE","ENCODING_GZIP","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtB3B;CACAP;CACAD;CACAS;AACF,CAAC,CAAC,KAAK,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IAASD,EAAK,MAAM,CAAC,IAAIA,CAAI;CAE1D,IACEF,MAAY,YACZC,MAAS,cACT,CAACV,GAAUjF,CAAG,KACd,CAACwF,GAAS5D,CAAM,KAChB,CAACkE,GAID,OAFAC,EAAM3H,CAAK,GACX2H,EAAM,aAAa,KAAK,UAAUhB,EAAK,IAAIM,EAAa,CAAC,GAAG,GACrDlH;CAGT,IAAM,EAAE,YAAS,mBAAgB2H,GAC3BE,IAAU,OAAOH,IAAS3B,IAAkBX,EAAA,CAAWvD,GAAK4B,GAAQqE,GAAStE,CAAW;CAE9F,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYqE,GACnC,EAAM,GAAGE,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOJ,EAAQ,OAAO,EAAE,cAAWE,CAAI,IAAIjI,IAAYC;AACzD"}
@@ -1,3 +1,3 @@
1
- const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-CfA3-7sJ.cjs"),n=require("./storm-C-zYSdDX.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");function i(t){if(e.r(t)){let e=(t.stack??``).split(`
1
+ const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-BqRc-7RO.cjs"),n=require("./storm-BHgI12iS.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");function i(t){if(e.r(t)){let e=(t.stack??``).split(`
2
2
  `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var a=class{constructor(e){r.t(this,`ctx`,void 0),r.t(this,`name`,`errors`),r.t(this,`installed`,!1),r.t(this,`seen`,new Map),r.t(this,`window`,{start:0,count:0}),r.t(this,`onError`,e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=t.i(r,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":t.i(i.filename,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),"error.line":i.lineno,"error.column":i.colno})}),r.t(this,`onRejection`,e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})}),this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}report(e,t,r){if(!n.t(this.window,this.ctx.config.captureLimits.errorsPerWindow,this.ctx.diagnostics,`errors`,this.ctx.config.captureLimits.windowMs))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>i(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<this.ctx.config.captureLimits.errorDedupeMs){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...r,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=a;
3
- //# sourceMappingURL=errors-CNPbesMs.cjs.map
3
+ //# sourceMappingURL=errors-DP2RUm4V.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-CNPbesMs.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","require_defineProperty","signatureOf","value","frame","message","ErrorCapture","target","event","resourceUrl","url","errorEvent","fallback","error","ctx","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"A,+JAiCA,SAASO,EAAY,EAA2B,CAC9C,GAAIP,EAAAA,EAAYQ,CAAK,EAAG,CACt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G,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASP,IAAU,IAAA,GAAgB,MAAMR,CAAO,EAAIQ,EAC1D,KAAK,IAAI,OAAO,MAAMR,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF,E"}
1
+ {"version":3,"file":"errors-DP2RUm4V.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","require_defineProperty","signatureOf","value","frame","message","ErrorCapture","target","event","resourceUrl","url","errorEvent","fallback","error","ctx","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"A,+JAiCA,SAASO,EAAY,EAA2B,CAC9C,GAAIP,EAAAA,EAAYQ,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgB3C,YAAY,EAAsC,CAArBL,EAAA,EAAA,KAAA,MAAA,IAAA,EAAA,EAd7BA,EAAA,EAAA,KAAA,OAAgB,QAAA,EAGhBA,EAAA,EAAA,KAAA,YAAoB,EAAA,EAGpBA,EAAA,EAAA,KAAA,OAAwB,IAAI,GAAuB,EAGnDA,EAAA,EAAA,KAAA,SAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,CAAA,EAgC5DA,EAAA,EAAA,KAAA,UAA4B,GAAoC,CAC9D,IAAMM,EAASC,EAAM,OACfC,EAAcF,GAAQ,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AAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CA8EA,OAAe,EAAgB,EAAgB,EAAsC,CACnF,GACE,CAACjB,EAAAA,EACC,KAAK,OACL,KAAK,IAAI,OAAO,cAAc,gBAC9B,KAAK,IAAI,YACT,SACA,KAAK,IAAI,OAAO,cAAc,QAChC,EAEA,OAGF,IAAMkB,EAAM,KAAK,IAAI,EAGf,CAAE,UAAS,OAAQ,KAAK,IAAI,YAAY,MAC5C,wBACA,6FACMb,EAAYW,CAAK,CACzB,GAAK,CAAE,QAAS,GAAI,IAAK,GAAG,OAAOA,EAAM,GAAI,EACvCG,EAAW,KAAK,KAAK,IAAIC,CAAG,EAElC,GAAID,GAAYD,EAAMC,EAAS,GAAK,KAAK,IAAI,OAAO,cAAc,cAAe,CAC/E,EAAS,QACT,EAAS,GAAKD,EACd,MACF,CAIA,IAAMG,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASP,IAAU,IAAA,GAAgB,MAAMR,CAAO,EAAIQ,EAC1D,KAAK,IAAI,OAAO,MAAMR,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF,E"}
@@ -1,6 +1,6 @@
1
1
  import { r as e } from "./error-like-B11pB4aL.js";
2
- import { i as t } from "./platform-BaaFIPCU.js";
3
- import { t as n } from "./storm-DjKetLKZ.js";
2
+ import { i as t } from "./platform-8DLhjddo.js";
3
+ import { t as n } from "./storm-DKlpv0FL.js";
4
4
  import { t as r } from "./defineProperty-s2S8BXUc.js";
5
5
  // src/capture/errors.ts
6
6
  function i(t) {
@@ -83,4 +83,4 @@ var a = class {
83
83
  };
84
84
  export { a as ErrorCapture };
85
85
 
86
- //# sourceMappingURL=errors-BE_EZV7Q.js.map
86
+ //# sourceMappingURL=errors-Q3Ng1ciC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BE_EZV7Q.js","names":["isErrorLike","recordedUrl","allowInWindow","_defineProperty","signatureOf","value","frame","message","ErrorCapture","target","event","resourceUrl","url","errorEvent","fallback","error","ctx","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAiCA,SAASI,EAAY,GAA2B;CAC9C,IAAIJ,EAAYK,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgB3C,YAAY,GAAsC;EAArB,AAAAL,EAAA,MAAA,OAAA,KAAA,CAAA,GAd7BA,EAAA,MAAA,QAAgB,QAAA,GAGhBA,EAAA,MAAA,aAAoB,EAAA,GAGpBA,EAAA,MAAA,wBAAwB,IAAI,IAAuB,CAAA,GAGnDA,EAAA,MAAA,UAAuC;GAAE,OAAO;GAAG,OAAO;EAAE,CAAA,GAgC5DA,EAAA,MAAA,YAA4B,MAAoC;GAC9D,IAAMM,IAASC,EAAM,QACfC,IAAcF,GAAQ,OAAOA,GAAQ,QAAQ;GAGnD,IACEA,MAAW,QACXA,MAAY,cACZE,MAAgB,IAChB;IACA,IAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,gBAC3B;IAKF,IAAMC,IAAMX,EACVU,GACA,KAAK,IAAI,OAAO,QAAQ,UACxB,KAAK,IAAI,OAAO,QAAQ,cACxB,KAAK,IAAI,WACX;IAOA,AALA,KAAK,IAAI,YAAY,KAAK;KACxB,GAAG,KAAK,IAAI;KACZ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WAAQ,KAAK,IAAI,YAAY,MAC5C,yBACA,gGACMb,EAAYW,CAAK,CACzB,KAAK;GAAE,SAAS;GAAI,KAAK,GAAG,OAAOA,EAAM;EAAI,GACvCG,IAAW,KAAK,KAAK,IAAIC,CAAG;EAElC,IAAID,KAAYD,IAAMC,EAAS,KAAK,KAAK,IAAI,OAAO,cAAc,eAAe;GAE/E,AADA,EAAS,SACT,EAAS,KAAKD;GACd;EACF;EAIA,IAAMG,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASP,MAAU,KAAA,IAAgB,MAAMR,CAAO,IAAIQ;EAC1D,KAAK,IAAI,OAAO,MAAMR,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"errors-Q3Ng1ciC.js","names":["isErrorLike","recordedUrl","allowInWindow","_defineProperty","signatureOf","value","frame","message","ErrorCapture","target","event","resourceUrl","url","errorEvent","fallback","error","ctx","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAiCA,SAASI,EAAY,GAA2B;CAC9C,IAAIJ,EAAYK,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgB3C,YAAY,GAAsC;EAArB,AAAAL,EAAA,MAAA,OAAA,KAAA,CAAA,GAd7BA,EAAA,MAAA,QAAgB,QA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0BH;EAC5B,CAAC;CACH;AACF"}
@@ -1,6 +1,6 @@
1
- import { E as e, Jn as t, Un as n, Wn as r, Xn as i, Yn as a, et as o, qn as s } from "./constants-CUyd9cTZ.js";
1
+ import { $n as e, E as t, Kn as n, Qn as r, Xn as i, Zn as a, qn as o, tt as s } from "./constants-BwJDXzj6.js";
2
2
  import { t as c } from "./defineProperty-s2S8BXUc.js";
3
- import { i as l, n as u, r as d } from "./batch-CXmPmTse.js";
3
+ import { i as l, n as u, r as d } from "./batch-D3NHhF9L.js";
4
4
  import { n as f } from "./deadline-C4ccAuk5.js";
5
5
  // src/models/storage.ts
6
6
  function p(e) {
@@ -80,20 +80,20 @@ function y(e, t) {
80
80
  let n = t.guard("storage.degraded", "An emergency entry is not valid JSON. The library dropped it.", () => JSON.parse(e));
81
81
  return n === void 0 ? null : l(n) ? n : (t.report("storage.degraded", "An emergency entry is not a batch. The library dropped it."), null);
82
82
  }
83
- async function b(e, t, n, i) {
84
- let a = 0;
85
- for (let o of v(i, t)) {
86
- let i = t.guard("storage.unavailable", "The library could not read the emergency queue.", () => {
87
- let e = localStorage.getItem(o), r = e ? y(e, t) : null;
88
- return r && !n(r) ? null : (localStorage.removeItem(o), r);
83
+ async function b(e, t, n, r) {
84
+ let i = 0;
85
+ for (let a of v(r, t)) {
86
+ let r = t.guard("storage.unavailable", "The library could not read the emergency queue.", () => {
87
+ let e = localStorage.getItem(a), r = e ? y(e, t) : null;
88
+ return r && !n(r) ? null : (localStorage.removeItem(a), r);
89
89
  });
90
- if (i) try {
91
- await f(e.save(i), r), a++;
90
+ if (r) try {
91
+ await f(e.save(r), o), i++;
92
92
  } catch (e) {
93
- t.report("storage.degraded", "The library could not recover an emergency batch.", { key: o }, e);
93
+ t.report("storage.degraded", "The library could not recover an emergency batch.", { key: a }, e);
94
94
  }
95
95
  }
96
- return a;
96
+ return i;
97
97
  }
98
98
  function x(e, t, n) {
99
99
  let r = w(e.persistenceNamespace), i = `writing the emergency queue, ${String(e.records.length)} records`, a = [], o = t.guard("storage.quota_exceeded", i, () => {
@@ -125,7 +125,7 @@ function C(e, t, n = "", r = !1) {
125
125
  });
126
126
  }
127
127
  function w(e = "") {
128
- return e ? `ui-observability:namespaced:${encodeURIComponent(e)}:emergency:` : o;
128
+ return e ? `ui-observability:namespaced:${encodeURIComponent(e)}:emergency:` : s;
129
129
  }
130
130
  // src/storage/eviction.ts
131
131
  function T(e) {
@@ -164,8 +164,8 @@ function A(e, t) {
164
164
  return Number.isFinite(r) ? r : null;
165
165
  }
166
166
  var j = class {
167
- constructor(t, n, r, i = e) {
168
- c(this, "limits", void 0), c(this, "diagnostics", void 0), c(this, "onGap", void 0), c(this, "prefix", void 0), c(this, "name", s), this.limits = t, this.diagnostics = n, this.onGap = r, this.prefix = i;
167
+ constructor(e, n, r, a = t) {
168
+ c(this, "limits", void 0), c(this, "diagnostics", void 0), c(this, "onGap", void 0), c(this, "prefix", void 0), c(this, "name", i), this.limits = e, this.diagnostics = n, this.onGap = r, this.prefix = a;
169
169
  }
170
170
  save(e) {
171
171
  if (this.write(e, "localStorage refused a batch, evicting the oldest")) {
@@ -303,8 +303,8 @@ var j = class {
303
303
  return v(this.prefix, this.diagnostics);
304
304
  }
305
305
  }, M = class {
306
- constructor(e, n) {
307
- c(this, "limits", void 0), c(this, "onGap", void 0), c(this, "name", t), c(this, "batches", []), this.limits = e, this.onGap = n;
306
+ constructor(e, t) {
307
+ c(this, "limits", void 0), c(this, "onGap", void 0), c(this, "name", a), c(this, "batches", []), this.limits = e, this.onGap = t;
308
308
  }
309
309
  async save(e) {
310
310
  let t = this.batches.findIndex((t) => t.id === e.id);
@@ -360,7 +360,7 @@ function N(e) {
360
360
  return e ? `${n}:${e}` : n;
361
361
  }
362
362
  var P = (e) => ({
363
- name: a,
363
+ name: r,
364
364
  save: (t) => (e?.({
365
365
  batches: 1,
366
366
  records: t.records.length,
@@ -381,8 +381,8 @@ var P = (e) => ({
381
381
  function F(e) {
382
382
  return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
383
383
  }
384
- function I(e) {
385
- return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(i, "1"), localStorage.removeItem(i), !0)) === !0;
384
+ function I(t) {
385
+ return t.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(e, "1"), localStorage.removeItem(e), !0)) === !0;
386
386
  }
387
387
  async function L(e, t, n, r, i, a = "") {
388
388
  if (e === "none") return P(i);
@@ -390,7 +390,7 @@ async function L(e, t, n, r, i, a = "") {
390
390
  if (e === "indexeddb" || e === "auto") {
391
391
  if (F(r)) {
392
392
  let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
393
- let { IndexedDbStorage: e } = await import("./indexeddb-storage-GHdl0t8A.js"), a = new e(t, n, r, i);
393
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-e-13ZLWm.js"), a = new e(t, n, r, i);
394
394
  return await a.open(), a;
395
395
  });
396
396
  if (e) return e;
@@ -401,4 +401,4 @@ async function L(e, t, n, r, i, a = "") {
401
401
  }
402
402
  export { E as a, S as c, h as d, m as f, k as i, x as l, N as n, T as o, p, O as r, C as s, L as t, g as u };
403
403
 
404
- //# sourceMappingURL=factory-CTi0Is3F.js.map
404
+ //# sourceMappingURL=factory-DV17sm2p.js.map