@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
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-CqdJhTxH.cjs","names":["SESSION_IDLE_MS","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","SEVERITY_NUMBER","LEVEL_ORDER","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_URL_FULL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","ATTR_SANITIZE_FAILED","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","ATTR_CLOCK_OFFSET_MS","ATTR_DEBUG_BUFFER","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","TELEMETRY_SDK_LANGUAGE","SERIALIZER_NAME_OTLP","ECS_LEVEL_NAMES","ECS_VERSION","CONTENT_TYPE_JSON","CONTENT_TYPE_NDJSON","NANOS_PER_MILLI","NANOS_PATTERN","HEADER_CONTENT_TYPE","HEADER_CONTENT_ENCODING","HEADER_RETRY_AFTER","HEADER_BATCH_ID","HEADER_ATTEMPT","HEADER_SAMPLING","HEADER_DATE","ENCODING_GZIP","MILLIS_PER_SECOND","BEACON_LIMIT_BYTES","RESPONSE_BODY_LIMIT_BYTES","CONTENT_TYPE_TEXT_PLAIN","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","BATCH_STORAGE_KEY_PREFIX","EMERGENCY_STORAGE_KEY_PREFIX","STORAGE_PROBE_KEY","QUOTA_EXCEEDED_ERROR","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","STORAGE_NAME_LOCAL","STORAGE_NAME_MEMORY","STORAGE_NAME_NONE","DRAIN_LOCK_NAME","EMERGENCY_LOCK_NAME","JOURNEY_STORAGE_KEY","JOURNEY_ID_PATTERN","JOURNEY_CLOCK_SKEW_MS","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LEVEL_BYPASS_TYPES","LOG_TYPE_METRIC","LOG_TYPE_ACTION","LOG_TYPE_SPAN","BUS_PROTOCOL","BUS_TYPE","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","LIBRARY_REQUEST_KEY","LIBRARY_CONSOLE_KEY","TRANSPORT_CALL_KEY","ERROR_STORM_WINDOW_MS","ACTION_ATTRIBUTE_DEFAULT","IGNORE_SELECTOR","RAGE_CLICK_WINDOW_MS","DEAD_CLICK_MS","DEAD_CLICK_CONTROLS","CONSOLE_DEFAULT_STYLES","GAP_REPORT_THROTTLE_MS","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DIAGNOSTICS_NAMESPACE","DEFAULT_METRIC_UNIT","METRIC_NAMESPACE","ATTR_METRIC_OVERFLOW","METRIC_DEFAULT_BOUNDARIES","METRIC_KEYS","METRIC_FIELD_KEYS","PROFILE_MAX_US","PROFILE_METRIC_NAME","PROFILE_KEYS","PROFILE_FRAME_METRIC_NAME","PROFILE_FRAME_PROBE","INSTRUMENT_OPTIONS_FAULT","REPLAY_ID_KEY","REPLAY_UNMASK_ATTRIBUTE","PROFILER_PROBE_LIMIT","PROFILER_GLOBAL_KEY","PROFILER_CALIBRATION_PAIRS","TRACE_NAMESPACE","SPAN_KEYS","TRANSPORT_WORKER_PROTOCOL","TRANSPORT_WORKER_TYPE","TRANSPORT_WORKER_REFUSAL","WORKER_REPLY_GRACE_MS","DEFER_IDLE_TIMEOUT_MS","DEFER_QUEUE_LIMIT","RESOURCE_SLOW_MS","SERVER_TIMING_HEADER","SERVER_TIMING_MAX_CHARS","REMOTE_CAPTURE_FLAGS","UNKNOWN_SERVICE_NAME","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","REMOTE_SAMPLING_POLL_MS","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","CONSOLE_DEFAULT_LEVEL","LOG_FLUSH_INTERVAL_MS","METRIC_INTERVAL_MS","REQUEST_TIMEOUT_MS","COMPRESSION_THRESHOLD_BYTES","STORAGE_DB_NAME","STORAGE_LIMITS","STORAGE_DEADLINE_MS","FLUSH_TIMEOUT_MS","FLUSH_TIMEOUT_MAX_MS","RETRY_BASE_DELAY_MS","RETRY_MAX_DELAY_MS","RETRY_IDLE_DELAY_MS","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","BUS_FLUSH_GAP_MS","FLUSH_REQUEST_SHARE","BUS_MAX_BOOT_BUFFER_ACTIONS","ERROR_DEDUPE_MS","RECORD_LIMITS","ROUTING_RESET","ROUTING_KEYS","DEFAULT_CONFIG"],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// Every limit, threshold, timing window, storage key, pattern and default the\n// library uses.\n\nimport type { ConsoleStyles, ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\nimport type { StorageLimits } from \"./models/storage\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/**\n * Throttle window per diagnostic code, in milliseconds. Limits how often an error\n * loop can call the handler.\n */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** sessionStorage key for a live page's marker. A clean close removes it. */\nexport const ALIVE_KEY = \"ui-observability.alive\";\n\n/** How often the alive marker is updated, in milliseconds. */\nexport const ALIVE_UPDATE_MS = 30_000;\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Maps each log level to its OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// The attribute and resource key names records carry in the payload. They follow the\n// OpenTelemetry conventions, and the `uiobs.` prefix marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** A record's sequence number within its context. Starts at 1. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** The document URL at the time the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL` for it,\n * because the page URL overwrites the request target under that key.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/** An Error reason's own fields, or the whole reason when it isn't an Error. */\nexport const ATTR_ERROR_DATA = \"error.data\";\n\n/** An error record's breadcrumb history. */\nexport const ATTR_BREADCRUMBS = \"breadcrumbs\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Server time minus client time, in milliseconds, from an accepted answer's Date header. */\nexport const ATTR_CLOCK_OFFSET_MS = \"uiobs.clock_offset_ms\";\n\n/** Marks a record the debug buffer held until an error. */\nexport const ATTR_DEBUG_BUFFER = \"uiobs.debug_buffer\";\n\n/** Half the HTTP Date header's resolution. Centers the clock offset's error. */\nexport const DATE_HEADER_HALF_STEP_MS = 500;\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. The build writes the package.json version here.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = __UIOBS_VERSION__;\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/**\n * ECS `log.level` names that differ from the lowercase severity text. ECS spells\n * the warning level out in full, and every other level matches in lowercase.\n * @see {@link SERIALIZER_NAME_ECS}\n */\nexport const ECS_LEVEL_NAMES: Partial<Record<LogLevel, string>> = { WARN: \"warning\" };\n\n/** The ECS version of the documents, the same one the Elastic ECS logging libraries write. */\nexport const ECS_VERSION = \"8.10.0\";\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch in decimal digits, for example \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Response header that carries sampling rules from the ingest server. */\nexport const HEADER_SAMPLING = \"X-UiObs-Sampling\";\n\n/** Response header that gives the server time. The server must expose it to CORS. */\nexport const HEADER_DATE = \"Date\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** Lowest valid HTTP status code. */\nexport const HTTP_STATUS_MIN = 100;\n\n/** Highest valid HTTP status code. */\nexport const HTTP_STATUS_MAX = 599;\n\n/** Lowest HTTP status code that accepts a batch. */\nexport const HTTP_SUCCESS_MIN = 200;\n\n/** Lowest HTTP status code above the success range. */\nexport const HTTP_SUCCESS_END = 300;\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. The transport can retry. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large. The transport must split the batch. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 415, unsupported media type. A stock OpenTelemetry Collector gives it to a text/plain batch. */\nexport const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Largest ingest response body the library reads, in bytes. It skips a larger body. */\nexport const RESPONSE_BODY_LIMIT_BYTES = 16_384;\n\n/** Longest server message that a diagnostic repeats. The server controls this text. */\nexport const SERVER_MESSAGE_MAX_CHARS = 256;\n\n/** Content type for an exit payload. CORS-safelisted, so it doesn't trigger a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a stored batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch stored by the exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Maximum number of exit batches in the emergency queue. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key we write to check whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store to evict on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/**\n * Native IndexedDB version. Version 11 replaced Dexie, and version 12 adds the context index.\n * Dexie opened this database at ten times its declared version, so a version below 11 makes\n * open() fail with VersionError on an existing installation, and then nothing can read its\n * batches.\n */\nexport const INDEXEDDB_SCHEMA_VERSION = 12;\n\n/** IndexedDB object store that holds the batches. The name dates from Dexie, since removed. */\nexport const INDEXEDDB_STORE_NAME = \"batches\";\n\n/** Index on the batch store that orders reads by creation time. */\nexport const INDEXEDDB_CREATED_AT_INDEX = \"createdAt\";\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** Name of the storage adapter that keeps nothing. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max length of a journey id from startJourney(), in characters. A journey with an id this long\n * and a full-length name still gets a token below the token limit.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_ID_MAX_CHARS = 64;\n\n/**\n * Accepted journey id from startJourney(): letters, digits, \"_\", \".\", \":\" and \"-\". Every\n * character is one byte in UTF-8. A multibyte id would push the token over its limit.\n */\nexport const JOURNEY_ID_PATTERN = new RegExp(`^[\\\\w.:-]{1,${String(JOURNEY_ID_MAX_CHARS)}}$`);\n\n/**\n * How far ahead of this clock a journey token's start time can be, in milliseconds. Two machines\n * can disagree on the time, but a token further ahead than this would never expire.\n */\nexport const JOURNEY_CLOCK_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Max whole-token length, in characters. This only rejects an oversized token. It doesn't\n * validate the token's content.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()`, in milliseconds. After that, the\n * runtime carries on without a seeded journey.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/**\n * W3C trace context header name\n * @see {@link TRACEPARENT_VERSION}\n */\nexport const TRACEPARENT_HEADER = \"traceparent\";\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants. The sampler uses them to turn a sampling key into a\n// stable 0-1 fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n/**\n * Types that minLevel never drops. An action is an audit fact, and a metric or a span is a\n * measurement. The remote rate cap for records below minLevel doesn't apply to them either.\n */\nexport const LEVEL_BYPASS_TYPES: readonly LogType[] = [\"action\", \"metric\", \"span\"];\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n/** Record kind of an audit fact. Storage and the hold buffers drop it last. */\nexport const LOG_TYPE_ACTION: LogType = \"action\";\n\n/** Record kind routed to the trace stream. */\nexport const LOG_TYPE_SPAN: LogType = \"span\";\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. The bus drops an envelope with a different version. */\nexport const BUS_PROTOCOL = \"ui-observability/2\";\n\n/**\n * Type tag for every bus message. Every frame must use the same values. The prefix makes a\n * message easy to spot in a postMessage log, but it is still the BUS_PROTOCOL envelope tag that\n * separates the bus from other traffic.\n */\nexport const BUS_TYPE = {\n hello: \"ui-observability.message.hello\",\n welcome: \"ui-observability.message.welcome\",\n records: \"ui-observability.message.records\",\n securityContext: \"ui-observability.message.security-context\",\n journey: \"ui-observability.message.journey\",\n journeyRequest: \"ui-observability.message.journey-request\",\n sampling: \"ui-observability.message.sampling\",\n samplingRequest: \"ui-observability.message.sampling-request\",\n tab: \"ui-observability.message.tab\",\n flushRequest: \"ui-observability.message.flush-request\",\n flushResult: \"ui-observability.message.flush-result\",\n} as const;\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n/** Global key for the runtime shutdown() stopped. Calls go to it until the next configure(). */\nexport const RUNTIME_STOPPED_KEY = \"ui-observability.stopped\";\n\n/** Global symbol key for the library request scope count, shared by every copy on the page. */\nexport const LIBRARY_REQUEST_KEY = \"ui-observability.request-scope\";\n\n/** Global symbol key for the library console scope count, shared by every copy on the page. */\nexport const LIBRARY_CONSOLE_KEY = \"ui-observability.console-scope\";\n\n/** Global symbol key for the number of custom transport calls still waiting for an answer. */\nexport const TRANSPORT_CALL_KEY = \"ui-observability.transport-calls\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/**\n * Default length of the capture rate limit window, and of the replay upload and error ceiling\n * windows, in milliseconds.\n */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/**\n * Max ERROR and FATAL records the pipeline admits per storm window. This is a safety limit for\n * a render loop, not a way to shape normal traffic. ERROR and FATAL records skip sampling, so a\n * direct logger.error call has no other limit.\n */\nexport const ERROR_CEILING_MAX_PER_WINDOW = 500;\n\n/** Default minimum duration for a long frame to be recorded, in milliseconds. */\nexport const LONG_FRAME_THRESHOLD_MS = 100;\n\n/** Maximum long frames recorded per storm window, so a frozen tab can't flood the pipeline. */\nexport const LONG_FRAME_MAX_PER_WINDOW = 20;\n\n/** Max WebSocket events recorded per storm window, so a reconnect loop can't flood the pipeline. */\nexport const WEBSOCKET_MAX_PER_WINDOW = 20;\n\n/** Maximum character length of a console breadcrumb message. */\nexport const CONSOLE_BREADCRUMB_MAX_CHARS = 200;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum characters of a clicked element's text kept in a breadcrumb. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Attribute that names a click action, unless the app configures a different one. */\nexport const ACTION_ATTRIBUTE_DEFAULT = \"data-observability-action\";\n\n/**\n * Selector for the regions the app keeps out of the records. Click capture skips them by\n * default, and session replay always blocks them, so a hidden region can't leak through either.\n */\nexport const IGNORE_SELECTOR = \"[data-observability-ignore]\";\n\n/** How many clicks on one element make a rage click, by default. */\nexport const RAGE_CLICK_COUNT = 3;\n\n/** The time window a rage click's clicks must fall within, in milliseconds, by default. */\nexport const RAGE_CLICK_WINDOW_MS = 1000;\n\n/** How long to wait for a visible response before a click counts as dead, in milliseconds. */\nexport const DEAD_CLICK_MS = 1000;\n\n/** Controls that should respond visibly to a click. Only these get a dead click check. */\nexport const DEAD_CLICK_CONTROLS =\n 'a, button, summary, input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"], [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"tab\"]';\n\n/** Maximum characters of an aria-label kept in a generated selector. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names per element in a generated CSS selector. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** Default CSS for the console prefix. The colors are readable in light and dark devtools. */\nexport const CONSOLE_DEFAULT_STYLES: Readonly<Required<ConsoleStyles>> = {\n namespace: \"color:#888\",\n TRACE: \"color:#888;font-weight:bold\",\n DEBUG: \"color:#888;font-weight:bold\",\n INFO: \"color:#1e6fd9;font-weight:bold\",\n WARN: \"color:#c77700;font-weight:bold\",\n ERROR: \"color:#d32f2f;font-weight:bold\",\n FATAL: \"color:#d32f2f;font-weight:bold\",\n};\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum time between storage gap warning reports, in milliseconds. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for records the auto-capture modules emit. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for records the storage subsystems emit. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Namespace for the records `diagnostics.records` produces. */\nexport const DIAGNOSTICS_NAMESPACE = \"uiobs.diagnostics\";\n\n/** The measurement unit used when a call doesn't give one. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n/** Namespace for the points the counter and histogram instruments produce. */\nexport const METRIC_NAMESPACE = \"uiobs.metrics\";\n\n/** Maximum attribute sets per instrument per interval. Any more go into one overflow set. */\nexport const METRIC_MAX_SERIES = 100;\n\n/** Maximum bucket boundaries per histogram. More than that makes for a large point. */\nexport const METRIC_MAX_BOUNDARIES = 50;\n\n/** Attribute on the overflow set. OpenTelemetry uses the same key. */\nexport const ATTR_METRIC_OVERFLOW = \"otel.metric.overflow\";\n\n/** Default histogram boundaries, the same as OpenTelemetry's defaults. */\nexport const METRIC_DEFAULT_BOUNDARIES: readonly number[] = [\n 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000,\n];\n\n/**\n * Attribute keys on an aggregated metric point, read by the OTLP metrics serializer.\n * Sampling keeps every record that has a start time, because sampling a sum gives a false sum.\n */\nexport const METRIC_KEYS = {\n start: \"metric.start_time_unix_nano\",\n attributeKeys: \"metric.attribute_keys\",\n count: \"metric.count\",\n sum: \"metric.sum\",\n min: \"metric.min\",\n max: \"metric.max\",\n bounds: \"metric.bounds\",\n buckets: \"metric.bucket_counts\",\n} as const;\n\n/**\n * Every metric field the library writes on a metric record. The OTLP metrics serializer keeps\n * them off a point's attributes, because the record holds the library's value under that name.\n */\nexport const METRIC_FIELD_KEYS: readonly string[] = [\n \"metric.name\",\n \"metric.value\",\n \"metric.unit\",\n \"metric.type\",\n ...Object.values(METRIC_KEYS),\n];\n\n/** Precision of the profiler histogram: 2^4 = 16 sub-buckets per power of two. */\nexport const PROFILE_SUB_BITS = 4;\n\n/** Buckets per probe: 16 for 0 to 15 us, then 16 for each exponent from 4 to 25. */\nexport const PROFILE_BUCKETS = 368;\n\n/** Largest tracked duration in microseconds (2^26 - 1). Larger values go in the last bucket. */\nexport const PROFILE_MAX_US = 67_108_863;\n\n/** Cap on the buckets in one profiler summary record, to keep the payload small. */\nexport const PROFILE_POINT_BUCKETS = 100;\n\n/** Default probe limit. The runtime fixes the limit at startup. */\nexport const PROFILER_MAX_PROBES = 64;\n\n/** Metric name for profiler summary records. */\nexport const PROFILE_METRIC_NAME = \"ui.profile.duration\";\n\n/** Attribute keys on profiler summary records. */\nexport const PROFILE_KEYS = {\n probe: \"profile.probe\",\n sampleEvery: \"profile.sample_every\",\n p50: \"profile.p50\",\n p90: \"profile.p90\",\n p99: \"profile.p99\",\n overhead: \"profile.overhead_ns\",\n selfP99: \"profile.self_p99\",\n framePhase: \"profile.frame_phase\",\n} as const;\n\n/** How deep spans can nest and still get a self time. Going deeper drops the frames below. */\nexport const PROFILER_STACK_DEPTH = 32;\n\n/** How many recent spans the profiler keeps for linking to long animation frames. */\nexport const PROFILER_RING_SPANS = 256;\n\n/** Shortest span, in ms, that gets linked to a long animation frame. */\nexport const PROFILER_LINK_MIN_MS = 1;\n\n/** Metric name for long animation frame phases, reported per probe in the frame. */\nexport const PROFILE_FRAME_METRIC_NAME = \"ui.profile.frame.duration\";\n\n/** Probe name for frame pacing. Each value is the time between two frames. */\nexport const PROFILE_FRAME_PROBE = \"frame.interval\";\n\n/** Reported when the library can't read an instrument's options. */\nexport const INSTRUMENT_OPTIONS_FAULT =\n \"The library could not read the options of an instrument. The library uses the defaults.\";\n\n/** Ambient attribute that ties every record to the session replay recording. */\nexport const REPLAY_ID_KEY = \"replay.id\";\n\n/** Put this attribute on an element to leave its text unmasked in session replay. */\nexport const REPLAY_UNMASK_ATTRIBUTE = \"data-observability-unmask\";\n\n/** Hard cap on registered probe names, and so the upper bound for profiler.maxProbes. */\nexport const PROFILER_PROBE_LIMIT = 1024;\n\n/** Global symbol key for the profiler core. Copies of the same library version share the core. */\nexport const PROFILER_GLOBAL_KEY = \"ui-observability.profiler\";\n\n/** Minimum window for the profiler's overhead measurement, in ms. */\nexport const PROFILER_CALIBRATION_MS = 2;\n\n/** Cap on begin()/end() pairs in the profiler's overhead measurement. */\nexport const PROFILER_CALIBRATION_PAIRS = 100_000;\n\n/** Namespace of the span records. */\nexport const TRACE_NAMESPACE = \"uiobs.traces\";\n\n/** Attribute keys for the span fields on a span record, read by the traces serializer. */\nexport const SPAN_KEYS = {\n kind: \"span.kind\",\n parentId: \"span.parent_id\",\n start: \"span.start_time_unix_nano\",\n end: \"span.end_time_unix_nano\",\n status: \"span.status\",\n linkTraceId: \"span.link.trace_id\",\n linkSpanId: \"span.link.span_id\",\n} as const;\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Protocol for the private transport worker channel. */\nexport const TRANSPORT_WORKER_PROTOCOL = \"ui-observability.transport/1\";\n\n/** Type tags for the private transport worker messages. */\nexport const TRANSPORT_WORKER_TYPE = {\n connect: \"connect\",\n ready: \"ready\",\n send: \"send\",\n result: \"result\",\n cancel: \"cancel\",\n} as const;\n\n/** The worker entry's refusal message. A constant keeps the protocol code out of the main chunk. */\nexport const TRANSPORT_WORKER_REFUSAL = {\n p: TRANSPORT_WORKER_PROTOCOL,\n v: TELEMETRY_SDK_VERSION,\n t: TRANSPORT_WORKER_TYPE.ready,\n ok: false,\n} as const;\n\n/** Maximum requests in one transport worker. */\nexport const TRANSPORT_WORKER_MAX_JOBS = 64;\n\n/**\n * Extra wait for the transport worker's answer after the request deadline. The worker replies\n * with a status it got in time when the deadline ends its body read, and that reply needs a\n * message hop.\n */\nexport const WORKER_REPLY_GRACE_MS = 1_000;\n\n/** Longest the deferred logger waits for idle time before it builds its records. */\nexport const DEFER_IDLE_TIMEOUT_MS = 1000;\n\n/** Maximum pending payload references per runtime. A full queue builds its records first. */\nexport const DEFER_QUEUE_LIMIT = 1000;\n\n/** Default minimum duration for a slow resource event, in milliseconds. */\nexport const RESOURCE_SLOW_MS = 1000;\n\n/** Response header with server duration entries. */\nexport const SERVER_TIMING_HEADER = \"Server-Timing\";\n\n/** Maximum Server-Timing header length and entry count. */\nexport const SERVER_TIMING_MAX_CHARS = 4096;\nexport const SERVER_TIMING_MAX_ENTRIES = 32;\n\n/** Capture switches a remote rule can change. Privacy controls stay local. */\nexport const REMOTE_CAPTURE_FLAGS = [\n \"errors\",\n \"rejections\",\n \"resourceErrors\",\n \"fetch\",\n \"xhr\",\n \"httpMetrics\",\n \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"interactions\",\n \"console\",\n \"webSocket\",\n \"uncleanExit\",\n \"userTiming\",\n \"serverTiming\",\n \"reports\",\n \"resourceTiming\",\n \"lifecycle\",\n] as const;\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/** The remote sampling rules version this library accepts. */\nexport const REMOTE_SAMPLING_VERSION = 1;\n\n/** Maximum length of the sampling header, in characters. */\nexport const REMOTE_SAMPLING_MAX_CHARS = 4096;\n\n/** Longest that remote sampling rules stay in effect, in milliseconds. */\nexport const REMOTE_SAMPLING_MAX_TTL_MS = 60 * 60 * 1000;\n\n/** Maximum namespace rates in one set of remote sampling rules. */\nexport const REMOTE_SAMPLING_MAX_RATES = 100;\n\n/** How often a forwarder asks for the remote sampling rules, in milliseconds. */\nexport const REMOTE_SAMPLING_POLL_MS = 30_000;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\n \"contextProvider\",\n \"redact\",\n \"onDiagnostic\",\n \"onDrop\",\n \"headers\",\n \"serializer\",\n \"otelLoader\",\n \"transport\",\n \"transportOnExit\",\n \"transportWorker\",\n] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\n \"captureLimits\",\n \"metadata\",\n \"storage\",\n \"diagnostics\",\n \"correlation\",\n \"metrics\",\n \"buffering\",\n \"delivery\",\n \"loggerCache\",\n \"securityContext\",\n \"sampling\",\n \"bus\",\n \"journey\",\n \"batching\",\n \"retention\",\n \"limits\",\n \"capture\",\n \"debugBuffer\",\n \"profiler\",\n \"replay\",\n] as const;\n\n/**\n * Section keys with no default, excluded from their section of `DEFAULT_CONFIG`.\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const UNDEFAULTED_SECTION_KEYS: Record<(typeof CONFIG_SECTIONS)[number], string[]> = {\n captureLimits: [],\n metadata: [],\n storage: [],\n diagnostics: [],\n correlation: [],\n metrics: [],\n buffering: [],\n delivery: [],\n loggerCache: [],\n securityContext: [],\n sampling: [],\n bus: [],\n journey: [],\n batching: [],\n retention: [],\n limits: [],\n capture: [\"urlTransform\"],\n debugBuffer: [],\n profiler: [],\n replay: [],\n};\n\n/** Console output level used when a consumer passes `consoleOutput: true`. */\nexport const CONSOLE_DEFAULT_LEVEL: LogLevel = \"DEBUG\";\n\n// ----------------------------------\n// Batching\n// ----------------------------------\n\n/** Max time a partial log batch waits before the pipeline sends it, in milliseconds. */\nexport const LOG_FLUSH_INTERVAL_MS = 2000;\n\n/** Max records per log batch. At this count, the pipeline sends the batch early. */\nexport const LOG_BATCH_SIZE = 100;\n\n/**\n * Default interval of the counter, histogram and profiler points, in milliseconds. A partial\n * metric batch waits this long too, longer than a log batch, because metrics have a higher\n * volume and no caller is waiting for them.\n */\nexport const METRIC_INTERVAL_MS = 10_000;\n\n/** Max records per metric batch. At this count, the pipeline sends the batch early. */\nexport const METRIC_BATCH_SIZE = 500;\n\n/** Max concurrent ingest requests, across both streams. */\nexport const MAX_CONCURRENT_REQUESTS = 2;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Max time for one ingest request, in milliseconds. The transport then aborts and retries it. */\nexport const REQUEST_TIMEOUT_MS = 15_000;\n\n/** Min payload size to compress, in bytes. */\nexport const COMPRESSION_THRESHOLD_BYTES = 1024;\n\n// ----------------------------------\n// Storage retention\n// ----------------------------------\n\n/** IndexedDB database name. */\nexport const STORAGE_DB_NAME = \"UiObservability\";\n\n/** Capacity and retention thresholds every storage adapter enforces. */\nexport const STORAGE_LIMITS: StorageLimits = {\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n};\n\n/**\n * Max time for one storage call, in milliseconds. After that the call counts as failed, because\n * a call that never settles would hold on to a dispatch slot or the drain flag.\n */\nexport const STORAGE_DEADLINE_MS = 10_000;\n\n/** Default wait of flush() and of a rotation's flush, in milliseconds. */\nexport const FLUSH_TIMEOUT_MS = 5000;\n\n/**\n * Longest wait of flush() and of a rotation's flush, in milliseconds. A browser timer fires at\n * once for a delay above 2^31 - 1 ms, so the wait has a ceiling.\n */\nexport const FLUSH_TIMEOUT_MAX_MS = 600_000;\n\n// ----------------------------------\n// Retry backoff\n// ----------------------------------\n\n/** First backoff step, in milliseconds. Doubles with every attempt. */\nexport const RETRY_BASE_DELAY_MS = 2000;\n\n/** Backoff ceiling, in milliseconds. */\nexport const RETRY_MAX_DELAY_MS = 60_000;\n\n/** How often to check for stored work when nothing has failed recently, in milliseconds. */\nexport const RETRY_IDLE_DELAY_MS = 30_000;\n\n// ----------------------------------\n// Journey lifetime\n// ----------------------------------\n\n/** Max time a journey stays open, in milliseconds. After that it counts as abandoned. */\nexport const JOURNEY_MAX_AGE_MS = 30 * 60 * 1000;\n\n/** True if the journey ends for all contexts when the owning context closes. */\nexport const JOURNEY_END_ON_OWNER_CLOSE = false;\n\n/** Query parameter checked at boot for a seeded journey token. */\nexport const JOURNEY_URL_PARAM = \"__uiobs_journey\";\n\n// ----------------------------------\n// Bus handshake\n// ----------------------------------\n\n/** BroadcastChannel name for the control plane. */\nexport const BUS_CHANNEL_NAME = \"ui_observability_control\";\n\n/** Max time a forwarder waits for an owner to answer before it promotes itself, in milliseconds. */\nexport const BUS_HANDSHAKE_TIMEOUT_MS = 1500;\n\n/** Handshake attempts allowed before a cross-origin forwarder promotes itself to sender. */\nexport const BUS_MAX_HANDSHAKE_ATTEMPTS = 3;\n\n/**\n * Max named sources, for example OpenFin identities, whose message rate the bus tracks at once.\n * A new source past it is refused, so a flood of fake names can't grow the map without end.\n */\nexport const BUS_MAX_TRACKED_SOURCES = 256;\n\n/**\n * Max flush requests from other contexts that wait for the next flush. A request past it gets\n * no answer, so a flood of requests can't grow the list without end.\n */\nexport const BUS_MAX_FLUSH_REQUESTS = 100;\n\n/** Max flush requests of one source that wait, so one frame can't fill the whole list. */\nexport const BUS_MAX_FLUSH_REQUESTS_PER_SOURCE = 4;\n\n/**\n * Min time between the starts of two flushes that the bus runs for other contexts, in\n * milliseconds. A request in the gap joins the next one, so a flood can't flush without a pause.\n */\nexport const BUS_FLUSH_GAP_MS = 1000;\n\n/**\n * Share of a forwarder's time left that it gives its sender in a flush request. The rest is for\n * the answer, so the caller's wait outlasts the callee's deadline at each hop of a chain.\n */\nexport const FLUSH_REQUEST_SHARE = 0.9;\n\n/** Default of buffering.maxHeldRecords, the cap on non-action records in one hold buffer. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n/** Max action records in one hold buffer. Their own cap means a log storm can't push one out. */\nexport const BUS_MAX_BOOT_BUFFER_ACTIONS = 2000;\n\n/**\n * Records of each kind that a full hold buffer never drops, counted from the first one. The\n * first error of a failed startup is usually the cause, so it has to outlive the storm.\n */\nexport const HOLD_BUFFER_HEAD_RECORDS = 100;\n\n/** Max distinct values in each list of an onDrop summary. */\nexport const DROP_SUMMARY_MAX_ITEMS = 20;\n\n/**\n * Max characters of an untrusted message type in a diagnostic detail, since the sender controls\n * that text. The longest BUS_TYPE value is 41 characters, so every valid type fits.\n */\nexport const BUS_TYPE_DETAIL_MAX_CHARS = 48;\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Breadcrumbs kept as context for the next error. */\nexport const MAX_BREADCRUMBS = 50;\n\n/** How long identical errors are counted without being sent again, in milliseconds. */\nexport const ERROR_DEDUPE_MS = 5000;\n\n// ----------------------------------\n// Per-record size caps\n// ----------------------------------\n\n/** Size caps for every record, applied after sanitize and after redact. */\nexport const RECORD_LIMITS = {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxNodes: 10_000,\n maxRecordBytes: 32_768,\n};\n\n// ----------------------------------\n// Config defaults\n// ----------------------------------\n\n/**\n * Routing settings a rotation resets when the update leaves them out. The rotation also spreads\n * this into its base, where undefined means no hook, so an undefined key in the update resets too.\n */\nexport const ROUTING_RESET = {\n endpoint: null,\n metricsEndpoint: null,\n tracesEndpoint: null,\n headers: undefined,\n credentials: \"omit\",\n transport: undefined,\n transportOnExit: undefined,\n transportWorker: undefined,\n} as const;\n\n/** Routing settings that configure() can't change while isolation is on. */\nexport const ROUTING_KEYS = Object.keys(ROUTING_RESET) as (keyof typeof ROUTING_RESET)[];\n\n/**\n * The default runtime config, before the consumer calls `configure()`. `serializer` is left\n * out, because `resolveConfig` supplies that default to avoid a circular import.\n * This sits below the constants it reads, since a const can't be read before its own line.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n captureLimits: {\n breadcrumbs: MAX_BREADCRUMBS,\n errorDedupeMs: ERROR_DEDUPE_MS,\n errorsPerWindow: 20,\n consolePerWindow: 20,\n longFramesPerWindow: 20,\n webSocketPerWindow: 20,\n reportsPerWindow: 20,\n resourcesPerWindow: 100,\n lifecyclePerWindow: 20,\n windowMs: ERROR_STORM_WINDOW_MS,\n },\n metadata: { pageUrl: true, userAgent: true, openfin: true, clockOffset: true },\n debugBuffer: { enabled: false, maxRecords: 200, maxAgeMs: 60_000 },\n profiler: {\n enabled: false,\n maxProbes: PROFILER_MAX_PROBES,\n framePhases: false,\n framePacing: false,\n },\n replay: {\n enabled: false,\n mode: \"onError\",\n endpoint: null,\n requireConsent: false,\n bufferMs: 60_000,\n maxBufferBytes: 10_000_000,\n afterErrorMs: 5000,\n uploadsPerWindow: 3,\n uploadWindowMs: ERROR_STORM_WINDOW_MS,\n maxSegmentEvents: 200,\n maxSegmentBytes: 512_000,\n flushIntervalMs: 2000,\n maxQueueBytes: 20_000_000,\n maxAttempts: 3,\n maskText: true,\n maskInputs: true,\n recordCanvas: false,\n maskSelectors: [],\n blockSelectors: [],\n loader: null,\n onSegment: null,\n headers: null,\n plugins: [],\n recordOptions: {},\n },\n storage: { backend: \"auto\", namespace: \"\", requestPersistent: false },\n diagnostics: { throttleMs: 1000, consoleFallback: false, records: false },\n correlation: { sessionIdleMs: SESSION_IDLE_MS, traceMaxAgeMs: TRACE_MAX_AGE_MS },\n metrics: {\n intervalMs: METRIC_INTERVAL_MS,\n maxSeries: METRIC_MAX_SERIES,\n maxInstruments: 1000,\n maxHistogramBoundaries: METRIC_MAX_BOUNDARIES,\n },\n buffering: {\n maxPendingRecords: 10000,\n maxPendingBytes: 16777216,\n maxHeldRecords: BUS_MAX_BOOT_BUFFER_RECORDS,\n overflow: \"drop-oldest\",\n },\n delivery: {\n requestTimeoutMs: REQUEST_TIMEOUT_MS,\n maxConcurrentRequests: MAX_CONCURRENT_REQUESTS,\n retryBaseDelayMs: RETRY_BASE_DELAY_MS,\n retryMaxDelayMs: RETRY_MAX_DELAY_MS,\n priority: \"low\",\n },\n lockConfiguration: false,\n loggerCache: { maxEntries: 256 },\n securityContext: { id: \"\", isolation: true },\n // \"\" means not set, so a configure() without an endpoint reports it. An app can't pass \"\".\n endpoint: \"\",\n metricsEndpoint: null,\n tracesEndpoint: null,\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n payloadMode: \"copy\",\n minLevel: \"INFO\",\n minLevels: {},\n processors: [],\n compression: \"gzip\",\n credentials: \"omit\",\n identity: \"storage\",\n sampling: {\n defaultRate: 1,\n rates: {},\n alwaysSampleTypes: [\"action\"],\n alwaysSampleFrom: \"ERROR\",\n errorCeiling: ERROR_CEILING_MAX_PER_WINDOW,\n errorCeilingWindowMs: ERROR_STORM_WINDOW_MS,\n remote: false,\n remoteMaxRate: 1,\n },\n bus: {\n mode: \"auto\",\n trustedOrigins: [],\n openFinRole: \"auto\",\n sourcePolicy: \"registered\",\n maxMessageBytes: 262144,\n maxRecordsPerMessage: 100,\n maxMessagesPerSecond: 100,\n },\n journey: { scope: \"auto\", maxAgeMs: JOURNEY_MAX_AGE_MS },\n batching: {\n logFlushIntervalMs: LOG_FLUSH_INTERVAL_MS,\n logBatchSize: LOG_BATCH_SIZE,\n metricBatchSize: METRIC_BATCH_SIZE,\n },\n retention: { ...STORAGE_LIMITS },\n limits: { ...RECORD_LIMITS },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n httpMetrics: true,\n interactions: false,\n navigation: false,\n webVitals: false,\n longFrames: false,\n console: false,\n fullUrls: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n webSocket: false,\n uncleanExit: false,\n userTiming: false,\n remoteToggles: [],\n serverTiming: false,\n reports: false,\n resourceTiming: false,\n lifecycle: false,\n plugins: [],\n },\n consoleOutput: { level: null, styles: CONSOLE_DEFAULT_STYLES },\n};\n"],"mappings":"AAcA,IA6BaA,EAAkB,KAgBlBC,GAAqB,WAGrBC,GAA6B,SAG7BC,EAAwB,yBAGxBC,GAAuB,gBAGvBC,GAAoB,aAqDpBC,EAA4C,CACvD,MAAO,EACP,MAAO,EACP,KAAM,EACN,KAAM,GACN,MAAO,GACP,MAAO,EACT,EAMaC,GAAwCD,EAUxCE,GAAgB,WAGhBC,GAAe,UAGfC,GAAqB,gBAGrBC,GAAgB,WAOhBC,GAAgB,WAGhBC,GAAkB,aAGlBC,GAAoB,eAGpBC,EAAyB,oBAGzBC,EAAuB,wBAGvBC,EAAkB,aAGlBC,EAAmB,cAMnBC,EAA0B,2BAM1BC,EAAwB,yBAGxBC,EAAuB,wBAGvBC,EAAoB,qBAMpBC,EAAwB,eAGxBC,EAA2B,kBAG3BC,EAAkC,yBAMlCC,EAA8B,qBAM9BC,EAAiC,wBAMjCC,EAAkC,yBAGlCC,EAAyB,gBAGzBC,EAAsB,aAGtBC,EAAkB,SAGlBC,EAAsB,aAGtBC,EAA8B,qBAG9BC,EAAwB,eAGxBC,EAAwB,eAMxBC,EAAqB,0BAMrBC,EAAA,QAMAC,EAAyB,QAOzBC,EAAuB,OAUvBC,EAAqD,CAAE,KAAM,SAAU,EAGvEC,EAAc,SAGdC,EAAoB,mBAGpBC,EAAsB,uBAGtBC,EAAkB,SAMlBC,EAAgB,QAOhBC,EAAsB,eAGtBC,EAA0B,mBAG1BC,EAAqB,cAMrBC,EAAkB,mBAGlBC,EAAiB,kBAGjBC,EAAkB,mBAGl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ACR,YAAa,EACb,MAAO,CAAC,EACR,kBAAmB,CAAC,QAAQ,EAC5B,iBAAkB,QAClB,aAAA,IACA,qBAAsB1D,EACtB,OAAQ,GACR,cAAe,CACjB,EACA,IAAK,CACH,KAAM,OACN,eAAgB,CAAC,EACjB,YAAa,OACb,aAAc,aACd,gBAAiB,OACjB,qBAAsB,IACtB,qBAAsB,GACxB,EACA,QAAS,CAAE,MAAO,OAAQ,SAAU4D,CAAmB,EACvD,SAAU,CACR,mBAAoBZ,GACpB,aAAA,IACA,gBAAA,GACF,EACA,UAAW,CAAE,GAAGK,EAAe,EAC/B,OAAQ,CAAE,GAAGe,CAAc,EAC3B,QAAS,CACP,OAAQ,GACR,WAAY,GACZ,eAAgB,GAChB,MAAO,GACP,IAAK,GACL,YAAa,GACb,aAAc,GACd,WAAY,GACZ,UAAW,GACX,WAAY,GACZ,QAAS,GACT,SAAU,GACV,WAAY,CAAC,EACb,uBAAwB,CAAC,EACzB,UAAW,GACX,YAAa,GACb,WAAY,GACZ,cAAe,CAAC,EAChB,aAAc,GACd,QAAS,GACT,eAAgB,GAChB,UAAW,GACX,QAAS,CAAC,CACZ,EACA,cAAe,CAAE,MAAO,KAAM,OAAQ9D,CAAuB,CAC/D,E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"identity-DdhKgrpk.js","names":["SESSION_IDLE_MS","TAB_ID_KEY","SESSION_ID_KEY","_defineProperty","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":";;;AAwDA,IAAaI,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAA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,IACrC,KAAK,cAAcJ,IAIrB,KAAK,MAAMI,GAAWJ,CAAG;CAC3B;CAMA,SAA6B;EAC3B,OAAOJ,EAAY,KAAK,QAAQ,KAAK,aAAa,KAAK,IAAI,GAAG,KAAK,MAAM;CAC3E;CAMA,QAAQ,GAAyB;EAC/B,KAAK,MAAMQ,GAAW,KAAK,IAAI,CAAC;CAClC;CAOA,MAAc,GAAmB,GAAmB;EAClD,KAAK,cAAcJ;EACnB,IAAMK,IAAU,KAAK,UAAU;GAAE,IAAID;GAAW,YAAYJ;EAAI,CAAC;EACjE,EAAU,KAAK,QAAQ,SAASzB,GAAgB8B,GAAS,KAAK,WAAW;CAC3E;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./defineProperty-X1c4tIPD.cjs");var n={local:()=>localStorage,session:()=>sessionStorage};function r(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function i(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function a(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return i(16)}function o(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function s(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function c(t,n,r,i){let a=o(t,`local`,e.zn,n);if(a)try{let e=JSON.parse(a);return e.id&&(i===null||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function l(t,r=n,i=e.Rn){let l=a(t),u=Date.now(),d=a(t),f=c(r,t,u,i)??d,p=JSON.stringify({id:f,lastSeenAt:u});s(r,`local`,e.zn,p,t);let m=o(r,`session`,`ui-observability.tab`,t)??``;return m||(m=a(t),s(r,`session`,e.Zn,m,t)),{sessionId:f,tabId:m,contextId:l}}function u(t,n,r){s(r,`session`,e.Zn,t,n)}var d=class{constructor(r,i=n,a=e.Rn){t.t(this,`diagnostics`,void 0),t.t(this,`stores`,void 0),t.t(this,`idleMs`,void 0),t.t(this,`lastTouchAt`,0),this.diagnostics=r,this.stores=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<6e4)return;let n=c(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return c(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});s(this.stores,`local`,e.zn,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
2
- //# sourceMappingURL=identity-DlWRIuwy.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"identity-DlWRIuwy.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","require_constants","require_defineProperty","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. null means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number | null,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === null || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs: number | null = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly idleMs: number | null = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"A,uFAwDA,IAAaK,E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AAA,OAAAG,EACA,KAAA,OAAAK,CAChB,CAMH,MAAM,EAAyB,CAC7B,IAAMC,EAAM,KAAK,IAAI,EAErB,GAAIA,EAAM,KAAK,YAAA,IACb,OAKF,IAAMS,EAASb,EAAY,KAAK,OAAQ,KAAK,YAAaI,EAAK,KAAK,MAAM,EACtES,IAAW,IAAA,IAAaA,IAAWL,EACrC,KAAK,YAAcJ,EAIrB,KAAK,MAAMI,EAAWJ,CAAG,CAC3B,CAMA,QAA6B,CAC3B,OAAOJ,EAAY,KAAK,OAAQ,KAAK,YAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAC3E,CAMA,QAAQ,EAAyB,CAC/B,KAAK,MAAMQ,EAAW,KAAK,IAAI,CAAC,CAClC,CAOA,MAAc,EAAmB,EAAmB,CAClD,KAAK,YAAcJ,EACnB,IAAMK,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYJ,CAAI,CAAC,EACjEL,EAAU,KAAK,OAAQ,QAASvB,EAAAA,GAAgBiC,EAAS,KAAK,WAAW,CAC3E,CACF,E"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./patch-BX8KrPCT.cjs"),n=require("./platform-CfA3-7sJ.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");var i=`a[target="_blank"], a[download]`;function a(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function o(){return history}var s=class{constructor(t){r.t(this,`ctx`,void 0),r.t(this,`name`,`interactions`),r.t(this,`installed`,!1),r.t(this,`restores`,[]),r.t(this,`lastUrl`,``),r.t(this,`burst`,{target:null,times:[],reported:!1}),r.t(this,`stopDeadCheck`,void 0),r.t(this,`onClick`,t=>{if(this.ctx.isActive?.()===!1)return;let n=t.target;if(!(n instanceof Element))return;let r=this.ctx.config.capture.interactions,o=typeof r==`object`?r:{},s=o.ignoreSelector===void 0?e.vt:o.ignoreSelector;if(s&&n.closest(s))return;let c=o.actionAttribute??`data-observability-action`,l=((n.closest(`[${c}]`)?.getAttribute(c)??``)||`unknown-click`).slice(0,this.ctx.config.limits.maxBodyChars),u={};o.selector&&(u.selector=a(n)),o.text&&(u.text=n.textContent.trim().slice(0,o.maxTextChars??50)),this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:l,data:Object.keys(u).length>0?u:void 0}),o.rageClicks&&this.countRage(n,l,o),o.deadClicks&&n.closest(`a, button, summary, input[type="button"], input[type="submit"], input[type="reset"], [role="button"], [role="link"], [role="menuitem"], [role="tab"], [${c}]`)&&!n.closest(i)&&this.watchDead(l,o)}),r.t(this,`onNavigate`,()=>{let e=this.lastUrl,t=location.href;if(e===t||(this.lastUrl=t,this.ctx.isActive?.()===!1))return;let r=this.ctx.config.capture.fullUrls,{urlTransform:i}=this.ctx.config.capture,a=n.i(e,r,i,this.ctx.diagnostics),o=n.i(t,r,i,this.ctx.diagnostics);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${a} -> ${o}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":a})}),this.ctx=t}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){if(this.installed){this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate);for(let e of this.restores.splice(0))e();this.stopDeadCheck?.(),this.burst={target:null,times:[],reported:!1}}}countRage(e,t,n){let r=Date.now(),i=n.rageClickWindowMs??1e3,a=n.rageClickCount??3,o=this.burst.target===e?this.burst.times.filter(e=>r-e<i):[],s=o.length>0&&this.burst.reported;o.push(r);let c=o.length>=a;this.burst={target:e,times:o,reported:s||c},c&&!s&&this.ctx.logger.logEvent(`ui.rage_click`,{"click.action":t,"click.count":a})}watchDead(e,t){if(this.stopDeadCheck||typeof MutationObserver>`u`)return;let n=location.href,r=!1,i=()=>{r=!0},a=new MutationObserver(i);a.observe(document,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),addEventListener(`scroll`,i,{capture:!0,passive:!0});let o=()=>{clearTimeout(s),a.disconnect(),removeEventListener(`scroll`,i,!0),this.stopDeadCheck=void 0},s=setTimeout(()=>{o(),!r&&location.href===n&&this.ctx.isActive?.()!==!1&&this.ctx.logger.logEvent(`ui.dead_click`,{"click.action":e})},t.deadClickMs??1e3);this.stopDeadCheck=o}installHistory(){if(typeof history>`u`)return;let e=o(),n=this.onNavigate,r=!0,i=t.t(e,`pushState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)}),a=t.t(e,`replaceState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)});this.restores.push(()=>{r=!1,i(),a()})}};exports.InteractionCapture=s;
2
- //# sourceMappingURL=interactions-CUkzK8sR.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"interactions-CUkzK8sR.cjs","names":["IGNORE_SELECTOR","recordedUrl","patch","require_constants","require_patch","require_platform","require_defineProperty","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","target","event","settings","options","ignore","attribute","message","data","from","to","full","fromUrl","urlTransform","toUrl","ctx","restore","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. Also detects\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n IGNORE_SELECTOR,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page shows no response, but the click isn't dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Builds a short CSS selector for an element. Prefers the test ID, then the ID, then the\n * aria-label, then the class names.\n * @param element Target DOM element.\n * @returns The selector.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and slicing it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members this module replaces. They are declared as properties, not\n * methods, so the original functions stay unbound. With a bound copy, uninstall would\n * restore a different function from the one it replaced, and every install cycle would\n * stack one more bind on top of the last.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object, typed so that its methods stay unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user clicks and single-page navigations. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions for the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** The URL before the latest navigation. */\n private lastUrl = \"\";\n\n /** The element of the current click burst, and when each of its clicks happened. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that is running now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger, breadcrumbs and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // In the capture phase we see the click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes the interaction listeners and restores every history method that still holds our\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates the trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) {\n return;\n }\n const target = event.target;\n if (!(target instanceof Element)) {\n return;\n }\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore = options.ignoreSelector === undefined ? IGNORE_SELECTOR : options.ignoreSelector;\n if (ignore && target.closest(ignore)) {\n return;\n }\n // A missing or empty attribute gives \"\", and the message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) {\n data.selector = describeElement(target);\n }\n if (options.text) {\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n }\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element and records `ui.rage_click` once per burst.\n * @param target Clicked element.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst only ends once no click is left in the window, so clicks that keep sliding\n // through it don't fire a second event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. If there's no DOM change, navigation or scroll\n * within `deadClickMs`, it records `ui.dead_click`. Only one check runs at a time.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // timer is declared after stop, but stop can only run once that line has executed.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context and records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) {\n return;\n }\n\n // The comparison above uses the full URL, so a query-only change still counts as a\n // navigation. The record doesn't keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL, and the record builder adds the current one as\n // `page.url`. Putting the new URL in `url.full` would make a navigation look like an HTTP\n // request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. Reading from the prototype would skip a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser only updates location.href after the call returns,\n // so a synchronous read would report the previous URL as the new one.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"A,8JAsBA,IAAMO,EAAgB,kCAQtB,SAASC,EAAgB,EAA0B,CACjD,IAAMC,EAAMC,EAAQ,QAAQ,YAAY,EAElCC,EAASD,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIC,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAID,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAME,EAAQF,EAAQ,aAAa,YAAY,EAC/C,GAAIE,IAAU,KACZ,MAAO,GAAGH,EAAI,eAAeG,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBH,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALIG,IAAmB,GACdJ,EAIF,GAAGA,EAAI,GADEI,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CA0BjD,YAAY,EAAsC,CAArBT,EAAA,EAAA,KAAA,MAAA,IAAA,EAAA,EAxB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D,CAAO,CAAC,CAExE,EAAGpB,EAAQ,aAAA,GAA4B,EACvC,KAAK,cAAgByB,CACvB,CAmCA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,IACrB,OAKF,IAAM5B,EAASF,EAAe,EACxBgC,EAAa,KAAK,WAEpBC,EAAS,GAEPC,EAAmB9C,EAAAA,EACvBc,EACA,YACC,GACC,SAAyB,GAAGiC,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EAGrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEMK,EAAsBjD,EAAAA,EAC1Bc,EACA,eACC,GACC,SAAyB,GAAGiC,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EACrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEA,KAAK,SAAS,SAAW,CACvB,EAAS,GACTE,EAAiB,EACjBG,EAAoB,CACtB,CAAC,CACH,CACF,E"}
@@ -1,111 +0,0 @@
1
- import { vt as e } from "./constants-CUyd9cTZ.js";
2
- import { t } from "./patch-UdPz1ea8.js";
3
- import { i as n } from "./platform-BaaFIPCU.js";
4
- import { t as r } from "./defineProperty-s2S8BXUc.js";
5
- // src/capture/interactions.ts
6
- var i = "a[target=\"_blank\"], a[download]";
7
- function a(e) {
8
- let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
9
- if (n !== null) return `[data-testid="${n}"]`;
10
- if (e.id !== "") return `#${e.id}`;
11
- let r = e.getAttribute("aria-label");
12
- if (r !== null) return `${t}[aria-label="${r.slice(0, 40)}"]`;
13
- let i = e.getAttribute("class")?.trim() ?? "";
14
- return i === "" ? t : `${t}.${i.split(/\s+/).slice(0, 2).join(".")}`;
15
- }
16
- function o() {
17
- return history;
18
- }
19
- var s = class {
20
- constructor(t) {
21
- r(this, "ctx", void 0), r(this, "name", "interactions"), r(this, "installed", !1), r(this, "restores", []), r(this, "lastUrl", ""), r(this, "burst", {
22
- target: null,
23
- times: [],
24
- reported: !1
25
- }), r(this, "stopDeadCheck", void 0), r(this, "onClick", (t) => {
26
- if (this.ctx.isActive?.() === !1) return;
27
- let n = t.target;
28
- if (!(n instanceof Element)) return;
29
- let r = this.ctx.config.capture.interactions, o = typeof r == "object" ? r : {}, s = o.ignoreSelector === void 0 ? e : o.ignoreSelector;
30
- if (s && n.closest(s)) return;
31
- let c = o.actionAttribute ?? "data-observability-action", l = ((n.closest(`[${c}]`)?.getAttribute(c) ?? "") || "unknown-click").slice(0, this.ctx.config.limits.maxBodyChars), u = {};
32
- o.selector && (u.selector = a(n)), o.text && (u.text = n.textContent.trim().slice(0, o.maxTextChars ?? 50)), this.ctx.tracing.rotate("interaction"), this.ctx.breadcrumbs.push({
33
- t: Date.now(),
34
- category: "click",
35
- message: l,
36
- data: Object.keys(u).length > 0 ? u : void 0
37
- }), o.rageClicks && this.countRage(n, l, o), o.deadClicks && n.closest(`a, button, summary, input[type="button"], input[type="submit"], input[type="reset"], [role="button"], [role="link"], [role="menuitem"], [role="tab"], [${c}]`) && !n.closest(i) && this.watchDead(l, o);
38
- }), r(this, "onNavigate", () => {
39
- let e = this.lastUrl, t = location.href;
40
- if (e === t || (this.lastUrl = t, this.ctx.isActive?.() === !1)) return;
41
- let r = this.ctx.config.capture.fullUrls, { urlTransform: i } = this.ctx.config.capture, a = n(e, r, i, this.ctx.diagnostics), o = n(t, r, i, this.ctx.diagnostics);
42
- this.ctx.tracing.rotate("navigation"), this.ctx.breadcrumbs.push({
43
- t: Date.now(),
44
- category: "navigation",
45
- message: `${a} -> ${o}`
46
- }), this.ctx.logger.logEvent("NAVIGATION", { "page.url.previous": a });
47
- }), this.ctx = t;
48
- }
49
- install() {
50
- this.installed || typeof document > "u" || (this.installed = !0, this.lastUrl = location.href, this.ctx.config.capture.interactions && addEventListener("click", this.onClick, !0), this.ctx.config.capture.navigation && (this.installHistory(), addEventListener("popstate", this.onNavigate), addEventListener("hashchange", this.onNavigate)));
51
- }
52
- uninstall() {
53
- if (this.installed) {
54
- this.installed = !1, removeEventListener("click", this.onClick, !0), removeEventListener("popstate", this.onNavigate), removeEventListener("hashchange", this.onNavigate);
55
- for (let e of this.restores.splice(0)) e();
56
- this.stopDeadCheck?.(), this.burst = {
57
- target: null,
58
- times: [],
59
- reported: !1
60
- };
61
- }
62
- }
63
- countRage(e, t, n) {
64
- let r = Date.now(), i = n.rageClickWindowMs ?? 1e3, a = n.rageClickCount ?? 3, o = this.burst.target === e ? this.burst.times.filter((e) => r - e < i) : [], s = o.length > 0 && this.burst.reported;
65
- o.push(r);
66
- let c = o.length >= a;
67
- this.burst = {
68
- target: e,
69
- times: o,
70
- reported: s || c
71
- }, c && !s && this.ctx.logger.logEvent("ui.rage_click", {
72
- "click.action": t,
73
- "click.count": a
74
- });
75
- }
76
- watchDead(e, t) {
77
- if (this.stopDeadCheck || typeof MutationObserver > "u") return;
78
- let n = location.href, r = !1, i = () => {
79
- r = !0;
80
- }, a = new MutationObserver(i);
81
- a.observe(document, {
82
- subtree: !0,
83
- childList: !0,
84
- attributes: !0,
85
- characterData: !0
86
- }), addEventListener("scroll", i, {
87
- capture: !0,
88
- passive: !0
89
- });
90
- let o = () => {
91
- clearTimeout(s), a.disconnect(), removeEventListener("scroll", i, !0), this.stopDeadCheck = void 0;
92
- }, s = setTimeout(() => {
93
- o(), !r && location.href === n && this.ctx.isActive?.() !== !1 && this.ctx.logger.logEvent("ui.dead_click", { "click.action": e });
94
- }, t.deadClickMs ?? 1e3);
95
- this.stopDeadCheck = o;
96
- }
97
- installHistory() {
98
- if (typeof history > "u") return;
99
- let e = o(), n = this.onNavigate, r = !0, i = t(e, "pushState", (e) => function(...t) {
100
- e.apply(this, t), r && queueMicrotask(n);
101
- }), a = t(e, "replaceState", (e) => function(...t) {
102
- e.apply(this, t), r && queueMicrotask(n);
103
- });
104
- this.restores.push(() => {
105
- r = !1, i(), a();
106
- });
107
- }
108
- };
109
- export { s as InteractionCapture };
110
-
111
- //# sourceMappingURL=interactions-DiFvCosX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"interactions-DiFvCosX.js","names":["IGNORE_SELECTOR","recordedUrl","_defineProperty","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","target","event","settings","options","ignore","attribute","message","data","from","to","full","fromUrl","urlTransform","toUrl","ctx","restore","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","onNavigate","active","restorePushState","patch","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. Also detects\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n IGNORE_SELECTOR,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page shows no response, but the click isn't dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Builds a short CSS selector for an element. Prefers the test ID, then the ID, then the\n * aria-label, then the class names.\n * @param element Target DOM element.\n * @returns The selector.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and slicing it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members this module replaces. They are declared as properties, not\n * methods, so the original functions stay unbound. With a bound copy, uninstall would\n * restore a different function from the one it replaced, and every install cycle would\n * stack one more bind on top of the last.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object, typed so that its methods stay unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user clicks and single-page navigations. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions for the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** The URL before the latest navigation. */\n private lastUrl = \"\";\n\n /** The element of the current click burst, and when each of its clicks happened. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that is running now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger, breadcrumbs and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // In the capture phase we see the click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes the interaction listeners and restores every history method that still holds our\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates the trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) {\n return;\n }\n const target = event.target;\n if (!(target instanceof Element)) {\n return;\n }\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore = options.ignoreSelector === undefined ? IGNORE_SELECTOR : options.ignoreSelector;\n if (ignore && target.closest(ignore)) {\n return;\n }\n // A missing or empty attribute gives \"\", and the message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) {\n data.selector = describeElement(target);\n }\n if (options.text) {\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n }\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element and records `ui.rage_click` once per burst.\n * @param target Clicked element.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst only ends once no click is left in the window, so clicks that keep sliding\n // through it don't fire a second event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. If there's no DOM change, navigation or scroll\n * within `deadClickMs`, it records `ui.dead_click`. Only one check runs at a time.\n * @param action The click's action name.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // timer is declared after stop, but stop can only run once that line has executed.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context and records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) {\n return;\n }\n\n // The comparison above uses the full URL, so a query-only change still counts as a\n // navigation. The record doesn't keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL, and the record builder adds the current one as\n // `page.url`. Putting the new URL in `url.full` would make a navigation look like an HTTP\n // request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. Reading from the prototype would skip a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser only updates location.href after the call returns,\n // so a synchronous read would report the previous URL as the new one.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":";;;;;AAsBA,IAAMG,IAAgB;AAQtB,SAASC,EAAgB,GAA0B;CACjD,IAAMC,IAAMC,EAAQ,QAAQ,YAAY,GAElCC,IAASD,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIC,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAID,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAME,IAAQF,EAAQ,aAAa,YAAY;CAC/C,IAAIE,MAAU,MACZ,OAAO,GAAGH,EAAI,e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Ae;EACjB,CAAC,GACD,iBAAiB,UAAUD,GAAS;GAAE,SAAS;GAAM,SAAS;EAAK,CAAC;EAEpE,IAAME,UAAmB;GAKvB,AAHA,aAAaC,CAAK,GAClBF,EAAS,WAAW,GACpB,oBAAoB,UAAUD,GAAS,EAAI,GAC3C,KAAK,gBAAgB,KAAA;EACvB,GACMG,IAAQ,iBAAiB;GAE7B,AADAD,EAAK,GACD,CAACH,KAAa,SAAS,SAASD,KAAQ,KAAK,IAAI,WAAW,MAAM,MACpE,KAAK,IAAI,OAAO,SAAS,iBAAiB,EAAE,gBAAgBD,EAAO,CAAC;EAExE,GAAGpB,EAAQ,eAAA,GAA4B;EACvC,KAAK,gBAAgByB;CACvB;CAmCA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,KACrB;EAKF,IAAM5B,IAASF,EAAe,GACxBgC,IAAa,KAAK,YAEpBC,IAAS,IAEPC,IAAmBC,EACvBjC,GACA,cACC,MACC,SAAyB,GAAGkC,GAAqB;GAI/C,AAHAC,EAAS,MAAM,MAAMD,CAAI,GAGrBH,KACF,eAAeD,CAAU;EAE7B,CACJ,GAEMM,IAAsBH,EAC1BjC,GACA,iBACC,MACC,SAAyB,GAAGkC,GAAqB;GAE/C,AADAC,EAAS,MAAM,MAAMD,CAAI,GACrBH,KACF,eAAeD,CAAU;EAE7B,CACJ;EAEA,KAAK,SAAS,WAAW;GAGvB,AAFA,IAAS,IACTE,EAAiB,GACjBI,EAAoB;EACtB,CAAC;CACH;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rotation-Cwct4ckk.js","names":["ROUTING_KEYS","ROUTING_RESET","newId","resolveEndpoint","resolveDestination","applyResolvedConfig","resolveConfig","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","validOptions","isObject","update","pending","timeoutMs","planRotation","host","options","previous","runtime","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","clearStored","keepStored","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again, unless a later rotation waits.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form. The serializer\n // check can still turn an accepted signal endpoint off, and that doesn't match either.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It rejects for a setting it can't apply.\n */\nasync function planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): Promise<RotationPlan> {\n const { runtime } = host;\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n plan = await planRotation(host, update, options);\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":";;;;;;AA2BA,IAAMO,IAAmC;CAAC;CAAW;CAAS;CAAU;AAAO,GAGzEC,IAAU,OAAO,SAAS;AAoFhC,SAASC,EACP,GACA,GACA,GACU;CACV,OAAOT,EAAa,QAAQ,MAAQ;EAClC,IA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M,GAC1BA,EAAQ,WAAW,GACnBA,EAAQ,QAAQ,mBAAmB,GACnC,MAAMH,EAAK,aAAa,GAGxBA,EAAK,YAAY2B,CAAG,GAEhB9B,MAAY,SAAS;EACvB,KAAK,IAAM+B,KAAUpB,GACnB,EAAK,MAAMoB,CAAM;EAInB,MAAM5B,EAAK,MAAMS,CAAM;CACzB;CAEA,EAAQ,YAAY,OAAO,oBAAoB,6CAA6C,EAC1F,WACF,CAAC;AACH"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./identity-DlWRIuwy.cjs"),r=require("./config-DUs7uHHt.cjs"),i=require("./stored-context-CXt7eHZL.cjs");var a=[`discard`,`flush`,`retain`,`carry`],o=Symbol(`refused`);function s(t,n,i){return e.An.filter(e=>{let a=t[e],s=n[e];return a===void 0?!1:e===`endpoint`?r.a(a,o,i)!==s:e===`metricsEndpoint`||e===`tracesEndpoint`?r.i(e,a,o,i)!==s:a===null?s!==void 0:s!==a})}function c(t,n){let r={...e.jn};for(let i of Object.keys(t))if(e.An.includes(i)){let e=Reflect.get(t,i);Object.assign(r,{[i]:e})}else n.diagnostics.report(`config.invalid`,`rotateSecurityContext() ignores routing.${i}. A rotation changes only the routing settings.`);return r}function l(e,n,r){return t.n(e)&&t.n(e.routing)&&t.n(e.context??{})&&a.includes(n)&&Number.isFinite(r)&&r>=0&&r<=6e5&&(e.id===void 0||typeof e.id==`string`&&e.id.length>0)}async function u(t,i,a){let{runtime:o}=t;await t.senderLoaded();let u=a.pending??`discard`,d=a.timeoutMs??5e3;if(!l(i,u,d))throw Error(`Invalid security-context rotation options.`);let f=o.config.securityContext.id,p=i.id??n.i(o.diagnostics);if(p===f)throw Error(`A rotation requires a different security-context id.`);let m=t.allowed({...c(i.routing,o),securityContext:{id:p}}),h=r.r(m,o.diagnostics,{...o.config,...e.jn});if(s(m,h,t.quiet).length>0)throw Error(`Invalid routing settings for the next security context.`);return{next:h,context:i.context?Object.fromEntries(Object.entries(i.context)):void 0,pending:u,timeoutMs:d,previous:f}}function d(e,t,n,r){return e===`retain`?t:e===`carry`?n:[...n,...r.flatMap(e=>e.records)]}async function f(e,t,n,a){let{runtime:o}=e,{config:s}=o,c;try{c=await u(e,t,n)}catch(t){throw await e.closeDelivery(),t}if(o.isDestroyed())throw Error(`The runtime has stopped.`);let{next:l,context:f,pending:p,timeoutMs:m,previous:h}=c,g=new Set([s.endpoint,s.metricsEndpoint,s.tracesEndpoint]),_=new Set([l.endpoint,l.metricsEndpoint,l.tracesEndpoint]);l.capture.ignoreUrls=l.capture.ignoreUrls.filter(e=>!g.has(e)||_.has(e)),e.closeContext();let{held:v,sender:y,closed:b,carried:x}=e.takeOld(),S=b&&p===`flush`?`discard`:p,C=await y?.retire(S,m,h)??{buffered:[],stored:[]},w=[...v,...C.buffered],T=[...x,...C.stored];if(o.isDestroyed())throw e.drop(d(S,v,w,C.stored)),await e.adopt(x),Error(`The runtime has stopped.`);S!==`retain`&&S!==`carry`&&e.drop([...w,...T.flatMap(e=>e.records)]);let{diagnostics:E}=o;if(!y&&(S===`discard`||S===`flush`)){let t=x.map(e=>e.id);await E.guardAsync(`storage.degraded`,`The library could not remove the stored batches of the old context.`,()=>i.clearStored(e.storeAccess(),`context`,t))}if(S===`retain`&&(v.length>0||x.length>0)&&await E.guardAsync(`storage.degraded`,`The library could not store the records of the old context.`,()=>i.keepStored(e.storeAccess(),v,x)),o.isDestroyed())throw Error(`The runtime has stopped.`);if(l.lockConfiguration=s.lockConfiguration,r.n(s,l),e.advanceIdentity(),o.context.clear(),f&&o.context.merge(f),o.breadcrumbs.clear(),o.newSession(),o.builder.invalidateResource(),await e.openDelivery(),e.endRotation(a),p===`carry`){for(let t of w)e.route(t);await e.adopt(T)}o.diagnostics.report(`security.rotated`,`The runtime rotated its security context.`,{pending:p})}exports.rotateContext=f;
2
- //# sourceMappingURL=rotation-D4qUAHAu.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rotation-D4qUAHAu.cjs","names":["ROUTING_KEYS","resolveEndpoint","resolveDestination","ROUTING_RESET","isObject","newId","resolveConfig","clearStored","keepStored","require_constants","require_guards","require_identity","require_config","require_stored_context","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","runtime","validOptions","update","pending","timeoutMs","planRotation","host","options","previous","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again, unless a later rotation waits.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form. The serializer\n // check can still turn an accepted signal endpoint off, and that doesn't match either.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It rejects for a setting it can't apply.\n */\nasync function planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): Promise<RotationPlan> {\n const { runtime } = host;\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n plan = await planRotation(host, update, options);\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":"A,kMA2BA,IAAMc,EAAmC,CAAC,UAAW,QAAS,SAAU,OAAO,EAGzEC,EAAU,OAAO,SAAS,EAoFhC,SAASC,EACP,EACA,EACA,EACU,CACV,OAAOhB,EAAAA,GAAa,OAAQ,GAAQ,CAClC,IAAMiB,EAAiBC,EAAMC,GACvBC,EAAmBC,EAAKF,GAkB9B,OAfIF,IAAU,IAAA,GACL,GAKLE,IAAQ,WACHlB,EAAAA,EAAgBgB,EAAOF,EAASO,CAAK,IAAMF,EAGhDD,IAAQ,mBAAqBA,IAAQ,iBAChCjB,EAAAA,EAAmBiB,EAAKF,EAAOF,EAASO,CAAK,IAAMF,EAIrDH,IAAU,KAAOG,IAAY,IAAA,GAAYA,IAAYH,CAC9D,CAAC,CACH,CASA,SAASM,EACP,EACA,EAC8B,CAC9B,IAAMC,EAAqC,CAAE,GAAGrB,EAAAA,EAAc,EAE9D,IAAK,IAAMgB,KAAO,OAAO,KAAKM,CAAO,EACnC,GAAKzB,EAAAA,GAAmC,SAASmB,CAAG,EAAG,CACrD,IAAMO,EAAiB,QAAQ,IAAID,EAASN,CAAG,EAC/C,OAAO,OAAOK,EAAM,EAAGL,GAAMO,CAAM,CAAC,CACtC,MACEC,EAAQ,YAAY,OAClB,iBACA,2CAA2CR,EAAI,gDACjD,EAIJ,OAAOK,CACT,CASA,SAASI,EAAa,EAA+B,EAAiB,EAA4B,CAChG,OACExB,EAAAA,EAASyB,CAAM,GACfzB,EAAAA,EAASyB,EAAO,OAAO,GAEvBzB,EAAAA,EAASyB,EAAO,SAAW,CAAC,CAAC,GAC7Bf,EAAc,SAASgB,CAAO,GAC9B,OAAO,SAASC,CAAS,GACzBA,GAAa,GACbA,GAAA,MACCF,EAAO,KAAO,IAAA,IAAc,OAAOA,EA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D,CACF,CAcA,GAXIhB,IAAS,WAAaC,EAAK,OAAS,GAAKc,EAAQ,OAAS,IAC5D,MAAME,EAAY,WAChB,mBACA,kEACM/C,EAAAA,WAAWyB,EAAK,YAAY,EAAGM,EAAMc,CAAO,CACpD,EAME1B,EAAQ,YAAY,EACtB,MAAU,MAAM,0BAA0B,EAsB5C,GAlBA,EAAK,kBAAoBoB,EAAO,kBAEhCnC,EAAA,EAAoBmC,EAAQ1B,CAAI,EAChCY,EAAK,gBAAgB,EACrBN,EAAQ,QAAQ,MAAM,EAElB6B,GACF7B,EAAQ,QAAQ,MAAM6B,CAAO,EAG/B7B,EAAQ,YAAY,MAAM,EAC1BA,EAAQ,WAAW,EACnBA,EAAQ,QAAQ,mBAAmB,EACnC,MAAMM,EAAK,aAAa,EAGxBA,EAAK,YAAYwB,CAAG,EAEhB3B,IAAY,QAAS,CACvB,IAAK,IAAM4B,KAAUlB,EACnBP,EAAK,MAAMyB,CAAM,EAInB,MAAMzB,EAAK,MAAMQ,CAAM,CACzB,CAEAd,EAAQ,YAAY,OAAO,mBAAoB,4CAA6C,CAC1F,SACF,CAAC,CACH,C"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./deadline-CUGbto-y.cjs"),n=require("./platform-CfA3-7sJ.cjs"),r=require("./response-body-YdNl-HkR.cjs"),i=require("./sender-BdRuNVhF.cjs"),a=require("./unref-CU9Nyz_9.cjs"),o=require("./worker-protocol-QbvqNazn.cjs"),s=require("./defineProperty-X1c4tIPD.cjs");var c=class extends Error{constructor(e){super(`The transport worker did not complete the request.`),s.t(this,`kind`,void 0),this.kind=e}};function l(t,n){let r,i=!1,s=0,l=e=>i||e.aborted,u=()=>{let e=r;if(r=void 0,e){n.guard(`transport.http_error`,`The transport worker could not be closed.`,()=>{e.detach()}),n.guard(`transport.http_error`,`The transport port could not be closed.`,()=>{e.port.close()}),n.guard(`transport.http_error`,`The transport worker could not be terminated.`,()=>{e.worker.terminate()});for(let t of e.pending.values())t.reject(new c(`channel`));e.pending.clear()}},d=(t,r,i)=>{try{t.port.postMessage(o.i(e.sr.send,{id:r,job:i}))}catch(e){n.report(`transport.http_error`,`The transport worker could not clone its batch.`,void 0,e),u()}},f=()=>{if(r)return r;let i;try{i=t();let n=new MessageChannel,a={worker:i,port:n.port1,ready:!1,pending:new Map,detach:()=>void 0};r=a;let s=t=>{let n=t.data;if(!o.n(n))u();else if(n.t===e.sr.ready){if(n.ok!==!0){u();return}if(!a.ready){a.ready=!0;for(let[e,t]of a.pending)d(a,e,t.job)}}else n.t!==e.sr.result||typeof n.id!=`number`||!o.r(n.result)?u():a.pending.get(n.id)?.resolve(n.result)},c=()=>{u()};return a.port.addEventListener(`message`,s),a.port.addEventListener(`messageerror`,c),i.addEventListener(`error`,c),i.addEventListener(`messageerror`,c),a.detach=()=>{a.port.removeEventListener(`message`,s),a.port.removeEventListener(`messageerror`,c),a.worker.removeEventListener(`error`,c),a.worker.removeEventListener(`messageerror`,c)},a.port.start(),i.postMessage(o.i(e.sr.connect),[n.port2]),a}catch(e){throw n.report(`transport.http_error`,`The transport worker could not start.`,void 0,e),u(),n.guard(`transport.http_error`,`The transport worker could not stop.`,()=>i?.terminate()),new c(`channel`)}};return{send:async(t,r,i,p)=>{if(l(r))throw new c(`cancelled`);let m=f();if(l(r))throw u(),new c(`cancelled`);let h=++s,g;try{return await new Promise((s,l)=>{let f=t=>{m.pending.delete(h),n.guard(`transport.http_error`,`The transport worker request could not be cancelled.`,()=>{m.port.postMessage(o.i(e.sr.cancel,{id:h}))}),l(new c(t))},_=()=>{f(`cancelled`)},v=setTimeout(()=>{m.ready?(v=setTimeout(()=>{f(`timeout`)},p),a.t(v)):u()},i);a.t(v),g=()=>{clearTimeout(v),r.removeEventListener(`abort`,_),m.pending.delete(h)},m.pending.set(h,{job:t,resolve:s,reject:l}),r.addEventListener(`abort`,_,{once:!0}),m.ready&&d(m,h,t)})}finally{g()}},close:()=>{i=!0,u()}}}var u=class extends i.a{constructor(e,t,n,r,i,a){super(e,t,r,i,a),s.t(this,`http`,void 0),s.t(this,`loss`,void 0),s.t(this,`client`,void 0),s.t(this,`source`,void 0),s.t(this,`disabled`,!1),this.http=n,this.loss=i}async send(e,a){this.assertContext(e);let o=r.o(e,this.config),s=r.s(o,this.config);if(!s)return this.diagnostics.count(`record.dropped_no_destination`),e.records.length;if(e.records.length===0)return 0;let l=this.workerClient(),u=typeof document<`u`&&document.visibilityState===`hidden`;if(!l||typeof this.config.serializer!=`string`||u)return this.http.send(e,a);let d;try{if(d=await this.attempt(l,e,o,s,this.config.serializer),this.assertContext(e),`status`in d&&(d.status===401||d.status===403)&&typeof this.config.headers==`function`&&(i.r(this.http),d=await this.attempt(l,e,o,s,this.config.serializer),this.assertContext(e)),`failure`in d&&d.failure===`protocol`)throw new c(`channel`)}catch(n){if(this.diagnostics.report(`transport.http_error`,`The transport worker request failed.`,void 0,n),this.assertContext(e),n instanceof t.t||n instanceof c&&n.kind===`timeout`)throw this.diagnostics.report(`transport.timeout`,`The transport worker request exceeded its time limit.`),new r.f(`timeout`,`The transport worker request exceeded its time limit.`);if(n instanceof c&&n.kind===`channel`)return this.client===l&&(this.disabled=!0,l.close()),this.http.send(e,a);throw new r.f(`transient`,`The transport worker request failed.`)}if(`failure`in d){if(d.failure===`serialize`)return this.diagnostics.report(`transport.serialize_failed`,`The transport worker could not serialize its batch.`,{batchId:e.id}),this.loss(`unserializable`,e.records,[e.id]),e.records.length;let t=d.failure===`timeout`;throw this.diagnostics.report(t?`transport.timeout`:`transport.http_error`,`The transport worker did not send its batch.`),new r.f(t?`timeout`:n.r()?`transient`:`offline`,`The transport worker did not send its batch.`)}if(d.compressionFailed&&this.diagnostics.report(`transport.http_error`,`The transport worker sent its batch without gzip after a compression failure.`),d.status>=200&&d.status<300)return this.accept(o,d.sampling,d.date),d.body===void 0?0:this.reportPartial(e,o,d.body);throw this.reject(d.status,e.id,o,{retryAfterMs:d.retryAfterMs,maxBytes:d.maxBytes,advice:i.t})}throttledForMs(e){return Math.max(super.throttledForMs(e),this.http.throttledForMs(e))}throttleEnd(){let e=Math.max(super.throttleEnd()??-1/0,this.http.throttleEnd()??-1/0);return Number.isFinite(e)?e:null}lastSendAt(){let e=Math.max(super.lastSendAt()??-1/0,this.http.lastSendAt()??-1/0);return Number.isFinite(e)?e:null}stop(){super.stop(),this.client?.close(),this.http.stop()}workerClient(){let e=this.config.transportWorker;if(e!==this.source&&(this.client?.close(),this.client=void 0,this.source=e,this.disabled=!1),e&&!this.disabled)return this.client??=l(e,this.diagnostics),this.client}async attempt(n,r,a,o,s){let c=this.config.delivery.requestTimeoutMs,l=Date.now()+c,u=await t.n(this.untilCancelled(i.i(this.http,this.config,this.diagnostics)),c);this.assertContext(r);let d=l-Date.now();if(d<=0)throw new t.t(c);let f=new Headers(u);return f.set(e.ut,r.id),f.set(e.lt,String(r.attempts)),n.send({batch:r,kind:a,endpoint:o,serializer:s,headers:Object.fromEntries(f),compression:this.config.compression,credentials:this.config.credentials,priority:this.config.delivery.priority,timeoutMs:d,deadlineMs:l},this.cancellation.signal,d,e.mr)}};function d(e,t,n,r,a){let o=new i.n(e,t,n,r,a);return{transport:new u(e,t,o,n,r,a),exitHeaders:()=>o.lastHeaders(),keepaliveInFlight:()=>o.keepaliveInFlight()}}exports.createWorkerTransport=d;
2
- //# sourceMappingURL=worker-transport-CRAX-09c.cjs.map