@utk09/ui-observability 0.12.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (515) hide show
  1. package/CHANGELOG.md +420 -0
  2. package/README.md +72 -839
  3. package/dist/{batch-BjQUwjA6.js → batch-CXmPmTse.js} +4 -4
  4. package/dist/{batch-BjQUwjA6.js.map → batch-CXmPmTse.js.map} +1 -1
  5. package/dist/{batch-D5LlU4Q9.cjs → batch-mmPigCpi.cjs} +2 -2
  6. package/dist/{batch-D5LlU4Q9.cjs.map → batch-mmPigCpi.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +331 -0
  8. package/dist/bus/bus.d.ts +60 -10
  9. package/dist/bus/links.d.cts +132 -0
  10. package/dist/bus/links.d.ts +18 -3
  11. package/dist/bus/validation.d.cts +16 -0
  12. package/dist/bus/validation.d.ts +10 -1
  13. package/dist/{bus-ecxUNTja.js → bus-C39wspFV.js} +308 -193
  14. package/dist/bus-C39wspFV.js.map +1 -0
  15. package/dist/bus-_EaOVPGq.cjs +2 -0
  16. package/dist/bus-_EaOVPGq.cjs.map +1 -0
  17. package/dist/capture/console.d.cts +37 -0
  18. package/dist/capture/console.d.ts +1 -1
  19. package/dist/capture/errors.d.cts +32 -0
  20. package/dist/capture/errors.d.ts +1 -1
  21. package/dist/capture/interactions.d.cts +48 -0
  22. package/dist/capture/interactions.d.ts +1 -1
  23. package/dist/capture/lifecycle.d.cts +20 -0
  24. package/dist/capture/lifecycle.d.ts +1 -1
  25. package/dist/capture/long-frames.d.cts +31 -0
  26. package/dist/capture/long-frames.d.ts +1 -1
  27. package/dist/capture/network.d.cts +57 -0
  28. package/dist/capture/network.d.ts +1 -1
  29. package/dist/capture/profiler-frames.d.cts +44 -0
  30. package/dist/capture/profiler-frames.d.ts +1 -1
  31. package/dist/capture/replay-buffer.d.cts +45 -0
  32. package/dist/capture/replay-buffer.d.ts +9 -10
  33. package/dist/capture/replay-upload.d.cts +79 -0
  34. package/dist/capture/replay-upload.d.ts +7 -2
  35. package/dist/capture/replay.d.cts +114 -0
  36. package/dist/capture/replay.d.ts +1 -1
  37. package/dist/capture/reports.d.cts +17 -0
  38. package/dist/capture/reports.d.ts +1 -1
  39. package/dist/capture/resource-timing.d.cts +14 -0
  40. package/dist/capture/resource-timing.d.ts +1 -1
  41. package/dist/capture/server-timing.d.cts +19 -0
  42. package/dist/capture/storm.d.cts +13 -0
  43. package/dist/capture/storm.d.ts +5 -5
  44. package/dist/capture/types.d.cts +128 -0
  45. package/dist/capture/types.d.ts +10 -9
  46. package/dist/capture/unclean-exit.d.cts +31 -0
  47. package/dist/capture/unclean-exit.d.ts +1 -1
  48. package/dist/capture/user-timing.d.cts +22 -0
  49. package/dist/capture/user-timing.d.ts +2 -2
  50. package/dist/capture/web-socket.d.cts +40 -0
  51. package/dist/capture/web-socket.d.ts +3 -3
  52. package/dist/capture/web-vitals.d.cts +40 -0
  53. package/dist/capture/web-vitals.d.ts +1 -1
  54. package/dist/{compression-lD9abCcO.cjs → compression-CvED_Jel.cjs} +2 -2
  55. package/dist/{compression-lD9abCcO.cjs.map → compression-CvED_Jel.cjs.map} +1 -1
  56. package/dist/{compression-AJJCMBOa.js → compression-tVtXwVjX.js} +2 -2
  57. package/dist/{compression-AJJCMBOa.js.map → compression-tVtXwVjX.js.map} +1 -1
  58. package/dist/config-DUs7uHHt.cjs +2 -0
  59. package/dist/config-DUs7uHHt.cjs.map +1 -0
  60. package/dist/config-SgQcCP1_.js +560 -0
  61. package/dist/config-SgQcCP1_.js.map +1 -0
  62. package/dist/console-BGgGnjSi.js +81 -0
  63. package/dist/console-BGgGnjSi.js.map +1 -0
  64. package/dist/console-CSZ5_Vx5.cjs +2 -0
  65. package/dist/console-CSZ5_Vx5.cjs.map +1 -0
  66. package/dist/constants-CUyd9cTZ.js +357 -0
  67. package/dist/constants-CUyd9cTZ.js.map +1 -0
  68. package/dist/constants-CqdJhTxH.cjs +2 -0
  69. package/dist/constants-CqdJhTxH.cjs.map +1 -0
  70. package/dist/constants.d.cts +751 -0
  71. package/dist/constants.d.ts +88 -20
  72. package/dist/core/breadcrumbs.d.cts +54 -0
  73. package/dist/core/breadcrumbs.d.ts +5 -0
  74. package/dist/core/config.d.cts +45 -0
  75. package/dist/core/config.d.ts +30 -2
  76. package/dist/core/context.d.cts +24 -0
  77. package/dist/core/context.d.ts +3 -8
  78. package/dist/core/debug-buffer.d.cts +34 -0
  79. package/dist/core/debug-buffer.d.ts +3 -3
  80. package/dist/core/debug-bundle.d.cts +12 -0
  81. package/dist/core/debug-bundle.d.ts +3 -3
  82. package/dist/core/deferred.d.cts +7 -0
  83. package/dist/core/deferred.d.ts +2 -2
  84. package/dist/core/diagnostics.d.cts +86 -0
  85. package/dist/core/diagnostics.d.ts +1 -1
  86. package/dist/core/drops.d.cts +39 -0
  87. package/dist/core/drops.d.ts +16 -6
  88. package/dist/core/hold-buffer.d.cts +36 -0
  89. package/dist/core/hold-buffer.d.ts +16 -7
  90. package/dist/core/journey.d.cts +148 -0
  91. package/dist/core/journey.d.ts +7 -7
  92. package/dist/core/logger.d.cts +141 -0
  93. package/dist/core/logger.d.ts +23 -30
  94. package/dist/core/measure.d.cts +30 -0
  95. package/dist/core/measure.d.ts +14 -3
  96. package/dist/core/meter.d.cts +78 -0
  97. package/dist/core/meter.d.ts +14 -8
  98. package/dist/core/pipeline.d.cts +227 -0
  99. package/dist/core/pipeline.d.ts +73 -10
  100. package/dist/core/profile-buckets.d.cts +31 -0
  101. package/dist/core/profiler.d.cts +218 -0
  102. package/dist/core/profiler.d.ts +2 -2
  103. package/dist/core/record.d.cts +190 -0
  104. package/dist/core/record.d.ts +44 -12
  105. package/dist/core/remote-rules.d.cts +17 -0
  106. package/dist/core/remote-rules.d.ts +3 -3
  107. package/dist/core/remote-sampling.d.cts +74 -0
  108. package/dist/core/remote-sampling.d.ts +3 -3
  109. package/dist/core/rotation.d.cts +75 -0
  110. package/dist/core/rotation.d.ts +75 -0
  111. package/dist/core/runtime.d.cts +765 -0
  112. package/dist/core/runtime.d.ts +245 -70
  113. package/dist/core/sampling.d.cts +86 -0
  114. package/dist/core/sampling.d.ts +5 -5
  115. package/dist/core/sender.d.cts +161 -0
  116. package/dist/core/sender.d.ts +59 -15
  117. package/dist/core/spans.d.cts +39 -0
  118. package/dist/core/spans.d.ts +1 -1
  119. package/dist/debug-bundle-BXIlwDKM.cjs +2 -0
  120. package/dist/debug-bundle-BXIlwDKM.cjs.map +1 -0
  121. package/dist/debug-bundle-CRpYV_ui.js +35 -0
  122. package/dist/debug-bundle-CRpYV_ui.js.map +1 -0
  123. package/dist/defineProperty-X1c4tIPD.cjs +1 -0
  124. package/dist/defineProperty-s2S8BXUc.js +35 -0
  125. package/dist/doctor.cjs +1 -1
  126. package/dist/doctor.cjs.map +1 -1
  127. package/dist/doctor.d.cts +36 -0
  128. package/dist/doctor.d.ts +5 -2
  129. package/dist/doctor.js +121 -89
  130. package/dist/doctor.js.map +1 -1
  131. package/dist/errors-BE_EZV7Q.js +86 -0
  132. package/dist/errors-BE_EZV7Q.js.map +1 -0
  133. package/dist/errors-CNPbesMs.cjs +3 -0
  134. package/dist/errors-CNPbesMs.cjs.map +1 -0
  135. package/dist/factory-CTi0Is3F.js +404 -0
  136. package/dist/factory-CTi0Is3F.js.map +1 -0
  137. package/dist/factory-hRrH32v5.cjs +2 -0
  138. package/dist/factory-hRrH32v5.cjs.map +1 -0
  139. package/dist/guards-BlYGRK4l.js +10 -0
  140. package/dist/guards-BlYGRK4l.js.map +1 -0
  141. package/dist/guards-EjG3ahFp.cjs +2 -0
  142. package/dist/guards-EjG3ahFp.cjs.map +1 -0
  143. package/dist/{identity-BrQp_5J5.js → identity-DdhKgrpk.js} +20 -24
  144. package/dist/identity-DdhKgrpk.js.map +1 -0
  145. package/dist/identity-DlWRIuwy.cjs +2 -0
  146. package/dist/identity-DlWRIuwy.cjs.map +1 -0
  147. package/dist/index.cjs +1 -1
  148. package/dist/index.cjs.map +1 -1
  149. package/dist/index.d.cts +300 -0
  150. package/dist/index.d.ts +89 -98
  151. package/dist/index.js +1173 -1506
  152. package/dist/index.js.map +1 -1
  153. package/dist/indexeddb-storage-CL9uqBCy.cjs +2 -0
  154. package/dist/indexeddb-storage-CL9uqBCy.cjs.map +1 -0
  155. package/dist/{indexeddb-storage-DLXQzAGh.js → indexeddb-storage-GHdl0t8A.js} +51 -47
  156. package/dist/indexeddb-storage-GHdl0t8A.js.map +1 -0
  157. package/dist/interactions-CUkzK8sR.cjs +2 -0
  158. package/dist/interactions-CUkzK8sR.cjs.map +1 -0
  159. package/dist/{interactions-B6z2I4tU.js → interactions-DiFvCosX.js} +41 -49
  160. package/dist/interactions-DiFvCosX.js.map +1 -0
  161. package/dist/journey-B4Adltjm.cjs +2 -0
  162. package/dist/journey-B4Adltjm.cjs.map +1 -0
  163. package/dist/{journey-35yCMNFo.js → journey-D2_sia57.js} +45 -48
  164. package/dist/journey-D2_sia57.js.map +1 -0
  165. package/dist/{library-console-Dl_Ly6DQ.js → library-console-Btrzt814.js} +2 -2
  166. package/dist/{library-console-Dl_Ly6DQ.js.map → library-console-Btrzt814.js.map} +1 -1
  167. package/dist/{library-console-BFWEuQsl.cjs → library-console-CPW6bvZH.cjs} +2 -2
  168. package/dist/{library-console-BFWEuQsl.cjs.map → library-console-CPW6bvZH.cjs.map} +1 -1
  169. package/dist/{library-request-nI6pvI6I.js → library-request-BJ9PLRaD.js} +2 -2
  170. package/dist/{library-request-nI6pvI6I.js.map → library-request-BJ9PLRaD.js.map} +1 -1
  171. package/dist/{library-request-Da-CHKzT.cjs → library-request-D7OvTxZV.cjs} +2 -2
  172. package/dist/{library-request-Da-CHKzT.cjs.map → library-request-D7OvTxZV.cjs.map} +1 -1
  173. package/dist/{lifecycle-CZ6RRXc6.js → lifecycle-22CUCrc9.js} +21 -29
  174. package/dist/lifecycle-22CUCrc9.js.map +1 -0
  175. package/dist/lifecycle-IaAm1mOC.cjs +2 -0
  176. package/dist/lifecycle-IaAm1mOC.cjs.map +1 -0
  177. package/dist/{log-record-DIA6McNr.js → log-record-BNiLfqtL.js} +8 -7
  178. package/dist/log-record-BNiLfqtL.js.map +1 -0
  179. package/dist/log-record-CkivuiEl.cjs +2 -0
  180. package/dist/log-record-CkivuiEl.cjs.map +1 -0
  181. package/dist/long-frames-BUUbXd-B.cjs +2 -0
  182. package/dist/long-frames-BUUbXd-B.cjs.map +1 -0
  183. package/dist/{long-frames-430_85Da.js → long-frames-DNFaRnC3.js} +18 -22
  184. package/dist/long-frames-DNFaRnC3.js.map +1 -0
  185. package/dist/models/batch.d.cts +57 -0
  186. package/dist/models/batch.d.ts +2 -2
  187. package/dist/models/bus.d.cts +158 -0
  188. package/dist/models/bus.d.ts +22 -2
  189. package/dist/models/config.d.cts +1540 -0
  190. package/dist/models/config.d.ts +360 -259
  191. package/dist/models/drop.d.cts +54 -0
  192. package/dist/models/drop.d.ts +16 -3
  193. package/dist/models/health.d.cts +148 -0
  194. package/dist/models/health.d.ts +108 -12
  195. package/dist/models/log-record.d.cts +61 -0
  196. package/dist/models/metric.d.cts +139 -0
  197. package/dist/models/metric.d.ts +13 -2
  198. package/dist/models/plugin.d.cts +47 -0
  199. package/dist/models/plugin.d.ts +3 -3
  200. package/dist/models/replay.d.cts +60 -0
  201. package/dist/models/serializer.d.cts +23 -0
  202. package/dist/models/serializer.d.ts +1 -1
  203. package/dist/models/storage.d.cts +95 -0
  204. package/dist/models/storage.d.ts +7 -5
  205. package/dist/network-CGMLQ-mA.cjs +2 -0
  206. package/dist/network-CGMLQ-mA.cjs.map +1 -0
  207. package/dist/{network-C7SkLf4v.js → network-on2zZT6H.js} +51 -51
  208. package/dist/network-on2zZT6H.js.map +1 -0
  209. package/dist/{otlp-2MCrC3kd.cjs → otlp-BENHf3g9.cjs} +2 -2
  210. package/dist/{otlp-2MCrC3kd.cjs.map → otlp-BENHf3g9.cjs.map} +1 -1
  211. package/dist/{otlp-COq033e3.js → otlp-DimfrRor.js} +12 -12
  212. package/dist/{otlp-COq033e3.js.map → otlp-DimfrRor.js.map} +1 -1
  213. package/dist/{platform-CVewe4wQ.js → platform-BaaFIPCU.js} +10 -10
  214. package/dist/{platform-CVewe4wQ.js.map → platform-BaaFIPCU.js.map} +1 -1
  215. package/dist/{platform-12uR7kBQ.cjs → platform-CfA3-7sJ.cjs} +2 -2
  216. package/dist/{platform-12uR7kBQ.cjs.map → platform-CfA3-7sJ.cjs.map} +1 -1
  217. package/dist/{profiler-BVWIOgnq.js → profiler-BAZoh7A4.js} +89 -107
  218. package/dist/profiler-BAZoh7A4.js.map +1 -0
  219. package/dist/profiler-D4tJpDRc.cjs +2 -0
  220. package/dist/profiler-D4tJpDRc.cjs.map +1 -0
  221. package/dist/profiler-frames-C4xr7KfH.cjs +2 -0
  222. package/dist/profiler-frames-C4xr7KfH.cjs.map +1 -0
  223. package/dist/{profiler-frames-CLXlT_xL.js → profiler-frames-cJMx9wNM.js} +29 -37
  224. package/dist/profiler-frames-cJMx9wNM.js.map +1 -0
  225. package/dist/remote-rules-Dz9MRAsB.js +95 -0
  226. package/dist/remote-rules-Dz9MRAsB.js.map +1 -0
  227. package/dist/remote-rules-_tY0zj5o.cjs +2 -0
  228. package/dist/remote-rules-_tY0zj5o.cjs.map +1 -0
  229. package/dist/replay-B3gFXIZd.cjs +2 -0
  230. package/dist/replay-B3gFXIZd.cjs.map +1 -0
  231. package/dist/replay-Ds-ANH34.js +310 -0
  232. package/dist/replay-Ds-ANH34.js.map +1 -0
  233. package/dist/reports-BDSe4dFH.cjs +2 -0
  234. package/dist/reports-BDSe4dFH.cjs.map +1 -0
  235. package/dist/{reports-BuXekPOS.js → reports-C-thq-bk.js} +25 -30
  236. package/dist/reports-C-thq-bk.js.map +1 -0
  237. package/dist/resource-timing-C576gFIQ.cjs +2 -0
  238. package/dist/resource-timing-C576gFIQ.cjs.map +1 -0
  239. package/dist/{resource-timing-CXGHwFRD.js → resource-timing-eUl2dNgC.js} +20 -23
  240. package/dist/resource-timing-eUl2dNgC.js.map +1 -0
  241. package/dist/response-body-YdNl-HkR.cjs +3 -0
  242. package/dist/response-body-YdNl-HkR.cjs.map +1 -0
  243. package/dist/response-body-eoSQpLiH.js +331 -0
  244. package/dist/response-body-eoSQpLiH.js.map +1 -0
  245. package/dist/rotation-Cwct4ckk.js +94 -0
  246. package/dist/rotation-Cwct4ckk.js.map +1 -0
  247. package/dist/rotation-D4qUAHAu.cjs +2 -0
  248. package/dist/rotation-D4qUAHAu.cjs.map +1 -0
  249. package/dist/sampling-BlrI8jor.js +63 -0
  250. package/dist/sampling-BlrI8jor.js.map +1 -0
  251. package/dist/sampling-mXt4dstx.cjs +2 -0
  252. package/dist/sampling-mXt4dstx.cjs.map +1 -0
  253. package/dist/{sanitize-CNmsD9r3.js → sanitize-Ba0KqU06.js} +2 -2
  254. package/dist/sanitize-Ba0KqU06.js.map +1 -0
  255. package/dist/{sanitize-ChLn97Ch.cjs → sanitize-DQyiI_KY.cjs} +2 -2
  256. package/dist/sanitize-DQyiI_KY.cjs.map +1 -0
  257. package/dist/sender-BdRuNVhF.cjs +2 -0
  258. package/dist/sender-BdRuNVhF.cjs.map +1 -0
  259. package/dist/sender-Dv8rAmpV.js +979 -0
  260. package/dist/sender-Dv8rAmpV.js.map +1 -0
  261. package/dist/storage/context-storage.d.cts +90 -0
  262. package/dist/storage/context-storage.d.ts +5 -5
  263. package/dist/storage/emergency-queue.d.cts +27 -0
  264. package/dist/storage/emergency-queue.d.ts +4 -4
  265. package/dist/storage/eviction.d.cts +40 -0
  266. package/dist/storage/eviction.d.ts +1 -1
  267. package/dist/storage/factory.d.cts +21 -0
  268. package/dist/storage/factory.d.ts +3 -3
  269. package/dist/storage/gap.d.cts +20 -0
  270. package/dist/storage/gap.d.ts +3 -3
  271. package/dist/storage/idb-driver.d.cts +93 -0
  272. package/dist/storage/idb-driver.d.ts +1 -1
  273. package/dist/storage/indexeddb-storage.d.cts +97 -0
  274. package/dist/storage/indexeddb-storage.d.ts +12 -4
  275. package/dist/storage/keys.d.cts +17 -0
  276. package/dist/storage/keys.d.ts +2 -2
  277. package/dist/storage/local-storage.d.cts +139 -0
  278. package/dist/storage/local-storage.d.ts +11 -4
  279. package/dist/storage/memory-storage.d.cts +73 -0
  280. package/dist/storage/memory-storage.d.ts +4 -3
  281. package/dist/storage/persistence.d.cts +8 -0
  282. package/dist/storage/persistence.d.ts +2 -2
  283. package/dist/storage/stored-context.d.cts +34 -0
  284. package/dist/storage/stored-context.d.ts +34 -0
  285. package/dist/stored-context-B2EzVuYm.js +51 -0
  286. package/dist/stored-context-B2EzVuYm.js.map +1 -0
  287. package/dist/stored-context-CXt7eHZL.cjs +2 -0
  288. package/dist/stored-context-CXt7eHZL.cjs.map +1 -0
  289. package/dist/storm-C-zYSdDX.cjs +2 -0
  290. package/dist/storm-C-zYSdDX.cjs.map +1 -0
  291. package/dist/storm-DjKetLKZ.js +9 -0
  292. package/dist/storm-DjKetLKZ.js.map +1 -0
  293. package/dist/transport/compression.d.cts +7 -0
  294. package/dist/transport/custom-transport.d.cts +22 -0
  295. package/dist/transport/custom-transport.d.ts +6 -5
  296. package/dist/transport/errors.d.cts +31 -0
  297. package/dist/transport/exit-flush.d.cts +135 -0
  298. package/dist/transport/exit-flush.d.ts +30 -13
  299. package/dist/transport/headers.d.cts +8 -0
  300. package/dist/transport/headers.d.ts +2 -2
  301. package/dist/transport/http-transport.d.cts +116 -0
  302. package/dist/transport/http-transport.d.ts +20 -8
  303. package/dist/transport/memory-transport.d.cts +30 -0
  304. package/dist/transport/memory-transport.d.ts +2 -2
  305. package/dist/transport/response-body.d.cts +49 -0
  306. package/dist/transport/response-body.d.ts +49 -0
  307. package/dist/transport/retry-engine.d.cts +129 -0
  308. package/dist/transport/retry-engine.d.ts +27 -9
  309. package/dist/transport/serializers/ecs.d.cts +3 -0
  310. package/dist/transport/serializers/ecs.d.ts +1 -1
  311. package/dist/transport/serializers/otlp-metrics.d.cts +3 -0
  312. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  313. package/dist/transport/serializers/otlp-traces.d.cts +3 -0
  314. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  315. package/dist/transport/serializers/otlp.d.cts +47 -0
  316. package/dist/transport/serializers/otlp.d.ts +2 -2
  317. package/dist/transport/serializers/select.d.cts +38 -0
  318. package/dist/transport/serializers/select.d.ts +5 -5
  319. package/dist/transport/status-transport.d.cts +129 -0
  320. package/dist/transport/status-transport.d.ts +25 -8
  321. package/dist/transport/worker-client.d.cts +23 -0
  322. package/dist/transport/worker-client.d.ts +12 -3
  323. package/dist/transport/worker-entry.d.cts +5 -0
  324. package/dist/transport/worker-entry.d.ts +1 -1
  325. package/dist/transport/worker-protocol.d.cts +38 -0
  326. package/dist/transport/worker-protocol.d.ts +4 -2
  327. package/dist/transport/worker-server.d.cts +3 -0
  328. package/dist/transport/worker-server.d.ts +1 -1
  329. package/dist/transport/worker-transport.d.cts +10 -0
  330. package/dist/transport/worker-transport.d.ts +5 -4
  331. package/dist/types-BAerHgCq.js.map +1 -1
  332. package/dist/types-C7WNpnG1.cjs.map +1 -1
  333. package/dist/{unclean-exit-Cob_jyTv.js → unclean-exit-DQD1cT7c.js} +23 -30
  334. package/dist/unclean-exit-DQD1cT7c.js.map +1 -0
  335. package/dist/unclean-exit-py99ApzT.cjs +2 -0
  336. package/dist/unclean-exit-py99ApzT.cjs.map +1 -0
  337. package/dist/{user-timing-DgHubxCI.js → user-timing-BePqb1uN.js} +15 -17
  338. package/dist/user-timing-BePqb1uN.js.map +1 -0
  339. package/dist/user-timing-D6XTmpuM.cjs +2 -0
  340. package/dist/user-timing-D6XTmpuM.cjs.map +1 -0
  341. package/dist/utils/console.d.cts +36 -0
  342. package/dist/utils/console.d.ts +4 -4
  343. package/dist/utils/deadline.d.cts +14 -0
  344. package/dist/utils/error-like.d.cts +25 -0
  345. package/dist/utils/fixed-window.d.cts +25 -0
  346. package/dist/utils/global-scope.d.cts +20 -0
  347. package/dist/utils/guards.d.cts +14 -0
  348. package/dist/utils/guards.d.ts +8 -0
  349. package/dist/utils/identity.d.cts +109 -0
  350. package/dist/utils/identity.d.ts +3 -4
  351. package/dist/utils/library-console.d.cts +11 -0
  352. package/dist/utils/library-request.d.cts +24 -0
  353. package/dist/utils/lock.d.cts +24 -0
  354. package/dist/utils/lock.d.ts +1 -1
  355. package/dist/utils/openfin.d.cts +48 -0
  356. package/dist/utils/patch.d.cts +9 -0
  357. package/dist/utils/platform.d.cts +62 -0
  358. package/dist/utils/platform.d.ts +2 -2
  359. package/dist/utils/sanitize.d.cts +52 -0
  360. package/dist/utils/sanitize.d.ts +1 -1
  361. package/dist/utils/sequence.d.cts +10 -0
  362. package/dist/utils/tracing.d.cts +158 -0
  363. package/dist/utils/tracing.d.ts +11 -4
  364. package/dist/utils/unref.d.cts +9 -0
  365. package/dist/web-socket-CoIUBM3C.cjs +2 -0
  366. package/dist/{web-socket-DthJuSAg.js.map → web-socket-CoIUBM3C.cjs.map} +1 -1
  367. package/dist/{web-socket-DthJuSAg.js → web-socket-DSHgDiZ6.js} +23 -28
  368. package/dist/web-socket-DSHgDiZ6.js.map +1 -0
  369. package/dist/{web-vitals-CsGCWnUr.js → web-vitals-4pWACwaR.js} +15 -21
  370. package/dist/web-vitals-4pWACwaR.js.map +1 -0
  371. package/dist/web-vitals-__X7t4pj.cjs +2 -0
  372. package/dist/web-vitals-__X7t4pj.cjs.map +1 -0
  373. package/dist/worker-protocol-QbvqNazn.cjs +2 -0
  374. package/dist/worker-protocol-QbvqNazn.cjs.map +1 -0
  375. package/dist/{worker-protocol-B0_8rWy5.js → worker-protocol-x074Rpet.js} +14 -11
  376. package/dist/worker-protocol-x074Rpet.js.map +1 -0
  377. package/dist/worker-server-CFe4nvos.cjs +2 -0
  378. package/dist/worker-server-CFe4nvos.cjs.map +1 -0
  379. package/dist/worker-server-iUVSjH8L.js +94 -0
  380. package/dist/worker-server-iUVSjH8L.js.map +1 -0
  381. package/dist/worker-transport-CRAX-09c.cjs +2 -0
  382. package/dist/worker-transport-CRAX-09c.cjs.map +1 -0
  383. package/dist/worker-transport-Dy1KMA7t.js +190 -0
  384. package/dist/worker-transport-Dy1KMA7t.js.map +1 -0
  385. package/llms.txt +397 -0
  386. package/package.json +54 -46
  387. package/dist/bus-D_7pd7RN.cjs +0 -2
  388. package/dist/bus-D_7pd7RN.cjs.map +0 -1
  389. package/dist/bus-ecxUNTja.js.map +0 -1
  390. package/dist/console-CLz_PvFn.cjs +0 -2
  391. package/dist/console-CLz_PvFn.cjs.map +0 -1
  392. package/dist/console-cwgHKXvM.js +0 -82
  393. package/dist/console-cwgHKXvM.js.map +0 -1
  394. package/dist/constants-Bwl_YtQi.js +0 -349
  395. package/dist/constants-Bwl_YtQi.js.map +0 -1
  396. package/dist/constants-DakMxVB2.cjs +0 -2
  397. package/dist/constants-DakMxVB2.cjs.map +0 -1
  398. package/dist/context-storage-BjzeBSxH.cjs +0 -2
  399. package/dist/context-storage-BjzeBSxH.cjs.map +0 -1
  400. package/dist/context-storage-BzkoHzkQ.js +0 -51
  401. package/dist/context-storage-BzkoHzkQ.js.map +0 -1
  402. package/dist/debug-bundle-BOdYmCeV.js +0 -32
  403. package/dist/debug-bundle-BOdYmCeV.js.map +0 -1
  404. package/dist/debug-bundle-Ex4L_LSP.cjs +0 -2
  405. package/dist/debug-bundle-Ex4L_LSP.cjs.map +0 -1
  406. package/dist/emergency-queue-B9WZxanZ.js +0 -67
  407. package/dist/emergency-queue-B9WZxanZ.js.map +0 -1
  408. package/dist/emergency-queue-HBpL5r3V.cjs +0 -2
  409. package/dist/emergency-queue-HBpL5r3V.cjs.map +0 -1
  410. package/dist/errors-D6bwgJtO.js +0 -92
  411. package/dist/errors-D6bwgJtO.js.map +0 -1
  412. package/dist/errors-DCOCRdSi.cjs +0 -3
  413. package/dist/errors-DCOCRdSi.cjs.map +0 -1
  414. package/dist/factory-DLFDjdLv.cjs +0 -2
  415. package/dist/factory-DLFDjdLv.cjs.map +0 -1
  416. package/dist/factory-e9Qo3K0z.js +0 -276
  417. package/dist/factory-e9Qo3K0z.js.map +0 -1
  418. package/dist/guards-Cidk71ME.js +0 -7
  419. package/dist/guards-Cidk71ME.js.map +0 -1
  420. package/dist/guards-nJ70syPt.cjs +0 -2
  421. package/dist/guards-nJ70syPt.cjs.map +0 -1
  422. package/dist/identity-BlvlgjrU.cjs +0 -2
  423. package/dist/identity-BlvlgjrU.cjs.map +0 -1
  424. package/dist/identity-BrQp_5J5.js.map +0 -1
  425. package/dist/indexeddb-storage-CtLvZH1r.cjs +0 -2
  426. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +0 -1
  427. package/dist/indexeddb-storage-DLXQzAGh.js.map +0 -1
  428. package/dist/interactions-B6z2I4tU.js.map +0 -1
  429. package/dist/interactions-P6pz08Jn.cjs +0 -2
  430. package/dist/interactions-P6pz08Jn.cjs.map +0 -1
  431. package/dist/journey-35yCMNFo.js.map +0 -1
  432. package/dist/journey-DAGh5h9k.cjs +0 -2
  433. package/dist/journey-DAGh5h9k.cjs.map +0 -1
  434. package/dist/keys-BHhw_0Wh.cjs +0 -2
  435. package/dist/keys-BHhw_0Wh.cjs.map +0 -1
  436. package/dist/keys-BU9j5YqW.js +0 -16
  437. package/dist/keys-BU9j5YqW.js.map +0 -1
  438. package/dist/lifecycle-BGGOcN4N.cjs +0 -2
  439. package/dist/lifecycle-BGGOcN4N.cjs.map +0 -1
  440. package/dist/lifecycle-CZ6RRXc6.js.map +0 -1
  441. package/dist/log-record-D7bA1RPb.cjs +0 -2
  442. package/dist/log-record-D7bA1RPb.cjs.map +0 -1
  443. package/dist/log-record-DIA6McNr.js.map +0 -1
  444. package/dist/long-frames-430_85Da.js.map +0 -1
  445. package/dist/long-frames-Dd8tsi2U.cjs +0 -2
  446. package/dist/long-frames-Dd8tsi2U.cjs.map +0 -1
  447. package/dist/models/stats.d.ts +0 -11
  448. package/dist/network-C7SkLf4v.js.map +0 -1
  449. package/dist/network-pEX3PAJv.cjs +0 -2
  450. package/dist/network-pEX3PAJv.cjs.map +0 -1
  451. package/dist/profiler-BVWIOgnq.js.map +0 -1
  452. package/dist/profiler-eVCknCzS.cjs +0 -2
  453. package/dist/profiler-eVCknCzS.cjs.map +0 -1
  454. package/dist/profiler-frames-CLXlT_xL.js.map +0 -1
  455. package/dist/profiler-frames-Dg2OebB2.cjs +0 -2
  456. package/dist/profiler-frames-Dg2OebB2.cjs.map +0 -1
  457. package/dist/remote-rules-BJGDJGwA.js +0 -98
  458. package/dist/remote-rules-BJGDJGwA.js.map +0 -1
  459. package/dist/remote-rules-CJD3ToVk.cjs +0 -2
  460. package/dist/remote-rules-CJD3ToVk.cjs.map +0 -1
  461. package/dist/replay-0zAJv9T3.js +0 -338
  462. package/dist/replay-0zAJv9T3.js.map +0 -1
  463. package/dist/replay-DomJpXqW.cjs +0 -2
  464. package/dist/replay-DomJpXqW.cjs.map +0 -1
  465. package/dist/reports-BsbqmP8h.cjs +0 -2
  466. package/dist/reports-BsbqmP8h.cjs.map +0 -1
  467. package/dist/reports-BuXekPOS.js.map +0 -1
  468. package/dist/resource-timing-CXGHwFRD.js.map +0 -1
  469. package/dist/resource-timing-DkycFGDa.cjs +0 -2
  470. package/dist/resource-timing-DkycFGDa.cjs.map +0 -1
  471. package/dist/sampling-Dd0wllyq.cjs +0 -2
  472. package/dist/sampling-Dd0wllyq.cjs.map +0 -1
  473. package/dist/sampling-UUDbi3K0.js +0 -60
  474. package/dist/sampling-UUDbi3K0.js.map +0 -1
  475. package/dist/sanitize-CNmsD9r3.js.map +0 -1
  476. package/dist/sanitize-ChLn97Ch.cjs.map +0 -1
  477. package/dist/select-CTk-K5mG.cjs +0 -3
  478. package/dist/select-CTk-K5mG.cjs.map +0 -1
  479. package/dist/select-DPv_j6wq.js +0 -270
  480. package/dist/select-DPv_j6wq.js.map +0 -1
  481. package/dist/sender-15zEsZpr.js +0 -857
  482. package/dist/sender-15zEsZpr.js.map +0 -1
  483. package/dist/sender-Bfpv9tad.cjs +0 -2
  484. package/dist/sender-Bfpv9tad.cjs.map +0 -1
  485. package/dist/storage-BA9RqRO-.cjs +0 -2
  486. package/dist/storage-BA9RqRO-.cjs.map +0 -1
  487. package/dist/storage-DZwed89z.js +0 -16
  488. package/dist/storage-DZwed89z.js.map +0 -1
  489. package/dist/storm-BTSNTIWI.js +0 -9
  490. package/dist/storm-BTSNTIWI.js.map +0 -1
  491. package/dist/storm-D0_qZOEg.cjs +0 -2
  492. package/dist/storm-D0_qZOEg.cjs.map +0 -1
  493. package/dist/unclean-exit-ClGzrc2A.cjs +0 -2
  494. package/dist/unclean-exit-ClGzrc2A.cjs.map +0 -1
  495. package/dist/unclean-exit-Cob_jyTv.js.map +0 -1
  496. package/dist/user-timing-CdYqx3PF.cjs +0 -2
  497. package/dist/user-timing-CdYqx3PF.cjs.map +0 -1
  498. package/dist/user-timing-DgHubxCI.js.map +0 -1
  499. package/dist/utils/timer.d.ts +0 -19
  500. package/dist/web-socket-BTuvYoJI.cjs +0 -2
  501. package/dist/web-socket-BTuvYoJI.cjs.map +0 -1
  502. package/dist/web-vitals-Ch5BpDmo.cjs +0 -2
  503. package/dist/web-vitals-Ch5BpDmo.cjs.map +0 -1
  504. package/dist/web-vitals-CsGCWnUr.js.map +0 -1
  505. package/dist/worker-protocol-B0_8rWy5.js.map +0 -1
  506. package/dist/worker-protocol-BjzFORfq.cjs +0 -2
  507. package/dist/worker-protocol-BjzFORfq.cjs.map +0 -1
  508. package/dist/worker-server-4en-Lt-3.cjs +0 -2
  509. package/dist/worker-server-4en-Lt-3.cjs.map +0 -1
  510. package/dist/worker-server-Cne9MX9I.js +0 -83
  511. package/dist/worker-server-Cne9MX9I.js.map +0 -1
  512. package/dist/worker-transport-B-GF4Aqn.cjs +0 -2
  513. package/dist/worker-transport-B-GF4Aqn.cjs.map +0 -1
  514. package/dist/worker-transport-C3SjJAEC.js +0 -200
  515. package/dist/worker-transport-C3SjJAEC.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-C7SkLf4v.js","names":["SERVER_TIMING_HEADER","SERVER_TIMING_MAX_CHARS","isErrorLike","isTransportPending","isLibraryRequest","patch","recordedUrl","matchesAny","splitHeader","parts","start","quoted","escaped","i","text","char","separator","xhrServerTiming","headers","readServerTiming","result","header","part","rawName","params","name","entry","seen","param","equal","key","value","duration","match","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","readTiming","call","original","startedAt","response","read","trace","injected","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","timing","span","endMs","rounded"],"sources":["../src/capture/server-timing.ts","../src/capture/network.ts"],"sourcesContent":["import { SERVER_TIMING_MAX_CHARS, SERVER_TIMING_MAX_ENTRIES } from \"../constants\";\n\n/** One duration entry from the Server-Timing response header. */\ninterface ServerTimingEntry {\n name: string;\n duration: number;\n description: string;\n}\n\n/** Server duration entries, plus the server span they name. */\nexport interface ServerTiming {\n entries: ServerTimingEntry[];\n link?: { traceId: string; spanId: string };\n}\n\n/** Splits a header on separators outside quoted strings. An escaped quote doesn't end a string. */\nfunction splitHeader(text: string, separator: string): string[] {\n const parts: string[] = [];\n let start = 0;\n let quoted = false;\n let escaped = false;\n\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (escaped) {\n escaped = false;\n } else if (quoted && char === \"\\\\\") {\n escaped = true;\n } else if (char === '\"') {\n quoted = !quoted;\n } else if (!quoted && char === separator) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n }\n\n parts.push(text.slice(start));\n return parts;\n}\n\n/** Finds the header in an XHR header list. Reading a hidden header directly logs a Chrome error. */\nexport function xhrServerTiming(headers: string): string | null {\n return /^server-timing:(.*)$/im.exec(headers)?.[1] ?? null;\n}\n\n/** Reads a bounded number of server duration entries. A missing header gives none. */\nexport function readServerTiming(header: string | null): ServerTiming {\n const result: ServerTiming = { entries: [] };\n if (!header) {\n return result;\n }\n\n for (const part of splitHeader(header.slice(0, SERVER_TIMING_MAX_CHARS), \",\").slice(\n 0,\n SERVER_TIMING_MAX_ENTRIES,\n )) {\n const [rawName, ...params] = splitHeader(part, \";\");\n const name = rawName.trim();\n if (!/^[!#$%&'*+.^_`|~\\da-z-]+$/i.test(name)) {\n continue;\n }\n\n const entry: ServerTimingEntry = { name, duration: 0, description: \"\" };\n const seen = new Set<string>();\n for (const param of params) {\n const equal = param.indexOf(\"=\");\n if (equal < 0) {\n continue;\n }\n\n const key = param.slice(0, equal).trim().toLowerCase();\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n\n let value = param.slice(equal + 1).trim();\n if (value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1).replace(/\\\\(.)/g, \"$1\");\n }\n\n if (key === \"dur\") {\n const duration = Number(value);\n if (Number.isFinite(duration) && duration >= 0) {\n entry.duration = duration;\n }\n } else if (key === \"desc\") {\n entry.description = value;\n }\n }\n\n result.entries.push(entry);\n if (name.toLowerCase() === \"traceparent\") {\n const match = /^00-([\\da-f]{32})-([\\da-f]{16})-[\\da-f]{2}$/.exec(entry.description);\n if (match && /[1-9a-f]/.test(match[1]) && /[1-9a-f]/.test(match[2])) {\n result.link = { traceId: match[1], spanId: match[2] };\n }\n }\n }\n\n return result;\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record the outcome and timing of network requests.\n\nimport { SERVER_TIMING_HEADER } from \"../constants\";\nimport { readServerTiming, xhrServerTiming } from \"./server-timing\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as its OpenTelemetry name says. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram from the OpenTelemetry semantic conventions, with the\n * boundaries the conventions recommend.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Builds the low-cardinality attributes for one request. The path and the query stay out,\n * because every distinct attribute value creates a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error What failed, for a request with no response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request with no response takes its error's type, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** The delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** The client span the traceparent names. */\n span?: ClientSpan;\n}\n\n/** An XMLHttpRequest with our tracking metadata attached. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** The XMLHttpRequest prototype methods we wrap, kept unbound. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** The delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** The client span the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL from a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`, but its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts anything with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init's method wins over the Request's.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. Defaults to GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Checks whether a fetch input is an object that isn't a Request or a URL from this realm,\n * for example a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. Never throws on a method that isn't a string.\n * @param method The caller's method argument.\n * @returns The uppercase method for a string, or the text form of anything else.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Guards against wrapping a function twice. */\n private installed = false;\n\n /** Restore functions for the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True once we've reported a request made during a custom transport call. Reported once. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger, breadcrumbs and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments the network APIs the configuration selects. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores every host function that still holds this capture's wrapper.\n * 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 for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Checks whether a URL matches the ignore patterns.\n * @param url Request target URL.\n * @returns True if the URL must stay out of the telemetry.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Otherwise a failed POST becomes a\n // log record, the record causes a new POST, and the loop never stops.\n // A custom transport has no known URL, but its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Checks whether a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Only add headers to allowlisted URLs. A traceparent on a third-party request triggers\n // a CORS preflight that the third party doesn't answer, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Wraps globalThis.fetch to inject the trace headers and log the outcome. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n plan: FetchPlan,\n status: number,\n durationMs: number,\n error: unknown,\n readTiming?: () => string | null,\n ): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n readTiming,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined, () =>\n response.headers.get(SERVER_TIMING_HEADER),\n );\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input The caller's fetch input.\n * @param init The caller's fetch init.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // This read runs inside the caller's fetch call, so a throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces every header on a foreign Request, Authorization\n // included. So a foreign input goes out without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Don't spread a non-empty init next to a Request input. That runs the Request\n // constructor on `input` again and reads its body, and reading a body twice\n // throws a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Only record the client span for a request that actually carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send exactly what the caller gave us. A missing header is better than a failed\n // request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Wraps the open and send methods on the XMLHttpRequest prototype. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (\n meta: XhrMeta,\n status: number,\n durationMs: number,\n readTiming: () => string | null,\n ): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n readTiming,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // This read runs inside the caller's open call, so a throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener on every send, so the old one must not\n // fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt, () =>\n xhrServerTiming(this.getAllResponseHeaders()),\n );\n },\n { once: true },\n );\n\n // setRequestHeader only works between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records the outcome of a request as attributes and a breadcrumb.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The query is removed here unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error The caught error, for a failed request.\n * @param span The client span the request's traceparent names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n readTiming?: () => string | null,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n ) {\n return;\n }\n\n const timing =\n this.ctx.config.capture.serverTiming && readTiming\n ? this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the Server-Timing response header.\",\n () => readServerTiming(readTiming()),\n )\n : undefined;\n\n // Strip the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL, and only the recorded URL loses its query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A transport request made after an await gets recorded, and that record causes the next\n // send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard, so a URL that doesn't parse can't stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n link: timing?.link,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This runs inside the caller's fetch call, so an error here must not fail the caller's\n // request.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n ...(timing && timing.entries.length > 0 ? { \"server.timing\": timing.entries } : {}),\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG, which the default minLevel of INFO drops. That way only\n // failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. If that fails, the request goes out without them.\n * @param xhr A request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":";;;;;;;AAgBA,SAASQ,EAAY,GAAc,GAA6B;CAC9D,IAAMC,IAAkB,CAAC,GACrBC,IAAQ,GACRC,IAAS,IACTC,IAAU;CAEd,KAAK,IAAIC,IAAI,GAAGA,IAAIC,EAAK,QAAQ,KAAK;EACpC,IAAMC,IAAOD,EAAKD;EAClB,AAAID,IACF,IAAU,KACDD,KAAUI,MAAS,OAC5B,IAAU,KACDA,MAAS,OAClB,IAAS,CAACJ,IACD,CAACA,KAAUI,MAASC,MAC7BP,EAAM,KAAKK,EAAK,MAAMJ,GAAOG,CAAC,CAAC,GAC/B,IAAQA,IAAI;CAEhB;CAGA,OADAJ,EAAM,KAAKK,EAAK,MAAMJ,CAAK,CAAC,GACrBD;AACT;AAGA,SAAgBQ,EAAgB,GAAgC;CAC9D,OAAO,yBAAyB,KAAKC,CAAO,CAAC,GAAG,MAAM;AACxD;AAGA,SAAgBC,EAAiB,GAAqC;CACpE,IAAMC,IAAuB,EAAE,SAAS,CAAC,EAAE;CAC3C,IAAI,CAACC,GACH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AI;EACF,IAAMX,IAAQhB,EAAI,QAAQ,QAAQ;EAClC,KAAK,IAAM,CAACtB,GAAKC,MAAU,OAAO,QAAQqC,EAAM,OAAO,GACrD,EAAI,iBAAiBtC,GAAKC,CAAK;EAEjC,OAAOqC,EAAM;CACf,SAAS1B,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;EACA;CACF;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./error-like-gGRx2s36.cjs"),n=require("./library-request-Da-CHKzT.cjs"),r=require("./patch-BX8KrPCT.cjs"),i=require("./platform-12uR7kBQ.cjs"),a=require("./types-C7WNpnG1.cjs");function o(e,t){let n=[],r=0,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];a?a=!1:i&&s===`\\`?a=!0:s===`"`?i=!i:!i&&s===t&&(n.push(e.slice(r,o)),r=o+1)}return n.push(e.slice(r)),n}function s(e){return/^server-timing:(.*)$/im.exec(e)?.[1]??null}function c(t){let n={entries:[]};if(!t)return n;for(let r of o(t.slice(0,e.On),`,`).slice(0,32)){let[e,...t]=o(r,`;`),i=e.trim();if(!/^[!#$%&'*+.^_`|~\da-z-]+$/i.test(i))continue;let a={name:i,duration:0,description:``},s=new Set;for(let e of t){let t=e.indexOf(`=`);if(t<0)continue;let n=e.slice(0,t).trim().toLowerCase();if(s.has(n))continue;s.add(n);let r=e.slice(t+1).trim();if(r.startsWith(`"`)&&r.endsWith(`"`)&&(r=r.slice(1,-1).replace(/\\(.)/g,`$1`)),n===`dur`){let e=Number(r);Number.isFinite(e)&&e>=0&&(a.duration=e)}else n===`desc`&&(a.description=r)}if(n.entries.push(a),i.toLowerCase()===`traceparent`){let e=/^00-([\da-f]{32})-([\da-f]{16})-[\da-f]{2}$/.exec(a.description);e&&/[1-9a-f]/.test(e[1])&&/[1-9a-f]/.test(e[2])&&(n.link={traceId:e[1],spanId:e[2]})}}return n}var l=1e3,u={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function d(e,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":e,"server.address":new URL(n,a).hostname};if(r===0){let e=t.r(i)?i.name:``;return o[`error.type`]=e===``?`_OTHER`:e,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function f(){return XMLHttpRequest.prototype}function p(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function m(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),g(n??`GET`)}function h(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function g(e){return typeof e==`string`?e.toUpperCase():String(e)}var _=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return n.t()||a.t(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let t=!0,n=(e,t)=>this.prepareFetch(e,t),i=(e,t,n,r,i)=>{this.record(e.method,e.url,t,n,r,e.span,e.routingContextId,i)},a=r.t(globalThis,`fetch`,r=>{let a=r.bind(globalThis);return async function(r,o){let s=t?n(r,o):void 0;if(!s)return a(r,o);let c=performance.now();try{let t=await a(s.input,s.init);return i(s,t.status,performance.now()-c,void 0,()=>t.headers.get(e.Dn)),t}catch(e){throw i(s,0,performance.now()-c,e),e}}});this.restores.push(()=>{t=!1,a()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=p(e);if(!this.ignored(n))return{method:m(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t,routingContextId:this.ctx.config.securityContext.id};if(!n.propagate||h(e))return a;try{let n=this.ctx.tracing.request(),r=Object.entries(n.headers);if(e instanceof Request){let t=new Headers(e.headers);for(let[e,n]of r)t.set(e,n);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,n]of r)e.set(t,n);a.init={...t,headers:e}}a.span=n.span}catch(n){a.input=e,a.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n,r)=>{this.record(e.method,e.url,t,n,void 0,e.span,e.routingContextId,r)},o=f(),c=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:g(r),url:p(i),startedAt:0}}),n.apply(this,[r,i,...a])}),l=r.t(o,`send`,r=>function(...o){let c=e?this.__uiobs:void 0;c&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${c.method} ${c.url}.`,()=>{n(c.url)||(c.startedAt=performance.now(),c.routingContextId=t.config.securityContext.id,this.addEventListener(`loadend`,()=>{a(c,this.status,performance.now()-c.startedAt,()=>s(this.getAllResponseHeaders()))},{once:!0}),i(c.url)&&(c.span=v(this,c.url,t)))}),r.apply(this,o)});this.restores.push(()=>{e=!1,c(),l()})}record(e,t,r,a,o,s,f,p){if(this.ctx.isActive?.()===!1||this.ctx.config.securityContext.isolation&&f!==void 0&&f!==this.ctx.config.securityContext.id)return;let m=this.ctx.config.capture.serverTiming&&p?this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the Server-Timing response header.`,()=>c(p())):void 0,h=i.i(t,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics);!this.warnedTransport&&n.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${h} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${h}.`,()=>{let n=d(e,t,r,o);this.ctx.recordMetric(u,a/l,n)}),s&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the span of ${e} ${h}.`,()=>{let n=Date.now();this.ctx.recordSpan({...s,link:m?.link,name:e,kind:`client`,startMs:n-a,endMs:n,error:r===0||r>=400,attributes:{...d(e,t,r,o),"url.full":h}})}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${h}.`,()=>{let t=Math.round(a);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${h} ${r===0?`failed`:String(r)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":h,"http.response.status_code":r,"http.duration_ms":t,...m&&m.entries.length>0?{"server.timing":m.entries}:{}};r===0?this.ctx.logger.error(`${e} ${h} failed`,o,n):r>=400?this.ctx.logger.warn(`${e} ${h} returned ${String(r)}`,n):this.ctx.logger.debug(`${e} ${h}`,n)})}};function v(e,t,n){try{let t=n.tracing.request();for(let[n,r]of Object.entries(t.headers))e.setRequestHeader(n,r);return t.span}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e);return}}exports.NetworkCapture=_;
2
- //# sourceMappingURL=network-pEX3PAJv.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-pEX3PAJv.cjs","names":["SERVER_TIMING_MAX_CHARS","isErrorLike","isLibraryRequest","matchesAny","patch","SERVER_TIMING_HEADER","recordedUrl","isTransportPending","require_constants","require_error_like","require_library_request","require_patch","require_platform","require_types","splitHeader","parts","start","quoted","escaped","i","text","char","separator","xhrServerTiming","headers","readServerTiming","result","header","part","rawName","params","name","entry","seen","param","equal","key","value","duration","match","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","readTiming","call","original","startedAt","response","read","trace","injected","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","timing","span","endMs","rounded","xhr"],"sources":["../src/capture/server-timing.ts","../src/capture/network.ts"],"sourcesContent":["import { SERVER_TIMING_MAX_CHARS, SERVER_TIMING_MAX_ENTRIES } from \"../constants\";\n\n/** One duration entry from the Server-Timing response header. */\ninterface ServerTimingEntry {\n name: string;\n duration: number;\n description: string;\n}\n\n/** Server duration entries, plus the server span they name. */\nexport interface ServerTiming {\n entries: ServerTimingEntry[];\n link?: { traceId: string; spanId: string };\n}\n\n/** Splits a header on separators outside quoted strings. An escaped quote doesn't end a string. */\nfunction splitHeader(text: string, separator: string): string[] {\n const parts: string[] = [];\n let start = 0;\n let quoted = false;\n let escaped = false;\n\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (escaped) {\n escaped = false;\n } else if (quoted && char === \"\\\\\") {\n escaped = true;\n } else if (char === '\"') {\n quoted = !quoted;\n } else if (!quoted && char === separator) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n }\n\n parts.push(text.slice(start));\n return parts;\n}\n\n/** Finds the header in an XHR header list. Reading a hidden header directly logs a Chrome error. */\nexport function xhrServerTiming(headers: string): string | null {\n return /^server-timing:(.*)$/im.exec(headers)?.[1] ?? null;\n}\n\n/** Reads a bounded number of server duration entries. A missing header gives none. */\nexport function readServerTiming(header: string | null): ServerTiming {\n const result: ServerTiming = { entries: [] };\n if (!header) {\n return result;\n }\n\n for (const part of splitHeader(header.slice(0, SERVER_TIMING_MAX_CHARS), \",\").slice(\n 0,\n SERVER_TIMING_MAX_ENTRIES,\n )) {\n const [rawName, ...params] = splitHeader(part, \";\");\n const name = rawName.trim();\n if (!/^[!#$%&'*+.^_`|~\\da-z-]+$/i.test(name)) {\n continue;\n }\n\n const entry: ServerTimingEntry = { name, duration: 0, description: \"\" };\n const seen = new Set<string>();\n for (const param of params) {\n const equal = param.indexOf(\"=\");\n if (equal < 0) {\n continue;\n }\n\n const key = param.slice(0, equal).trim().toLowerCase();\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n\n let value = param.slice(equal + 1).trim();\n if (value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1).replace(/\\\\(.)/g, \"$1\");\n }\n\n if (key === \"dur\") {\n const duration = Number(value);\n if (Number.isFinite(duration) && duration >= 0) {\n entry.duration = duration;\n }\n } else if (key === \"desc\") {\n entry.description = value;\n }\n }\n\n result.entries.push(entry);\n if (name.toLowerCase() === \"traceparent\") {\n const match = /^00-([\\da-f]{32})-([\\da-f]{16})-[\\da-f]{2}$/.exec(entry.description);\n if (match && /[1-9a-f]/.test(match[1]) && /[1-9a-f]/.test(match[2])) {\n result.link = { traceId: match[1], spanId: match[2] };\n }\n }\n }\n\n return result;\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record the outcome and timing of network requests.\n\nimport { SERVER_TIMING_HEADER } from \"../constants\";\nimport { readServerTiming, xhrServerTiming } from \"./server-timing\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as its OpenTelemetry name says. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram from the OpenTelemetry semantic conventions, with the\n * boundaries the conventions recommend.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Builds the low-cardinality attributes for one request. The path and the query stay out,\n * because every distinct attribute value creates a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error What failed, for a request with no response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request with no response takes its error's type, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** The delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** The client span the traceparent names. */\n span?: ClientSpan;\n}\n\n/** An XMLHttpRequest with our tracking metadata attached. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** The XMLHttpRequest prototype methods we wrap, kept unbound. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** The delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** The client span the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL from a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`, but its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts anything with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init's method wins over the Request's.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. Defaults to GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Checks whether a fetch input is an object that isn't a Request or a URL from this realm,\n * for example a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. Never throws on a method that isn't a string.\n * @param method The caller's method argument.\n * @returns The uppercase method for a string, or the text form of anything else.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Guards against wrapping a function twice. */\n private installed = false;\n\n /** Restore functions for the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True once we've reported a request made during a custom transport call. Reported once. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger, breadcrumbs and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments the network APIs the configuration selects. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores every host function that still holds this capture's wrapper.\n * 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 for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Checks whether a URL matches the ignore patterns.\n * @param url Request target URL.\n * @returns True if the URL must stay out of the telemetry.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Otherwise a failed POST becomes a\n // log record, the record causes a new POST, and the loop never stops.\n // A custom transport has no known URL, but its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Checks whether a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Only add headers to allowlisted URLs. A traceparent on a third-party request triggers\n // a CORS preflight that the third party doesn't answer, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Wraps globalThis.fetch to inject the trace headers and log the outcome. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n plan: FetchPlan,\n status: number,\n durationMs: number,\n error: unknown,\n readTiming?: () => string | null,\n ): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n readTiming,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined, () =>\n response.headers.get(SERVER_TIMING_HEADER),\n );\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input The caller's fetch input.\n * @param init The caller's fetch init.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // This read runs inside the caller's fetch call, so a throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces every header on a foreign Request, Authorization\n // included. So a foreign input goes out without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Don't spread a non-empty init next to a Request input. That runs the Request\n // constructor on `input` again and reads its body, and reading a body twice\n // throws a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Only record the client span for a request that actually carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send exactly what the caller gave us. A missing header is better than a failed\n // request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Wraps the open and send methods on the XMLHttpRequest prototype. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag, so a wrapper that stays in place only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (\n meta: XhrMeta,\n status: number,\n durationMs: number,\n readTiming: () => string | null,\n ): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n readTiming,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // This read runs inside the caller's open call, so a throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener on every send, so the old one must not\n // fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt, () =>\n xhrServerTiming(this.getAllResponseHeaders()),\n );\n },\n { once: true },\n );\n\n // setRequestHeader only works between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records the outcome of a request as attributes and a breadcrumb.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The query is removed here unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error The caught error, for a failed request.\n * @param span The client span the request's traceparent names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n readTiming?: () => string | null,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n ) {\n return;\n }\n\n const timing =\n this.ctx.config.capture.serverTiming && readTiming\n ? this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the Server-Timing response header.\",\n () => readServerTiming(readTiming()),\n )\n : undefined;\n\n // Strip the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL, and only the recorded URL loses its query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A transport request made after an await gets recorded, and that record causes the next\n // send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard, so a URL that doesn't parse can't stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n link: timing?.link,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This runs inside the caller's fetch call, so an error here must not fail the caller's\n // request.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n ...(timing && timing.entries.length > 0 ? { \"server.timing\": timing.entries } : {}),\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG, which the default minLevel of INFO drops. That way only\n // failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. If that fails, the request goes out without them.\n * @param xhr A request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":"A,wOAgBA,SAASc,EAAY,EAAc,EAA6B,CAC9D,IAAMC,EAAkB,CAAC,EACrBC,EAAQ,EACRC,EAAS,GACTC,EAAU,GAEd,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,IAAK,CACpC,IAAMC,EAAOD,EAAKD,GACdD,EACF,EAAU,GACDD,GAAUI,IAAS,KAC5B,EAAU,GACDA,IAAS,IAClB,EAAS,CAACJ,EACD,CAACA,GAAUI,IAASC,IAC7BP,EAAM,KAAKK,EAAK,MAAMJ,EAAOG,CAAC,CAAC,EAC/B,EAAQA,EAAI,EAEhB,CAGA,OADAJ,EAAM,KAAKK,EAAK,MAAMJ,CAAK,CAAC,EACrBD,CACT,CAGA,SAAgBQ,EAAgB,EAAgC,CAC9D,MAAO,yBAAyB,KAAKC,CAAO,CAAC,GAAG,IAAM,IACxD,CAGA,SAAgBC,EAAiB,EAAqC,CACpE,IAAMC,EAAuB,CAAE,QAAS,CAAC,CAAE,EAC3C,GAAI,CAACC,EACH,OAAOD,EAGT,IAAK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,EAClC,IAAK,GAAM,CAACtB,EAAKC,KAAU,OAAO,QAAQqC,EAAM,OAAO,EACrDkB,EAAI,iBAAiBxD,EAAKC,CAAK,EAEjC,OAAOqC,EAAM,IACf,OAAS1B,EAAO,CACdU,EAAI,YAAY,OACd,wBACA,oFACA,CAAE,KAAI,EACNV,CACF,EACA,MACF,CACF,C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiler-BVWIOgnq.js","names":["TELEMETRY_SDK_VERSION","PROFILER_PROBE_LIMIT","PROFILE_KEYS","METRIC_KEYS","PROFILER_CALIBRATION_PAIRS","PROFILER_GLOBAL_KEY","PROFILE_METRIC_NAME","PROFILE_MAX_US","unrefTimer","SUB_COUNT","SUB_MASK","bucketOf","value","us","shift","upperOf","index","percentileOf","rank","q","count","sum","i","buckets","base","pointBuckets","first","last","merge","low","high","counts","k","STATS_WIDTH","COUNT","SUM","MIN","MAX","SAMPLING_WIDTH","MAX_PERIOD","FRAME_WIDTH","SPAN_WIDTH","CORE_KEY","NOOP_PROBE","ProfilerCore","name","diagnostics","known","rules","options","slot","entry","period","probe","token","waits","result","fn","then","done","error","minMs","names","found","at","ring","to","from","limit","sink","timed","start","threshold","loose","put","ms","settle","now","leave","end","self","durationMs","child","stack","ringAt","frame","page","drain","waiting","left","row","stats","min","max","quantile","hist","attributes","selfCount","selfHist","fields","bounds","edge","reads","until","tick","pairsAtTick","pairs","profilerCore","store","pinned","core"],"sources":["../src/core/profile-buckets.ts","../src/core/profiler.ts"],"sourcesContent":["// src/core/profile-buckets.ts\n//\n// Maps a duration in microseconds to a bucket of the profiler's log-linear histogram. Also\n// reads percentiles and builds the explicit bounds for a summary record.\n\nimport {\n PROFILE_BUCKETS,\n PROFILE_MAX_US,\n PROFILE_POINT_BUCKETS,\n PROFILE_SUB_BITS,\n} from \"../constants\";\n\n/** Sub-buckets per power of two. Values below this each get a bucket of their own. */\nconst SUB_COUNT = 1 << PROFILE_SUB_BITS;\n\n/** Masks the sub-bucket bits of a bucket index. */\nconst SUB_MASK = SUB_COUNT - 1;\n\n/**\n * Returns the bucket for a duration. Runs on the hot path, once per value.\n * @param us Duration in microseconds, a non-negative integer.\n * @returns The bucket index, 0 to 367. Anything above PROFILE_MAX_US lands in 367.\n */\nexport function bucketOf(us: number): number {\n // Clamp before the bit math: Math.clz32 and >>> only look at 32 bits, so a value of 2^32 or\n // more would land in the wrong bucket.\n const value = Math.min(us, PROFILE_MAX_US);\n\n if (value < SUB_COUNT) {\n return value;\n }\n\n // Math.clz32 gives us the exponent without a loop (up to 26 steps) or float math.\n // `shift` is how many low bits sit below the sub-bucket bits.\n const shift = 31 - Math.clz32(value) - PROFILE_SUB_BITS;\n return ((shift + 1) << PROFILE_SUB_BITS) | ((value >>> shift) & SUB_MASK);\n}\n\n/**\n * Returns the largest duration that still falls into a bucket.\n * @param index Bucket index, 0 to 367.\n * @returns The inclusive upper bound, in microseconds.\n */\nexport function upperOf(index: number): number {\n if (index < SUB_COUNT) {\n return index;\n }\n\n // Set all the low bits bucketOf dropped. Without them we'd return the bucket's smallest value.\n const shift = (index >>> PROFILE_SUB_BITS) - 1;\n return ((SUB_COUNT + (index & SUB_MASK)) << shift) + (1 << shift) - 1;\n}\n\n/**\n * Reads a percentile from one probe's histogram. Allocates nothing.\n * @param buckets Bucket counts for all probes.\n * @param base Index of the probe's first bucket.\n * @param count Sum of the probe's buckets. Must be above 0.\n * @param q Percentile as a fraction, e.g. 0.99.\n * @returns The upper bound of the bucket that holds the rank, in microseconds.\n */\nexport function percentileOf(buckets: Uint32Array, base: number, count: number, q: number): number {\n // A rank of 0 would match the first bucket even when it is empty.\n const rank = Math.max(1, Math.ceil(q * count));\n let sum = 0;\n\n // Walk the counts in place. Copying or sorting would make garbage on every flush.\n for (let i = 0; i < PROFILE_BUCKETS; i++) {\n sum += buckets[base + i];\n\n if (sum >= rank) {\n return upperOf(i);\n }\n }\n\n // Only reachable if the caller passed a wrong count.\n return upperOf(PROFILE_BUCKETS - 1);\n}\n\n/**\n * Builds the explicit-bounds histogram for a summary record.\n * @param buckets Bucket counts for all probes.\n * @param base Index of the probe's first bucket.\n * @returns Bounds in ms and the count per group. There is one more count than there are bounds.\n */\nexport function pointBuckets(\n buckets: Uint32Array,\n base: number,\n): { bounds: number[]; counts: number[] } {\n let first = 0;\n while (first < PROFILE_BUCKETS && buckets[base + first] === 0) {\n first++;\n }\n\n if (first === PROFILE_BUCKETS) {\n return { bounds: [], counts: [0] };\n }\n\n // The bucket at `first` isn't empty, so this loop stops there at the latest.\n let last = PROFILE_BUCKETS - 1;\n while (buckets[base + last] === 0) {\n last--;\n }\n\n // Groups start at multiples of 2^merge. That puts every bound on a fixed grid for the merge\n // level, whatever the record's first bucket happens to be.\n let merge = 0;\n while ((last >> merge) - (first >> merge) + 1 > PROFILE_POINT_BUCKETS) {\n merge++;\n }\n\n const low = first >> merge;\n const high = last >> merge;\n\n // Plain arrays, because the OTLP metrics serializer drops typed arrays.\n const counts = Array.from({ length: high - low + 1 }, () => 0);\n for (let i = first; i <= last; i++) {\n counts[(i >> merge) - low] += buckets[base + i];\n }\n\n // A group's bound is the bound of its last bucket. Dividing by 1000 gives ms.\n const bounds = Array.from(\n { length: high - low },\n (_unused, k) => upperOf(((low + k + 1) << merge) - 1) / 1000,\n );\n\n return { bounds, counts };\n}\n","// src/core/profiler.ts\n//\n// Times spans of app code with probes. Durations accumulate in typed arrays, and once per\n// interval every probe that saw data is flushed as one histogram summary record.\n\nimport {\n METRIC_KEYS,\n PROFILE_BUCKETS,\n PROFILE_KEYS,\n PROFILE_METRIC_NAME,\n PROFILER_CALIBRATION_MS,\n PROFILER_CALIBRATION_PAIRS,\n PROFILER_GLOBAL_KEY,\n PROFILER_PROBE_LIMIT,\n PROFILER_RING_SPANS,\n PROFILER_STACK_DEPTH,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { MetricAttributes, Probe, ProbeOptions, Profiler } from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { bucketOf, percentileOf, pointBuckets } from \"./profile-buckets\";\n\n/** One stats row is [count, sum, min, max]. Sum, min and max are in ms. */\nconst STATS_WIDTH = 4;\nconst COUNT = 0;\nconst SUM = 1;\nconst MIN = 2;\nconst MAX = 3;\n\n/** One sampling row is [countdown, period]. */\nconst SAMPLING_WIDTH = 2;\n\n/** The period lives in an Int32Array, so this is as large as it gets. */\nconst MAX_PERIOD = 2 ** 31 - 1;\n\n/** One span-stack frame is [start, child time, slot]. */\nconst FRAME_WIDTH = 3;\n\n/** One entry in the recent-span ring is [slot, start, end]. */\nconst SPAN_WIDTH = 3;\n\n/** Global key for the core, one per library version. */\nconst CORE_KEY = Symbol.for(`${PROFILER_GLOBAL_KEY}@${TELEMETRY_SDK_VERSION}`);\n\n/** Handed out for names we reject. Never reads the clock. */\nconst NOOP_PROBE: Probe = {\n begin: () => -1,\n end: () => undefined,\n endAfterPaint: () => undefined,\n record: () => undefined,\n};\n\n/** Ends a span that was waiting on a paint or a promise. */\ntype Settle = (token: number, now: number) => void;\n\n/** The page globals the paint wait needs. Workers and Node.js have none of them. */\ninterface PaintScope {\n requestAnimationFrame?: (callback: () => void) => unknown;\n document?: {\n /** \"hidden\" while the page isn't painting. */\n visibilityState?: string;\n addEventListener: (type: string, listener: () => void) => void;\n };\n}\n\n/** What the runtime hands the core on attach. */\nexport interface ProfilerSink {\n /** Max number of probes (profiler.maxProbes). */\n capacity: number;\n /** Interval length in ms. */\n intervalMs(): number;\n /**\n * Builds and sends the record for one point.\n * @param name Metric name.\n * @param attributes Record attributes for the point.\n * @param fields Metric fields for the point.\n */\n emit(name: string, attributes: MetricAttributes, fields: Record<string, unknown>): void;\n /** The runtime's diagnostics reporter. */\n diagnostics: Diagnostics;\n /** False while the runtime can't accept records. */\n ready(): boolean;\n /**\n * Leaves a breadcrumb for a span that ran longer than its probe's threshold.\n * @param name Probe name.\n * @param ms Span duration in ms.\n */\n outlier(name: string, ms: number): void;\n}\n\n/** Probe options after validation. */\ninterface ProbeRules {\n /** Measure one span in every `period`. */\n period: number;\n /** Spans longer than this (ms) leave a breadcrumb. Infinity means never. */\n threshold: number;\n /** True for async probes, whose spans stay off the span stack. */\n loose: boolean;\n}\n\n/** A registered probe. */\ninterface ProbeEntry {\n /** The handle. Every probe() call with the same name returns this one. */\n probe: Probe;\n /** The probe's row in the typed arrays: registration index + 1. */\n slot: number;\n /** Sampling period, from the options passed the first time the name was seen. */\n period: number;\n /** Ends one of this probe's spans that isn't on the span stack. */\n settle: Settle;\n /** Pops a span off the stack without ending it. It ends later. */\n leave: (token: number) => void;\n}\n\n/** Holds the probe names and all their timings. There is one core per library version. */\nexport class ProfilerCore implements Profiler {\n /** Probes by name. Names are never removed, so insertion order is slot order. */\n private readonly registry = new Map<string, ProbeEntry>();\n\n /** Rows in use. 0 while detached, so one compare covers both \"off\" and \"over the limit\". */\n private limit = 0;\n\n // The typed arrays start empty rather than null. Hypothesis (not measured): a single field\n // type keeps V8's inline caches on the hot path monomorphic.\n\n /**\n * Count, sum, min and max per slot. A row's four values sit in 32 adjacent bytes, so an add\n * should touch a single cache line (hypothesis, not measured).\n */\n private stats = new Float64Array(0);\n\n /** Bucket counts, PROFILE_BUCKETS per slot. */\n private hist = new Uint32Array(0);\n\n /** Self-time bucket counts per slot. Spans without a stack frame don't add to it. */\n private selfHist = new Uint32Array(0);\n\n /** Frames for the open, nested spans. Each frame adds up the time of the spans inside it. */\n private readonly stack = new Float64Array(PROFILER_STACK_DEPTH * FRAME_WIDTH);\n\n /** Number of frames in use. */\n private depth = 0;\n\n /** Recent spans, for linking to long animation frames. Empty until link() turns it on. */\n private ring = new Float64Array(0);\n\n /** Next write offset in the ring. */\n private ringAt = 0;\n\n /** Shortest span (ms) that goes into the ring. Infinity keeps the ring off. */\n private linkMs = Infinity;\n\n /** Spans waiting for the next paint. */\n private painted: ((now: number) => void)[] = [];\n\n /** Gets us a task right after the paint. Created on the first wait. */\n private channel: MessageChannel | undefined;\n\n /** Countdown and period per slot. */\n private sampling = new Int32Array(0);\n\n /**\n * Clock value at the last detach() or reset(). Spans that started at or before it are dropped.\n * \"At\" matters: on a coarse clock, a span started in the reset's tick reads the same value.\n */\n private floor = -1;\n\n /** Timer for the current interval. It only runs while there is data waiting. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** When the interval's first value arrived, in epoch ms. */\n private startedAt = 0;\n\n /** Invalid tokens seen while on, since the last collect(). end() itself reports nothing. */\n private badTokens = 0;\n\n /** Cost of one sampled begin()/end() pair, in ns. */\n private overhead: number | undefined = undefined;\n\n /** Set once calibration has run, so a too-coarse clock only blocks us once. */\n private calibrated = false;\n\n /** The runtime's sink. Null while detached. */\n private sink: ProfilerSink | null = null;\n\n /** True once this attach has reported a probe over the limit. */\n private reported = false;\n\n /** True while a limit report the throttle dropped is waiting for the next collect. */\n private limitDue = false;\n\n /**\n * Returns the probe for a name. Never throws into the app.\n * @param name Probe name. A JavaScript caller can pass anything.\n * @param options Probe options. Only the options from the first call for a name count.\n * @param diagnostics The current runtime's diagnostics. Without a runtime, nothing is reported.\n * @returns The probe, or a no-op probe if the name is rejected.\n */\n probe(name: string, options?: ProbeOptions, diagnostics?: Diagnostics): Probe {\n // Only look at the type. String(name) would run a hostile toString().\n if (typeof name !== \"string\" || name === \"\") {\n diagnostics?.report(\n \"config.invalid\",\n \"The probe name must be a string that is not empty. The probe does nothing.\",\n );\n return NOOP_PROBE;\n }\n\n const known = this.registry.get(name);\n if (known) {\n return known.probe;\n }\n\n if (this.registry.size >= PROFILER_PROBE_LIMIT) {\n diagnostics?.report(\n \"config.invalid\",\n `The profiler keeps at most ${String(PROFILER_PROBE_LIMIT)} probe names. The probe ${name} does nothing.`,\n );\n return NOOP_PROBE;\n }\n\n const rules = this.rulesOf(name, options, diagnostics);\n const { period } = rules;\n\n // An options getter can register probes behind our back. Re-check, or two names share a slot.\n if (this.registry.has(name) || this.registry.size >= PROFILER_PROBE_LIMIT) {\n return this.probe(name, undefined, diagnostics);\n }\n\n const slot = this.registry.size + 1;\n const entry = this.makeProbe(name, slot, rules);\n const { probe } = entry;\n this.registry.set(name, entry);\n\n if (slot < this.limit) {\n this.prime(slot, period);\n } else if (this.limit > 0 && !this.reported) {\n this.reported = true;\n // The limit belongs to the attached runtime, so report through it even when the caller\n // passed no diagnostics.\n const sent = this.sink?.diagnostics.report(\n \"config.invalid\",\n `The probe ${name} is above the profiler.maxProbes limit of ${String(this.limit - 1)}. The probe does nothing.`,\n );\n\n if (sent === false) {\n this.limitDue = true;\n }\n }\n\n return probe;\n }\n\n /**\n * Calls a function and times it. If the result is a thenable, the span ends when it settles.\n * The caller only ever sees errors from its own function.\n * @param name Probe name.\n * @param fn The app's function.\n * @param diagnostics The current runtime's diagnostics, if there is one.\n * @returns Whatever fn returned, or the result of its then() call.\n */\n time<T>(name: string, fn: () => T, diagnostics?: Diagnostics): T {\n this.probe(name, undefined, diagnostics);\n\n // A rejected name has no entry. Just run the function without a span.\n const entry = this.registry.get(name);\n const token = entry ? entry.probe.begin() : -1;\n let waits = false;\n\n try {\n const result = fn();\n\n if (entry && token >= 0) {\n try {\n const then = (result as { then?: unknown } | null | undefined)?.then;\n\n if (typeof then === \"function\") {\n const done = (): void => {\n entry.settle(token, performance.now());\n };\n\n waits = true;\n entry.leave(token);\n\n // Hand back the chained result, so a rejection has exactly one owner: the caller.\n return (then as PromiseLike<unknown>[\"then\"]).call(\n result,\n (value) => {\n done();\n return value;\n },\n (error: unknown) => {\n done();\n throw error;\n },\n ) as T;\n }\n } catch (error) {\n waits = false;\n diagnostics?.report(\n \"capture.record_failed\",\n `The library could not read what the function of the probe ${name} returned. The span ends now.`,\n undefined,\n error,\n );\n }\n }\n\n return result;\n } finally {\n if (!waits) {\n entry?.probe.end(token);\n }\n }\n }\n\n /**\n * Turns the recent-span ring on or off. The frame phases capture reads from it.\n * @param minMs Shortest span (ms) to keep. Infinity turns the ring off.\n */\n link(minMs: number): void {\n this.linkMs = minMs;\n\n if (minMs < Infinity && this.ring.length === 0) {\n this.ring = new Float64Array(PROFILER_RING_SPANS * SPAN_WIDTH);\n }\n }\n\n /**\n * Finds the probes that had a recent span inside a time range.\n * @param from Range start, as a performance.now() value.\n * @param to Range end.\n * @returns The probe names, without duplicates.\n */\n linked(from: number, to: number): string[] {\n const { ring } = this;\n const names = [...this.registry.keys()];\n const found = new Set<string>();\n\n for (let at = 0; at < ring.length; at += SPAN_WIDTH) {\n // Slot 0 means an empty row or a calibration span.\n if (ring[at] > 0 && ring[at + 1] < to && ring[at + 2] > from) {\n found.add(names[ring[at] - 1]);\n }\n }\n\n return [...found];\n }\n\n /**\n * Turns the profiler on with a runtime's sink. Calling it again swaps the sink.\n * @param sink The runtime's sink.\n */\n attach(sink: ProfilerSink): void {\n const limit = sink.capacity + 1;\n this.sink = sink;\n\n // Re-attaching with the same capacity keeps the data.\n if (this.stats.length !== limit * STATS_WIDTH) {\n this.stats = new Float64Array(limit * STATS_WIDTH);\n this.hist = new Uint32Array(limit * PROFILE_BUCKETS);\n this.selfHist = new Uint32Array(limit * PROFILE_BUCKETS);\n this.sampling = new Int32Array(limit * SAMPLING_WIDTH);\n }\n\n this.limit = limit;\n this.reported = false;\n this.limitDue = false;\n this.prime(0, 1);\n for (const entry of this.registry.values()) {\n if (entry.slot < limit) {\n this.prime(entry.slot, entry.period);\n }\n }\n\n if (this.registry.size > sink.capacity) {\n this.reported = true;\n this.reportLimit(sink);\n }\n }\n\n /** Turns the profiler off and drops the data. The runtime calls collect(false) first. */\n detach(): void {\n this.limit = 0;\n this.sink = null;\n this.clearTimer();\n this.clear();\n }\n\n /**\n * Sends one summary record per probe that has data, then starts a new interval. Does nothing\n * while the sink isn't ready.\n * @param timed True when called from the interval timer. Only a timed collect calibrates.\n */\n collect(timed: boolean): void {\n const { sink } = this;\n\n // A runtime that isn't ready would refuse the records, so keep the data and the timer for a\n // later collect. Zeroing the slots here would lose those points.\n if (!sink?.ready()) {\n return;\n }\n\n // The diagnostics throttle swallowed this attach's limit report. Try again, otherwise the\n // app never hears that some of its probes do nothing.\n if (this.limitDue) {\n this.reportLimit(sink);\n }\n\n this.clearTimer();\n\n // Calibration blocks the thread for 2-3 ms (longer on a too-coarse clock), so flush() and\n // the exit path skip it.\n if (timed && !this.calibrated && this.hasData()) {\n this.calibrate();\n }\n\n const start = `${String(this.startedAt)}000000`;\n for (const [name, entry] of this.registry) {\n // Probes over the limit have no row. After a detach() from inside an emit, none do.\n if (entry.slot < this.limit && this.stats[entry.slot * STATS_WIDTH + COUNT] > 0) {\n this.emitSlot(sink, name, entry, start);\n }\n }\n\n if (this.badTokens > 0) {\n sink.diagnostics.count(\"record.dropped_malformed\", this.badTokens);\n this.badTokens = 0;\n }\n }\n\n /** Drops the interval's data. The profiler stays on. */\n reset(): void {\n this.clearTimer();\n this.badTokens = 0;\n this.clear();\n }\n\n /** Drops the data and any open spans. Spans started at or before this call add nothing. */\n private clear(): void {\n this.floor = performance.now();\n this.depth = 0;\n this.stats.fill(0);\n this.hist.fill(0);\n this.selfHist.fill(0);\n this.ring.fill(0);\n }\n\n /**\n * Reads the options for a new probe. Never throws into the app.\n * @param name Probe name.\n * @param options Options from the app.\n * @param diagnostics The current runtime's diagnostics, if there is one.\n * @returns The rules. Any invalid option falls back to its default.\n */\n private rulesOf(\n name: string,\n options: ProbeOptions | undefined,\n diagnostics: Diagnostics | undefined,\n ): ProbeRules {\n const rules: ProbeRules = { period: 1, threshold: Infinity, loose: false };\n let period: unknown;\n let threshold: unknown;\n let loose: unknown;\n\n // A getter or a Proxy trap on the options can throw.\n try {\n period = options?.sampleEvery;\n threshold = options?.slowMs;\n loose = options?.async;\n } catch (error) {\n diagnostics?.report(\n \"config.invalid\",\n `The library could not read the options of the probe ${name}. The library uses the defaults.`,\n undefined,\n error,\n );\n return rules;\n }\n\n if (\n typeof period === \"number\" &&\n Number.isInteger(period) &&\n period >= 1 &&\n period <= MAX_PERIOD\n ) {\n rules.period = period;\n } else if (period !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The sampleEvery option of the probe ${name} must be an integer from 1 to ${String(MAX_PERIOD)}. The library uses 1.`,\n );\n }\n\n if (typeof threshold === \"number\" && threshold >= 0 && threshold < Infinity) {\n rules.threshold = threshold;\n } else if (threshold !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The slowMs option of the probe ${name} must be a finite number, 0 or larger. The probe adds no breadcrumb.`,\n );\n }\n\n if (typeof loose === \"boolean\") {\n rules.loose = loose;\n } else if (loose !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The async option of the probe ${name} must be a boolean. The library uses false.`,\n );\n }\n\n return rules;\n }\n\n /**\n * Builds a probe's closures, once per probe, so destructured members still work.\n * @param name Probe name.\n * @param slot The probe's row.\n * @param rules Validated probe options.\n * @returns The registry entry, including the probe.\n */\n private makeProbe(name: string, slot: number, rules: ProbeRules): ProbeEntry {\n const { period, threshold, loose } = rules;\n\n // Records one duration, plus a breadcrumb if it is over the probe's threshold.\n const put = (ms: number): void => {\n this.add(slot, ms);\n\n if (ms > threshold) {\n this.sink?.outlier(name, ms);\n }\n };\n\n // Drop the span if we're off, or if it started at or before a detach() or reset().\n const settle: Settle = (token, now) => {\n if (slot < this.limit && token > this.floor) {\n put(now - token);\n }\n };\n\n const leave = (token: number): void => {\n if (!loose) {\n this.pop(slot, token, performance.now());\n }\n };\n\n const end = (token: number): void => {\n // Type check first, so the compare can never run a hostile valueOf().\n const now = typeof token === \"number\" && token >= 0 ? performance.now() : -1;\n if (now < 0) {\n // -1 means begin() didn't measure this span. Other bad tokens only count while we're on.\n if (token !== -1 && slot < this.limit) {\n this.badTokens++;\n }\n return;\n }\n\n if (loose) {\n settle(token, now);\n return;\n }\n\n // Drop the span if we're off, or if it started at or before a detach() or reset().\n if (slot >= this.limit || token <= this.floor) {\n return;\n }\n\n const self = this.pop(slot, token, now);\n put(now - token);\n\n // No frame means no self time: the frame was lost to a reset or to a full stack.\n if (self >= 0) {\n this.selfHist[slot * PROFILE_BUCKETS + bucketOf(Math.ceil(self * 1000))]++;\n }\n };\n\n const probe: Probe = {\n begin: () => {\n // Off, over the limit or sampled out: don't even read the clock.\n if (slot >= this.limit || !this.sampled(slot)) {\n return -1;\n }\n\n const now = performance.now();\n if (!loose) {\n this.push(slot, now);\n }\n\n return now;\n },\n end,\n endAfterPaint: (token) => {\n const waits =\n typeof token === \"number\" &&\n token >= 0 &&\n slot < this.limit &&\n this.afterPaint((now) => {\n settle(token, now);\n });\n\n // Bad token, probe off, or a page that isn't painting: end right away.\n if (!waits) {\n end(token);\n return;\n }\n\n leave(token);\n },\n record: (durationMs) => {\n if (slot >= this.limit) {\n return;\n }\n\n if (typeof durationMs !== \"number\" || !Number.isFinite(durationMs) || durationMs < 0) {\n this.sink?.diagnostics.report(\n \"record.dropped_malformed\",\n `The duration of the probe ${name} is not valid. The library dropped it.`,\n { [PROFILE_KEYS.probe]: name },\n );\n return;\n }\n\n if (this.sampled(slot)) {\n put(durationMs);\n }\n },\n };\n\n return { probe, slot, period, settle, leave };\n }\n\n /**\n * Pushes a frame for a new span.\n * @param slot The probe's row.\n * @param now Span start.\n */\n private push(slot: number, now: number): void {\n const { stack } = this;\n\n // A full stack is full of frames whose spans never got an end(). Drop them, or no later\n // span gets a self time.\n if (this.depth === PROFILER_STACK_DEPTH) {\n this.depth = 0;\n }\n\n const at = this.depth++ * FRAME_WIDTH;\n stack[at] = now;\n stack[at + 1] = 0;\n stack[at + 2] = slot;\n }\n\n /**\n * Pops a span's frame, along with any frames above it, and adds the span's duration to the\n * child time of the frame below.\n * @param slot The probe's row.\n * @param token Span start.\n * @param now Span end, or the time the span leaves the stack.\n * @returns Self time in ms, or -1 if the span had no frame.\n */\n private pop(slot: number, token: number, now: number): number {\n const { stack } = this;\n const ms = now - token;\n let child = 0;\n\n for (let at = (this.depth - 1) * FRAME_WIDTH; at >= 0; at -= FRAME_WIDTH) {\n // Any frame above ours is a span that never got an end(). Its child time is ours.\n child += stack[at + 1];\n\n if (stack[at] === token && stack[at + 2] === slot) {\n this.depth = at / FRAME_WIDTH;\n\n if (at > 0) {\n stack[at - FRAME_WIDTH + 1] += ms;\n }\n\n if (ms >= this.linkMs) {\n const { ring, ringAt } = this;\n ring[ringAt] = slot;\n ring[ringAt + 1] = token;\n ring[ringAt + 2] = now;\n this.ringAt = (ringAt + SPAN_WIDTH) % ring.length;\n }\n\n return Math.max(ms - child, 0);\n }\n }\n\n return -1;\n }\n\n /**\n * Runs a function in the first task after the next paint.\n * @param done Called with the time after the paint.\n * @returns False where there is no frame callback, or when the page is hidden.\n */\n private afterPaint(done: (now: number) => void): boolean {\n const { requestAnimationFrame: frame, document: page } = globalThis as PaintScope;\n\n if (\n typeof frame !== \"function\" ||\n typeof MessageChannel === \"undefined\" ||\n page?.visibilityState === \"hidden\"\n ) {\n return false;\n }\n\n if (!this.channel) {\n const drain = (): void => {\n const now = performance.now();\n const waiting = this.painted;\n this.painted = [];\n\n for (const end of waiting) {\n end(now);\n }\n };\n\n this.channel = new MessageChannel();\n this.channel.port1.onmessage = drain;\n\n // A hidden page gets no frame callbacks. End the spans now, or they include the hidden time.\n page?.addEventListener(\"visibilitychange\", () => {\n if (page.visibilityState === \"hidden\") {\n drain();\n }\n });\n }\n\n // rAF callbacks run before the paint. A task posted from one runs after it.\n if (this.painted.push(done) === 1) {\n frame(() => {\n this.channel?.port2.postMessage(0);\n });\n }\n\n return true;\n }\n\n /**\n * Writes a slot's sampling row so the next span gets measured.\n * @param slot The probe's row.\n * @param period Sampling period.\n */\n private prime(slot: number, period: number): void {\n const at = slot * SAMPLING_WIDTH;\n this.sampling[at] = 1;\n this.sampling[at + 1] = period;\n }\n\n /**\n * Counts down a slot's sampling. A countdown gives an exact rate, which Math.random() wouldn't.\n * @param slot The probe's row.\n * @returns True if this span should be measured.\n */\n private sampled(slot: number): boolean {\n const at = slot * SAMPLING_WIDTH;\n const left = this.sampling[at] - 1;\n\n if (left > 0) {\n this.sampling[at] = left;\n return false;\n }\n\n this.sampling[at] = this.sampling[at + 1];\n return true;\n }\n\n /**\n * Adds one duration to a slot. This is the hot path: no Map lookup, no try.\n * @param slot The probe's row.\n * @param ms Duration in ms.\n */\n private add(slot: number, ms: number): void {\n // A forged token gives a negative duration. A broken clock gives NaN or Infinity.\n if (!(ms >= 0) || ms === Infinity) {\n this.badTokens++;\n return;\n }\n\n const { stats } = this;\n const row = slot * STATS_WIDTH;\n const count = stats[row + COUNT];\n stats[row + COUNT] = count + 1;\n stats[row + SUM] += ms;\n\n if (count === 0 || ms < stats[row + MIN]) {\n stats[row + MIN] = ms;\n }\n\n if (count === 0 || ms > stats[row + MAX]) {\n stats[row + MAX] = ms;\n }\n\n // Buckets include their upper bound, so round up or the value lands one bucket too low.\n this.hist[slot * PROFILE_BUCKETS + bucketOf(Math.ceil(ms * 1000))]++;\n\n // Slot 0 is the calibration slot, and calibration must not start an interval.\n if (this.timer === null && slot > 0 && this.sink !== null) {\n this.startedAt = Date.now();\n this.wait(this.sink);\n }\n }\n\n /**\n * Starts the interval timer, unref'd so a pending timer doesn't keep Node.js alive.\n * @param sink The runtime's sink.\n */\n private wait(sink: ProfilerSink): void {\n this.timer = setTimeout(() => {\n this.tick();\n }, sink.intervalMs());\n unrefTimer(this.timer);\n }\n\n /** Collects at the end of an interval, or waits another one if the runtime isn't ready. */\n private tick(): void {\n const { sink } = this;\n\n if (sink !== null && !sink.ready()) {\n this.wait(sink);\n return;\n }\n\n this.collect(true);\n }\n\n /** Stops the interval timer. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Reports that there are more probes than the limit allows. If the throttle drops the report,\n * the next collect tries again.\n * @param sink The runtime's sink.\n */\n private reportLimit(sink: ProfilerSink): void {\n // Clear the flag first, so a handler that collects can't kick off a second report.\n this.limitDue = false;\n const sent = sink.diagnostics.report(\n \"config.invalid\",\n `The app registered ${String(this.registry.size)} probes. The profiler.maxProbes limit is ${String(sink.capacity)}. The probes above the limit do nothing.`,\n );\n\n if (!sent) {\n this.limitDue = true;\n }\n }\n\n /**\n * Checks whether any probe recorded a value in this interval.\n * @returns True if a slot above 0 has a non-zero count.\n */\n private hasData(): boolean {\n for (let slot = 1; slot < this.limit; slot++) {\n if (this.stats[slot * STATS_WIDTH + COUNT] > 0) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Sends one slot's summary record and zeroes the slot. The sampling countdown is left alone.\n * @param sink The runtime's sink.\n * @param name Probe name.\n * @param entry The probe's registry entry.\n * @param start Interval start, in Unix nanoseconds.\n */\n private emitSlot(sink: ProfilerSink, name: string, entry: ProbeEntry, start: string): void {\n const { stats, hist } = this;\n const row = entry.slot * STATS_WIDTH;\n const base = entry.slot * PROFILE_BUCKETS;\n const count = stats[row + COUNT];\n const min = stats[row + MIN];\n const max = stats[row + MAX];\n\n // A bucket bound can be higher than the exact max, so clamp every percentile to [min, max].\n const quantile = (q: number): number =>\n Math.min(Math.max(percentileOf(hist, base, count, q) / 1000, min), max);\n\n const attributes: MetricAttributes = {\n [PROFILE_KEYS.probe]: name,\n [PROFILE_KEYS.sampleEvery]: entry.period,\n [PROFILE_KEYS.p50]: quantile(0.5),\n [PROFILE_KEYS.p90]: quantile(0.9),\n [PROFILE_KEYS.p99]: quantile(0.99),\n };\n if (this.overhead !== undefined) {\n attributes[PROFILE_KEYS.overhead] = this.overhead;\n }\n\n // Count the self times here, at collect, so the hot path has no second counter to write.\n const { selfHist } = this;\n let selfCount = 0;\n for (let at = base; at < base + PROFILE_BUCKETS; at++) {\n selfCount += selfHist[at];\n }\n\n if (selfCount > 0) {\n attributes[PROFILE_KEYS.selfP99] = Math.min(\n percentileOf(selfHist, base, selfCount, 0.99) / 1000,\n max,\n );\n }\n\n const { bounds, counts } = pointBuckets(hist, base);\n const fields: Record<string, unknown> = {\n \"metric.name\": PROFILE_METRIC_NAME,\n \"metric.unit\": \"ms\",\n \"metric.type\": \"histogram\",\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: [PROFILE_KEYS.probe, PROFILE_KEYS.sampleEvery],\n [METRIC_KEYS.count]: count,\n [METRIC_KEYS.sum]: stats[row + SUM],\n [METRIC_KEYS.min]: min,\n [METRIC_KEYS.max]: max,\n [METRIC_KEYS.bounds]: bounds,\n [METRIC_KEYS.buckets]: counts,\n };\n\n // Zero before emitting: an app processor can call end() from inside the emit.\n stats.fill(0, row, row + STATS_WIDTH);\n hist.fill(0, base, base + PROFILE_BUCKETS);\n selfHist.fill(0, base, base + PROFILE_BUCKETS);\n sink.emit(PROFILE_METRIC_NAME, attributes, fields);\n }\n\n /**\n * Measures what one sampled begin()/end() pair costs, on slot 0. Runs once. If the clock never\n * shows an edge or never ticks, no value is set.\n */\n private calibrate(): void {\n this.calibrated = true;\n const { probe } = this.makeProbe(\"\", 0, { period: 1, threshold: Infinity, loose: false });\n\n // Browsers round performance.now() to 5 us, 100 us or 1 ms. Measure from clock edge to clock\n // edge: a window that isn't aligned to an edge can be off by up to one tick.\n const first = performance.now();\n let edge = first;\n for (let reads = 0; reads < PROFILER_CALIBRATION_PAIRS && edge === first; reads++) {\n edge = performance.now();\n }\n\n // No edge within the read limit, so the clock is frozen or too coarse. Without a start edge\n // the result would come out too large.\n if (edge === first) {\n return;\n }\n\n // begin()'s token is the clock reading, so the loop doesn't need a third clock read.\n const until = edge + PROFILER_CALIBRATION_MS;\n let tick = edge;\n let pairsAtTick = 0;\n for (let pairs = 0; pairs < PROFILER_CALIBRATION_PAIRS; pairs++) {\n const token = probe.begin();\n probe.end(token);\n\n if (token !== tick) {\n tick = token;\n pairsAtTick = pairs;\n\n if (token >= until) {\n break;\n }\n }\n }\n\n // Whole nanoseconds. Hypothesis: the noise in a single 2 ms run is more than 1 ns anyway.\n if (pairsAtTick > 0) {\n this.overhead = Math.round(((tick - edge) * 1e6) / pairsAtTick);\n }\n }\n}\n\n/**\n * Returns the profiler core for this library version. Two copies of the same version share it.\n * @returns The core.\n */\nexport function profilerCore(): ProfilerCore {\n // Each copy has its own class, so instanceof fails across copies. Cast structurally instead.\n const store = globalThis as Record<symbol, unknown>;\n const pinned = store[CORE_KEY] as ProfilerCore | undefined;\n if (pinned) {\n return pinned;\n }\n\n const core = new ProfilerCore();\n store[CORE_KEY] = core;\n return core;\n}\n"],"mappings":";;;AAaA,IAAMS,IAAY,IAGZC,IAAWD,IAAY;AAO7B,SAAgBE,EAAS,GAAoB;CAG3C,IAAMC,IAAQ,KAAK,IAAIC,GAAIN,CAAc;CAEzC,IAAIK,IAAQH,GACV,OAAOG;CAKT,IAAME,IAAQ,KAAK,KAAK,MAAMF,CAAK,IAAA;CACnC,OAASE,IAAQ,KAAA,IAA4BF,MAAUE,IAASJ;AAClE;AAOA,SAAgBK,EAAQ,GAAuB;CAC7C,IAAIC,IAAQP,GACV,OAAOO;CAIT,IAAMF,KAASE,MAAA,KAA8B;CAC7C,QAASP,KAAaO,IAAQN,MAAcI,MAAU,KAAKA,KAAS;AACtE;AAUA,SAAgBG,EAAa,GAAsB,GAAc,GAAe,GAAmB;CAEjG,IAAMC,IAAO,KAAK,IAAI,GAAG,KAAK,KAAKC,IAAIC,CAAK,CAAC,GACzCC,IAAM;CAGV,KAAK,IAAIC,IAAI,GAAGA,IAAA,KAAqB,KAGnC,IAFA,KAAOC,EAAQC,IAAOF,IAElBD,KAAOH,GACT,OAAOH,EAAQO,CAAC;CAKpB,OAAOP,EAAA,GAA2B;AACpC;AAQA,SAAgBU,EACd,GACA,GACwC;CACxC,IAAIC,IAAQ;CACZ,OAAOA,IAAA,OAA2BH,EAAQC,IAAOE,OAAW,IAC1D;CAGF,IAAIA,MAAA,KACF,OAAO;EAAE,QAAQ,CAAC;EAAG,QAAQ,CAAC,CAAC;CAAE;CAInC,IAAIC,IAAA;CACJ,OAAOJ,EAAQC,IAAOG,OAAU,IAC9B;CAKF,IAAIC,IAAQ;CACZ,QAAQD,KAAQC,MAAUF,KAASE,KAAS,IAAA,MAC1C;CAGF,IAAMC,IAAMH,KAASE,GACfE,IAAOH,KAAQC,GAGfG,I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;return a+1<<4|i>>>a&r}function a(e){if(e<n)return e;let t=(e>>>4)-1;return(n+(e&r)<<t)+(1<<t)-1}function o(e,t,n,r){let i=Math.max(1,Math.ceil(r*n)),o=0;for(let n=0;n<368;n++)if(o+=e[t+n],o>=i)return a(n);return a(367)}function s(e,t){let n=0;for(;n<368&&e[t+n]===0;)n++;if(n===368)return{bounds:[],counts:[0]};let r=367;for(;e[t+r]===0;)r--;let i=0;for(;(r>>i)-(n>>i)+1>100;)i++;let o=n>>i,s=r>>i,c=Array.from({length:s-o+1},()=>0);for(let a=n;a<=r;a++)c[(a>>i)-o]+=e[t+a];return{bounds:Array.from({length:s-o},(e,t)=>a((o+t+1<<i)-1)/1e3),counts:c}}var c=4,l=0,u=1,d=2,f=3,p=2,m=2**31-1,h=3,g=3,_=Symbol.for(`${e.Wt}@${e.Gn}`),v={begin:()=>-1,end:()=>void 0,endAfterPaint:()=>void 0,record:()=>void 0},y=class{registry=new Map;limit=0;stats=new Float64Array;hist=new Uint32Array;selfHist=new Uint32Array;stack=new Float64Array(32*h);depth=0;ring=new Float64Array;ringAt=0;linkMs=1/0;painted=[];channel;sampling=new Int32Array;floor=-1;timer=null;startedAt=0;badTokens=0;overhead=void 0;calibrated=!1;sink=null;reported=!1;limitDue=!1;probe(t,n,r){if(typeof t!=`string`||t===``)return r?.report(`config.invalid`,`The probe name must be a string that is not empty. The probe does nothing.`),v;let i=this.registry.get(t);if(i)return i.probe;if(this.registry.size>=1024)return r?.report(`config.invalid`,`The profiler keeps at most ${String(e.Gt)} probe names. The probe ${t} does nothing.`),v;let a=this.rulesOf(t,n,r),{period:o}=a;if(this.registry.has(t)||this.registry.size>=1024)return this.probe(t,void 0,r);let s=this.registry.size+1,c=this.makeProbe(t,s,a),{probe:l}=c;return this.registry.set(t,c),s<this.limit?this.prime(s,o):this.limit>0&&!this.reported&&(this.reported=!0,this.sink?.diagnostics.report(`config.invalid`,`The probe ${t} is above the profiler.maxProbes limit of ${String(this.limit-1)}. The probe does nothing.`)===!1&&(this.limitDue=!0)),l}time(e,t,n){this.probe(e,void 0,n);let r=this.registry.get(e),i=r?r.probe.begin():-1,a=!1;try{let o=t();if(r&&i>=0)try{let e=o?.then;if(typeof e==`function`){let t=()=>{r.settle(i,performance.now())};return a=!0,r.leave(i),e.call(o,e=>(t(),e),e=>{throw t(),e})}}catch(t){a=!1,n?.report(`capture.record_failed`,`The library could not read what the function of the probe ${e} returned. The span ends now.`,void 0,t)}return o}finally{a||r?.probe.end(i)}}link(e){this.linkMs=e,e<1/0&&this.ring.length===0&&(this.ring=new Float64Array(256*g))}linked(e,t){let{ring:n}=this,r=[...this.registry.keys()],i=new Set;for(let a=0;a<n.length;a+=g)n[a]>0&&n[a+1]<t&&n[a+2]>e&&i.add(r[n[a]-1]);return[...i]}attach(e){let t=e.capacity+1;this.sink=e,this.stats.length!==t*c&&(this.stats=new Float64Array(t*c),this.hist=new Uint32Array(t*368),this.selfHist=new Uint32Array(t*368),this.sampling=new Int32Array(t*p)),this.limit=t,this.reported=!1,this.limitDue=!1,this.prime(0,1);for(let e of this.registry.values())e.slot<t&&this.prime(e.slot,e.period);this.registry.size>e.capacity&&(this.reported=!0,this.reportLimit(e))}detach(){this.limit=0,this.sink=null,this.clearTimer(),this.clear()}collect(e){let{sink:t}=this;if(!t?.ready())return;this.limitDue&&this.reportLimit(t),this.clearTimer(),e&&!this.calibrated&&this.hasData()&&this.calibrate();let n=`${String(this.startedAt)}000000`;for(let[e,r]of this.registry)r.slot<this.limit&&this.stats[r.slot*c+l]>0&&this.emitSlot(t,e,r,n);this.badTokens>0&&(t.diagnostics.count(`record.dropped_malformed`,this.badTokens),this.badTokens=0)}reset(){this.clearTimer(),this.badTokens=0,this.clear()}clear(){this.floor=performance.now(),this.depth=0,this.stats.fill(0),this.hist.fill(0),this.selfHist.fill(0),this.ring.fill(0)}rulesOf(e,t,n){let r={period:1,threshold:1/0,loose:!1},i,a,o;try{i=t?.sampleEvery,a=t?.slowMs,o=t?.async}catch(t){return n?.report(`config.invalid`,`The library could not read the options of the probe ${e}. The library uses the defaults.`,void 0,t),r}return typeof i==`number`&&Number.isInteger(i)&&i>=1&&i<=m?r.period=i:i!==void 0&&n?.report(`config.invalid`,`The sampleEvery option of the probe ${e} must be an integer from 1 to ${String(m)}. The library uses 1.`),typeof a==`number`&&a>=0&&a<1/0?r.threshold=a:a!==void 0&&n?.report(`config.invalid`,`The slowMs option of the probe ${e} must be a finite number, 0 or larger. The probe adds no breadcrumb.`),typeof o==`boolean`?r.loose=o:o!==void 0&&n?.report(`config.invalid`,`The async option of the probe ${e} must be a boolean. The library uses false.`),r}makeProbe(t,n,r){let{period:a,threshold:o,loose:s}=r,c=e=>{this.add(n,e),e>o&&this.sink?.outlier(t,e)},l=(e,t)=>{n<this.limit&&e>this.floor&&c(t-e)},u=e=>{s||this.pop(n,e,performance.now())},d=e=>{let t=typeof e==`number`&&e>=0?performance.now():-1;if(t<0){e!==-1&&n<this.limit&&this.badTokens++;return}if(s){l(e,t);return}if(n>=this.limit||e<=this.floor)return;let r=this.pop(n,e,t);c(t-e),r>=0&&this.selfHist[n*368+i(Math.ceil(r*1e3))]++};return{probe:{begin:()=>{if(n>=this.limit||!this.sampled(n))return-1;let e=performance.now();return s||this.push(n,e),e},end:d,endAfterPaint:e=>{typeof e==`number`&&e>=0&&n<this.limit&&this.afterPaint(t=>{l(e,t)})?u(e):d(e)},record:r=>{n>=this.limit||(typeof r!=`number`||!Number.isFinite(r)||r<0?this.sink?.diagnostics.report(`record.dropped_malformed`,`The duration of the probe ${t} is not valid. The library dropped it.`,{[e.Jt.probe]:t}):this.sampled(n)&&c(r))}},slot:n,period:a,settle:l,leave:u}}push(e,t){let{stack:n}=this;this.depth===32&&(this.depth=0);let r=this.depth++*h;n[r]=t,n[r+1]=0,n[r+2]=e}pop(e,t,n){let{stack:r}=this,i=n-t,a=0;for(let o=(this.depth-1)*h;o>=0;o-=h)if(a+=r[o+1],r[o]===t&&r[o+2]===e){if(this.depth=o/h,o>0&&(r[o-h+1]+=i),i>=this.linkMs){let{ring:r,ringAt:i}=this;r[i]=e,r[i+1]=t,r[i+2]=n,this.ringAt=(i+g)%r.length}return Math.max(i-a,0)}return-1}afterPaint(e){let{requestAnimationFrame:t,document:n}=globalThis;if(typeof t!=`function`||typeof MessageChannel>`u`||n?.visibilityState===`hidden`)return!1;if(!this.channel){let e=()=>{let e=performance.now(),t=this.painted;this.painted=[];for(let n of t)n(e)};this.channel=new MessageChannel,this.channel.port1.onmessage=e,n?.addEventListener(`visibilitychange`,()=>{n.visibilityState===`hidden`&&e()})}return this.painted.push(e)===1&&t(()=>{this.channel?.port2.postMessage(0)}),!0}prime(e,t){let n=e*p;this.sampling[n]=1,this.sampling[n+1]=t}sampled(e){let t=e*p,n=this.sampling[t]-1;return n>0?(this.sampling[t]=n,!1):(this.sampling[t]=this.sampling[t+1],!0)}add(e,t){if(!(t>=0)||t===1/0){this.badTokens++;return}let{stats:n}=this,r=e*c,a=n[r+l];n[r+l]=a+1,n[r+u]+=t,(a===0||t<n[r+d])&&(n[r+d]=t),(a===0||t>n[r+f])&&(n[r+f]=t),this.hist[e*368+i(Math.ceil(t*1e3))]++,this.timer===null&&e>0&&this.sink!==null&&(this.startedAt=Date.now(),this.wait(this.sink))}wait(e){this.timer=setTimeout(()=>{this.tick()},e.intervalMs()),t.t(this.timer)}tick(){let{sink:e}=this;e!==null&&!e.ready()?this.wait(e):this.collect(!0)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reportLimit(e){this.limitDue=!1,e.diagnostics.report(`config.invalid`,`The app registered ${String(this.registry.size)} probes. The profiler.maxProbes limit is ${String(e.capacity)}. The probes above the limit do nothing.`)||(this.limitDue=!0)}hasData(){for(let e=1;e<this.limit;e++)if(this.stats[e*c+l]>0)return!0;return!1}emitSlot(t,n,r,i){let{stats:a,hist:p}=this,m=r.slot*c,h=r.slot*368,g=a[m+l],_=a[m+d],v=a[m+f],y=e=>Math.min(Math.max(o(p,h,g,e)/1e3,_),v),b={[e.Jt.probe]:n,[e.Jt.sampleEvery]:r.period,[e.Jt.p50]:y(.5),[e.Jt.p90]:y(.9),[e.Jt.p99]:y(.99)};this.overhead!==void 0&&(b[e.Jt.overhead]=this.overhead);let{selfHist:x}=this,S=0;for(let e=h;e<h+368;e++)S+=x[e];S>0&&(b[e.Jt.selfP99]=Math.min(o(x,h,S,.99)/1e3,v));let{bounds:C,counts:w}=s(p,h),T={"metric.name":e.Xt,"metric.unit":`ms`,"metric.type":`histogram`,[e.Pt.start]:i,[e.Pt.attributeKeys]:[e.Jt.probe,e.Jt.sampleEvery],[e.Pt.count]:g,[e.Pt.sum]:a[m+u],[e.Pt.min]:_,[e.Pt.max]:v,[e.Pt.bounds]:C,[e.Pt.buckets]:w};a.fill(0,m,m+c),p.fill(0,h,h+368),x.fill(0,h,h+368),t.emit(e.Xt,b,T)}calibrate(){this.calibrated=!0;let{probe:t}=this.makeProbe(``,0,{period:1,threshold:1/0,loose:!1}),n=performance.now(),r=n;for(let e=0;e<1e5&&r===n;e++)r=performance.now();if(r===n)return;let i=r+2,a=r,o=0;for(let n=0;n<e.Ut;n++){let e=t.begin();if(t.end(e),e!==a&&(a=e,o=n,e>=i))break}o>0&&(this.overhead=Math.round((a-r)*1e6/o))}};function b(){let e=globalThis,t=e[_];if(t)return t;let n=new y;return e[_]=n,n}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return b}});
2
- //# sourceMappingURL=profiler-eVCknCzS.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiler-eVCknCzS.cjs","names":["PROFILE_MAX_US","PROFILER_GLOBAL_KEY","TELEMETRY_SDK_VERSION","PROFILER_PROBE_LIMIT","PROFILE_KEYS","PROFILE_METRIC_NAME","METRIC_KEYS","PROFILER_CALIBRATION_PAIRS","require_constants","require_unref","SUB_COUNT","SUB_MASK","bucketOf","value","us","shift","upperOf","index","percentileOf","rank","q","count","sum","i","buckets","base","pointBuckets","first","last","merge","low","high","counts","k","STATS_WIDTH","COUNT","SUM","MIN","MAX","SAMPLING_WIDTH","MAX_PERIOD","FRAME_WIDTH","SPAN_WIDTH","CORE_KEY","NOOP_PROBE","ProfilerCore","name","diagnostics","known","rules","options","slot","entry","period","probe","token","waits","result","fn","then","done","error","minMs","names","found","at","ring","to","from","limit","sink","timed","start","threshold","loose","put","ms","settle","now","leave","end","self","durationMs","child","stack","ringAt","frame","page","drain","waiting","left","row","stats","min","max","quantile","hist","attributes","selfCount","selfHist","fields","bounds","edge","reads","until","tick","pairsAtTick","pairs","profilerCore","store","pinned","core"],"sources":["../src/core/profile-buckets.ts","../src/core/profiler.ts"],"sourcesContent":["// src/core/profile-buckets.ts\n//\n// Maps a duration in microseconds to a bucket of the profiler's log-linear histogram. Also\n// reads percentiles and builds the explicit bounds for a summary record.\n\nimport {\n PROFILE_BUCKETS,\n PROFILE_MAX_US,\n PROFILE_POINT_BUCKETS,\n PROFILE_SUB_BITS,\n} from \"../constants\";\n\n/** Sub-buckets per power of two. Values below this each get a bucket of their own. */\nconst SUB_COUNT = 1 << PROFILE_SUB_BITS;\n\n/** Masks the sub-bucket bits of a bucket index. */\nconst SUB_MASK = SUB_COUNT - 1;\n\n/**\n * Returns the bucket for a duration. Runs on the hot path, once per value.\n * @param us Duration in microseconds, a non-negative integer.\n * @returns The bucket index, 0 to 367. Anything above PROFILE_MAX_US lands in 367.\n */\nexport function bucketOf(us: number): number {\n // Clamp before the bit math: Math.clz32 and >>> only look at 32 bits, so a value of 2^32 or\n // more would land in the wrong bucket.\n const value = Math.min(us, PROFILE_MAX_US);\n\n if (value < SUB_COUNT) {\n return value;\n }\n\n // Math.clz32 gives us the exponent without a loop (up to 26 steps) or float math.\n // `shift` is how many low bits sit below the sub-bucket bits.\n const shift = 31 - Math.clz32(value) - PROFILE_SUB_BITS;\n return ((shift + 1) << PROFILE_SUB_BITS) | ((value >>> shift) & SUB_MASK);\n}\n\n/**\n * Returns the largest duration that still falls into a bucket.\n * @param index Bucket index, 0 to 367.\n * @returns The inclusive upper bound, in microseconds.\n */\nexport function upperOf(index: number): number {\n if (index < SUB_COUNT) {\n return index;\n }\n\n // Set all the low bits bucketOf dropped. Without them we'd return the bucket's smallest value.\n const shift = (index >>> PROFILE_SUB_BITS) - 1;\n return ((SUB_COUNT + (index & SUB_MASK)) << shift) + (1 << shift) - 1;\n}\n\n/**\n * Reads a percentile from one probe's histogram. Allocates nothing.\n * @param buckets Bucket counts for all probes.\n * @param base Index of the probe's first bucket.\n * @param count Sum of the probe's buckets. Must be above 0.\n * @param q Percentile as a fraction, e.g. 0.99.\n * @returns The upper bound of the bucket that holds the rank, in microseconds.\n */\nexport function percentileOf(buckets: Uint32Array, base: number, count: number, q: number): number {\n // A rank of 0 would match the first bucket even when it is empty.\n const rank = Math.max(1, Math.ceil(q * count));\n let sum = 0;\n\n // Walk the counts in place. Copying or sorting would make garbage on every flush.\n for (let i = 0; i < PROFILE_BUCKETS; i++) {\n sum += buckets[base + i];\n\n if (sum >= rank) {\n return upperOf(i);\n }\n }\n\n // Only reachable if the caller passed a wrong count.\n return upperOf(PROFILE_BUCKETS - 1);\n}\n\n/**\n * Builds the explicit-bounds histogram for a summary record.\n * @param buckets Bucket counts for all probes.\n * @param base Index of the probe's first bucket.\n * @returns Bounds in ms and the count per group. There is one more count than there are bounds.\n */\nexport function pointBuckets(\n buckets: Uint32Array,\n base: number,\n): { bounds: number[]; counts: number[] } {\n let first = 0;\n while (first < PROFILE_BUCKETS && buckets[base + first] === 0) {\n first++;\n }\n\n if (first === PROFILE_BUCKETS) {\n return { bounds: [], counts: [0] };\n }\n\n // The bucket at `first` isn't empty, so this loop stops there at the latest.\n let last = PROFILE_BUCKETS - 1;\n while (buckets[base + last] === 0) {\n last--;\n }\n\n // Groups start at multiples of 2^merge. That puts every bound on a fixed grid for the merge\n // level, whatever the record's first bucket happens to be.\n let merge = 0;\n while ((last >> merge) - (first >> merge) + 1 > PROFILE_POINT_BUCKETS) {\n merge++;\n }\n\n const low = first >> merge;\n const high = last >> merge;\n\n // Plain arrays, because the OTLP metrics serializer drops typed arrays.\n const counts = Array.from({ length: high - low + 1 }, () => 0);\n for (let i = first; i <= last; i++) {\n counts[(i >> merge) - low] += buckets[base + i];\n }\n\n // A group's bound is the bound of its last bucket. Dividing by 1000 gives ms.\n const bounds = Array.from(\n { length: high - low },\n (_unused, k) => upperOf(((low + k + 1) << merge) - 1) / 1000,\n );\n\n return { bounds, counts };\n}\n","// src/core/profiler.ts\n//\n// Times spans of app code with probes. Durations accumulate in typed arrays, and once per\n// interval every probe that saw data is flushed as one histogram summary record.\n\nimport {\n METRIC_KEYS,\n PROFILE_BUCKETS,\n PROFILE_KEYS,\n PROFILE_METRIC_NAME,\n PROFILER_CALIBRATION_MS,\n PROFILER_CALIBRATION_PAIRS,\n PROFILER_GLOBAL_KEY,\n PROFILER_PROBE_LIMIT,\n PROFILER_RING_SPANS,\n PROFILER_STACK_DEPTH,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { MetricAttributes, Probe, ProbeOptions, Profiler } from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport { bucketOf, percentileOf, pointBuckets } from \"./profile-buckets\";\n\n/** One stats row is [count, sum, min, max]. Sum, min and max are in ms. */\nconst STATS_WIDTH = 4;\nconst COUNT = 0;\nconst SUM = 1;\nconst MIN = 2;\nconst MAX = 3;\n\n/** One sampling row is [countdown, period]. */\nconst SAMPLING_WIDTH = 2;\n\n/** The period lives in an Int32Array, so this is as large as it gets. */\nconst MAX_PERIOD = 2 ** 31 - 1;\n\n/** One span-stack frame is [start, child time, slot]. */\nconst FRAME_WIDTH = 3;\n\n/** One entry in the recent-span ring is [slot, start, end]. */\nconst SPAN_WIDTH = 3;\n\n/** Global key for the core, one per library version. */\nconst CORE_KEY = Symbol.for(`${PROFILER_GLOBAL_KEY}@${TELEMETRY_SDK_VERSION}`);\n\n/** Handed out for names we reject. Never reads the clock. */\nconst NOOP_PROBE: Probe = {\n begin: () => -1,\n end: () => undefined,\n endAfterPaint: () => undefined,\n record: () => undefined,\n};\n\n/** Ends a span that was waiting on a paint or a promise. */\ntype Settle = (token: number, now: number) => void;\n\n/** The page globals the paint wait needs. Workers and Node.js have none of them. */\ninterface PaintScope {\n requestAnimationFrame?: (callback: () => void) => unknown;\n document?: {\n /** \"hidden\" while the page isn't painting. */\n visibilityState?: string;\n addEventListener: (type: string, listener: () => void) => void;\n };\n}\n\n/** What the runtime hands the core on attach. */\nexport interface ProfilerSink {\n /** Max number of probes (profiler.maxProbes). */\n capacity: number;\n /** Interval length in ms. */\n intervalMs(): number;\n /**\n * Builds and sends the record for one point.\n * @param name Metric name.\n * @param attributes Record attributes for the point.\n * @param fields Metric fields for the point.\n */\n emit(name: string, attributes: MetricAttributes, fields: Record<string, unknown>): void;\n /** The runtime's diagnostics reporter. */\n diagnostics: Diagnostics;\n /** False while the runtime can't accept records. */\n ready(): boolean;\n /**\n * Leaves a breadcrumb for a span that ran longer than its probe's threshold.\n * @param name Probe name.\n * @param ms Span duration in ms.\n */\n outlier(name: string, ms: number): void;\n}\n\n/** Probe options after validation. */\ninterface ProbeRules {\n /** Measure one span in every `period`. */\n period: number;\n /** Spans longer than this (ms) leave a breadcrumb. Infinity means never. */\n threshold: number;\n /** True for async probes, whose spans stay off the span stack. */\n loose: boolean;\n}\n\n/** A registered probe. */\ninterface ProbeEntry {\n /** The handle. Every probe() call with the same name returns this one. */\n probe: Probe;\n /** The probe's row in the typed arrays: registration index + 1. */\n slot: number;\n /** Sampling period, from the options passed the first time the name was seen. */\n period: number;\n /** Ends one of this probe's spans that isn't on the span stack. */\n settle: Settle;\n /** Pops a span off the stack without ending it. It ends later. */\n leave: (token: number) => void;\n}\n\n/** Holds the probe names and all their timings. There is one core per library version. */\nexport class ProfilerCore implements Profiler {\n /** Probes by name. Names are never removed, so insertion order is slot order. */\n private readonly registry = new Map<string, ProbeEntry>();\n\n /** Rows in use. 0 while detached, so one compare covers both \"off\" and \"over the limit\". */\n private limit = 0;\n\n // The typed arrays start empty rather than null. Hypothesis (not measured): a single field\n // type keeps V8's inline caches on the hot path monomorphic.\n\n /**\n * Count, sum, min and max per slot. A row's four values sit in 32 adjacent bytes, so an add\n * should touch a single cache line (hypothesis, not measured).\n */\n private stats = new Float64Array(0);\n\n /** Bucket counts, PROFILE_BUCKETS per slot. */\n private hist = new Uint32Array(0);\n\n /** Self-time bucket counts per slot. Spans without a stack frame don't add to it. */\n private selfHist = new Uint32Array(0);\n\n /** Frames for the open, nested spans. Each frame adds up the time of the spans inside it. */\n private readonly stack = new Float64Array(PROFILER_STACK_DEPTH * FRAME_WIDTH);\n\n /** Number of frames in use. */\n private depth = 0;\n\n /** Recent spans, for linking to long animation frames. Empty until link() turns it on. */\n private ring = new Float64Array(0);\n\n /** Next write offset in the ring. */\n private ringAt = 0;\n\n /** Shortest span (ms) that goes into the ring. Infinity keeps the ring off. */\n private linkMs = Infinity;\n\n /** Spans waiting for the next paint. */\n private painted: ((now: number) => void)[] = [];\n\n /** Gets us a task right after the paint. Created on the first wait. */\n private channel: MessageChannel | undefined;\n\n /** Countdown and period per slot. */\n private sampling = new Int32Array(0);\n\n /**\n * Clock value at the last detach() or reset(). Spans that started at or before it are dropped.\n * \"At\" matters: on a coarse clock, a span started in the reset's tick reads the same value.\n */\n private floor = -1;\n\n /** Timer for the current interval. It only runs while there is data waiting. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** When the interval's first value arrived, in epoch ms. */\n private startedAt = 0;\n\n /** Invalid tokens seen while on, since the last collect(). end() itself reports nothing. */\n private badTokens = 0;\n\n /** Cost of one sampled begin()/end() pair, in ns. */\n private overhead: number | undefined = undefined;\n\n /** Set once calibration has run, so a too-coarse clock only blocks us once. */\n private calibrated = false;\n\n /** The runtime's sink. Null while detached. */\n private sink: ProfilerSink | null = null;\n\n /** True once this attach has reported a probe over the limit. */\n private reported = false;\n\n /** True while a limit report the throttle dropped is waiting for the next collect. */\n private limitDue = false;\n\n /**\n * Returns the probe for a name. Never throws into the app.\n * @param name Probe name. A JavaScript caller can pass anything.\n * @param options Probe options. Only the options from the first call for a name count.\n * @param diagnostics The current runtime's diagnostics. Without a runtime, nothing is reported.\n * @returns The probe, or a no-op probe if the name is rejected.\n */\n probe(name: string, options?: ProbeOptions, diagnostics?: Diagnostics): Probe {\n // Only look at the type. String(name) would run a hostile toString().\n if (typeof name !== \"string\" || name === \"\") {\n diagnostics?.report(\n \"config.invalid\",\n \"The probe name must be a string that is not empty. The probe does nothing.\",\n );\n return NOOP_PROBE;\n }\n\n const known = this.registry.get(name);\n if (known) {\n return known.probe;\n }\n\n if (this.registry.size >= PROFILER_PROBE_LIMIT) {\n diagnostics?.report(\n \"config.invalid\",\n `The profiler keeps at most ${String(PROFILER_PROBE_LIMIT)} probe names. The probe ${name} does nothing.`,\n );\n return NOOP_PROBE;\n }\n\n const rules = this.rulesOf(name, options, diagnostics);\n const { period } = rules;\n\n // An options getter can register probes behind our back. Re-check, or two names share a slot.\n if (this.registry.has(name) || this.registry.size >= PROFILER_PROBE_LIMIT) {\n return this.probe(name, undefined, diagnostics);\n }\n\n const slot = this.registry.size + 1;\n const entry = this.makeProbe(name, slot, rules);\n const { probe } = entry;\n this.registry.set(name, entry);\n\n if (slot < this.limit) {\n this.prime(slot, period);\n } else if (this.limit > 0 && !this.reported) {\n this.reported = true;\n // The limit belongs to the attached runtime, so report through it even when the caller\n // passed no diagnostics.\n const sent = this.sink?.diagnostics.report(\n \"config.invalid\",\n `The probe ${name} is above the profiler.maxProbes limit of ${String(this.limit - 1)}. The probe does nothing.`,\n );\n\n if (sent === false) {\n this.limitDue = true;\n }\n }\n\n return probe;\n }\n\n /**\n * Calls a function and times it. If the result is a thenable, the span ends when it settles.\n * The caller only ever sees errors from its own function.\n * @param name Probe name.\n * @param fn The app's function.\n * @param diagnostics The current runtime's diagnostics, if there is one.\n * @returns Whatever fn returned, or the result of its then() call.\n */\n time<T>(name: string, fn: () => T, diagnostics?: Diagnostics): T {\n this.probe(name, undefined, diagnostics);\n\n // A rejected name has no entry. Just run the function without a span.\n const entry = this.registry.get(name);\n const token = entry ? entry.probe.begin() : -1;\n let waits = false;\n\n try {\n const result = fn();\n\n if (entry && token >= 0) {\n try {\n const then = (result as { then?: unknown } | null | undefined)?.then;\n\n if (typeof then === \"function\") {\n const done = (): void => {\n entry.settle(token, performance.now());\n };\n\n waits = true;\n entry.leave(token);\n\n // Hand back the chained result, so a rejection has exactly one owner: the caller.\n return (then as PromiseLike<unknown>[\"then\"]).call(\n result,\n (value) => {\n done();\n return value;\n },\n (error: unknown) => {\n done();\n throw error;\n },\n ) as T;\n }\n } catch (error) {\n waits = false;\n diagnostics?.report(\n \"capture.record_failed\",\n `The library could not read what the function of the probe ${name} returned. The span ends now.`,\n undefined,\n error,\n );\n }\n }\n\n return result;\n } finally {\n if (!waits) {\n entry?.probe.end(token);\n }\n }\n }\n\n /**\n * Turns the recent-span ring on or off. The frame phases capture reads from it.\n * @param minMs Shortest span (ms) to keep. Infinity turns the ring off.\n */\n link(minMs: number): void {\n this.linkMs = minMs;\n\n if (minMs < Infinity && this.ring.length === 0) {\n this.ring = new Float64Array(PROFILER_RING_SPANS * SPAN_WIDTH);\n }\n }\n\n /**\n * Finds the probes that had a recent span inside a time range.\n * @param from Range start, as a performance.now() value.\n * @param to Range end.\n * @returns The probe names, without duplicates.\n */\n linked(from: number, to: number): string[] {\n const { ring } = this;\n const names = [...this.registry.keys()];\n const found = new Set<string>();\n\n for (let at = 0; at < ring.length; at += SPAN_WIDTH) {\n // Slot 0 means an empty row or a calibration span.\n if (ring[at] > 0 && ring[at + 1] < to && ring[at + 2] > from) {\n found.add(names[ring[at] - 1]);\n }\n }\n\n return [...found];\n }\n\n /**\n * Turns the profiler on with a runtime's sink. Calling it again swaps the sink.\n * @param sink The runtime's sink.\n */\n attach(sink: ProfilerSink): void {\n const limit = sink.capacity + 1;\n this.sink = sink;\n\n // Re-attaching with the same capacity keeps the data.\n if (this.stats.length !== limit * STATS_WIDTH) {\n this.stats = new Float64Array(limit * STATS_WIDTH);\n this.hist = new Uint32Array(limit * PROFILE_BUCKETS);\n this.selfHist = new Uint32Array(limit * PROFILE_BUCKETS);\n this.sampling = new Int32Array(limit * SAMPLING_WIDTH);\n }\n\n this.limit = limit;\n this.reported = false;\n this.limitDue = false;\n this.prime(0, 1);\n for (const entry of this.registry.values()) {\n if (entry.slot < limit) {\n this.prime(entry.slot, entry.period);\n }\n }\n\n if (this.registry.size > sink.capacity) {\n this.reported = true;\n this.reportLimit(sink);\n }\n }\n\n /** Turns the profiler off and drops the data. The runtime calls collect(false) first. */\n detach(): void {\n this.limit = 0;\n this.sink = null;\n this.clearTimer();\n this.clear();\n }\n\n /**\n * Sends one summary record per probe that has data, then starts a new interval. Does nothing\n * while the sink isn't ready.\n * @param timed True when called from the interval timer. Only a timed collect calibrates.\n */\n collect(timed: boolean): void {\n const { sink } = this;\n\n // A runtime that isn't ready would refuse the records, so keep the data and the timer for a\n // later collect. Zeroing the slots here would lose those points.\n if (!sink?.ready()) {\n return;\n }\n\n // The diagnostics throttle swallowed this attach's limit report. Try again, otherwise the\n // app never hears that some of its probes do nothing.\n if (this.limitDue) {\n this.reportLimit(sink);\n }\n\n this.clearTimer();\n\n // Calibration blocks the thread for 2-3 ms (longer on a too-coarse clock), so flush() and\n // the exit path skip it.\n if (timed && !this.calibrated && this.hasData()) {\n this.calibrate();\n }\n\n const start = `${String(this.startedAt)}000000`;\n for (const [name, entry] of this.registry) {\n // Probes over the limit have no row. After a detach() from inside an emit, none do.\n if (entry.slot < this.limit && this.stats[entry.slot * STATS_WIDTH + COUNT] > 0) {\n this.emitSlot(sink, name, entry, start);\n }\n }\n\n if (this.badTokens > 0) {\n sink.diagnostics.count(\"record.dropped_malformed\", this.badTokens);\n this.badTokens = 0;\n }\n }\n\n /** Drops the interval's data. The profiler stays on. */\n reset(): void {\n this.clearTimer();\n this.badTokens = 0;\n this.clear();\n }\n\n /** Drops the data and any open spans. Spans started at or before this call add nothing. */\n private clear(): void {\n this.floor = performance.now();\n this.depth = 0;\n this.stats.fill(0);\n this.hist.fill(0);\n this.selfHist.fill(0);\n this.ring.fill(0);\n }\n\n /**\n * Reads the options for a new probe. Never throws into the app.\n * @param name Probe name.\n * @param options Options from the app.\n * @param diagnostics The current runtime's diagnostics, if there is one.\n * @returns The rules. Any invalid option falls back to its default.\n */\n private rulesOf(\n name: string,\n options: ProbeOptions | undefined,\n diagnostics: Diagnostics | undefined,\n ): ProbeRules {\n const rules: ProbeRules = { period: 1, threshold: Infinity, loose: false };\n let period: unknown;\n let threshold: unknown;\n let loose: unknown;\n\n // A getter or a Proxy trap on the options can throw.\n try {\n period = options?.sampleEvery;\n threshold = options?.slowMs;\n loose = options?.async;\n } catch (error) {\n diagnostics?.report(\n \"config.invalid\",\n `The library could not read the options of the probe ${name}. The library uses the defaults.`,\n undefined,\n error,\n );\n return rules;\n }\n\n if (\n typeof period === \"number\" &&\n Number.isInteger(period) &&\n period >= 1 &&\n period <= MAX_PERIOD\n ) {\n rules.period = period;\n } else if (period !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The sampleEvery option of the probe ${name} must be an integer from 1 to ${String(MAX_PERIOD)}. The library uses 1.`,\n );\n }\n\n if (typeof threshold === \"number\" && threshold >= 0 && threshold < Infinity) {\n rules.threshold = threshold;\n } else if (threshold !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The slowMs option of the probe ${name} must be a finite number, 0 or larger. The probe adds no breadcrumb.`,\n );\n }\n\n if (typeof loose === \"boolean\") {\n rules.loose = loose;\n } else if (loose !== undefined) {\n diagnostics?.report(\n \"config.invalid\",\n `The async option of the probe ${name} must be a boolean. The library uses false.`,\n );\n }\n\n return rules;\n }\n\n /**\n * Builds a probe's closures, once per probe, so destructured members still work.\n * @param name Probe name.\n * @param slot The probe's row.\n * @param rules Validated probe options.\n * @returns The registry entry, including the probe.\n */\n private makeProbe(name: string, slot: number, rules: ProbeRules): ProbeEntry {\n const { period, threshold, loose } = rules;\n\n // Records one duration, plus a breadcrumb if it is over the probe's threshold.\n const put = (ms: number): void => {\n this.add(slot, ms);\n\n if (ms > threshold) {\n this.sink?.outlier(name, ms);\n }\n };\n\n // Drop the span if we're off, or if it started at or before a detach() or reset().\n const settle: Settle = (token, now) => {\n if (slot < this.limit && token > this.floor) {\n put(now - token);\n }\n };\n\n const leave = (token: number): void => {\n if (!loose) {\n this.pop(slot, token, performance.now());\n }\n };\n\n const end = (token: number): void => {\n // Type check first, so the compare can never run a hostile valueOf().\n const now = typeof token === \"number\" && token >= 0 ? performance.now() : -1;\n if (now < 0) {\n // -1 means begin() didn't measure this span. Other bad tokens only count while we're on.\n if (token !== -1 && slot < this.limit) {\n this.badTokens++;\n }\n return;\n }\n\n if (loose) {\n settle(token, now);\n return;\n }\n\n // Drop the span if we're off, or if it started at or before a detach() or reset().\n if (slot >= this.limit || token <= this.floor) {\n return;\n }\n\n const self = this.pop(slot, token, now);\n put(now - token);\n\n // No frame means no self time: the frame was lost to a reset or to a full stack.\n if (self >= 0) {\n this.selfHist[slot * PROFILE_BUCKETS + bucketOf(Math.ceil(self * 1000))]++;\n }\n };\n\n const probe: Probe = {\n begin: () => {\n // Off, over the limit or sampled out: don't even read the clock.\n if (slot >= this.limit || !this.sampled(slot)) {\n return -1;\n }\n\n const now = performance.now();\n if (!loose) {\n this.push(slot, now);\n }\n\n return now;\n },\n end,\n endAfterPaint: (token) => {\n const waits =\n typeof token === \"number\" &&\n token >= 0 &&\n slot < this.limit &&\n this.afterPaint((now) => {\n settle(token, now);\n });\n\n // Bad token, probe off, or a page that isn't painting: end right away.\n if (!waits) {\n end(token);\n return;\n }\n\n leave(token);\n },\n record: (durationMs) => {\n if (slot >= this.limit) {\n return;\n }\n\n if (typeof durationMs !== \"number\" || !Number.isFinite(durationMs) || durationMs < 0) {\n this.sink?.diagnostics.report(\n \"record.dropped_malformed\",\n `The duration of the probe ${name} is not valid. The library dropped it.`,\n { [PROFILE_KEYS.probe]: name },\n );\n return;\n }\n\n if (this.sampled(slot)) {\n put(durationMs);\n }\n },\n };\n\n return { probe, slot, period, settle, leave };\n }\n\n /**\n * Pushes a frame for a new span.\n * @param slot The probe's row.\n * @param now Span start.\n */\n private push(slot: number, now: number): void {\n const { stack } = this;\n\n // A full stack is full of frames whose spans never got an end(). Drop them, or no later\n // span gets a self time.\n if (this.depth === PROFILER_STACK_DEPTH) {\n this.depth = 0;\n }\n\n const at = this.depth++ * FRAME_WIDTH;\n stack[at] = now;\n stack[at + 1] = 0;\n stack[at + 2] = slot;\n }\n\n /**\n * Pops a span's frame, along with any frames above it, and adds the span's duration to the\n * child time of the frame below.\n * @param slot The probe's row.\n * @param token Span start.\n * @param now Span end, or the time the span leaves the stack.\n * @returns Self time in ms, or -1 if the span had no frame.\n */\n private pop(slot: number, token: number, now: number): number {\n const { stack } = this;\n const ms = now - token;\n let child = 0;\n\n for (let at = (this.depth - 1) * FRAME_WIDTH; at >= 0; at -= FRAME_WIDTH) {\n // Any frame above ours is a span that never got an end(). Its child time is ours.\n child += stack[at + 1];\n\n if (stack[at] === token && stack[at + 2] === slot) {\n this.depth = at / FRAME_WIDTH;\n\n if (at > 0) {\n stack[at - FRAME_WIDTH + 1] += ms;\n }\n\n if (ms >= this.linkMs) {\n const { ring, ringAt } = this;\n ring[ringAt] = slot;\n ring[ringAt + 1] = token;\n ring[ringAt + 2] = now;\n this.ringAt = (ringAt + SPAN_WIDTH) % ring.length;\n }\n\n return Math.max(ms - child, 0);\n }\n }\n\n return -1;\n }\n\n /**\n * Runs a function in the first task after the next paint.\n * @param done Called with the time after the paint.\n * @returns False where there is no frame callback, or when the page is hidden.\n */\n private afterPaint(done: (now: number) => void): boolean {\n const { requestAnimationFrame: frame, document: page } = globalThis as PaintScope;\n\n if (\n typeof frame !== \"function\" ||\n typeof MessageChannel === \"undefined\" ||\n page?.visibilityState === \"hidden\"\n ) {\n return false;\n }\n\n if (!this.channel) {\n const drain = (): void => {\n const now = performance.now();\n const waiting = this.painted;\n this.painted = [];\n\n for (const end of waiting) {\n end(now);\n }\n };\n\n this.channel = new MessageChannel();\n this.channel.port1.onmessage = drain;\n\n // A hidden page gets no frame callbacks. End the spans now, or they include the hidden time.\n page?.addEventListener(\"visibilitychange\", () => {\n if (page.visibilityState === \"hidden\") {\n drain();\n }\n });\n }\n\n // rAF callbacks run before the paint. A task posted from one runs after it.\n if (this.painted.push(done) === 1) {\n frame(() => {\n this.channel?.port2.postMessage(0);\n });\n }\n\n return true;\n }\n\n /**\n * Writes a slot's sampling row so the next span gets measured.\n * @param slot The probe's row.\n * @param period Sampling period.\n */\n private prime(slot: number, period: number): void {\n const at = slot * SAMPLING_WIDTH;\n this.sampling[at] = 1;\n this.sampling[at + 1] = period;\n }\n\n /**\n * Counts down a slot's sampling. A countdown gives an exact rate, which Math.random() wouldn't.\n * @param slot The probe's row.\n * @returns True if this span should be measured.\n */\n private sampled(slot: number): boolean {\n const at = slot * SAMPLING_WIDTH;\n const left = this.sampling[at] - 1;\n\n if (left > 0) {\n this.sampling[at] = left;\n return false;\n }\n\n this.sampling[at] = this.sampling[at + 1];\n return true;\n }\n\n /**\n * Adds one duration to a slot. This is the hot path: no Map lookup, no try.\n * @param slot The probe's row.\n * @param ms Duration in ms.\n */\n private add(slot: number, ms: number): void {\n // A forged token gives a negative duration. A broken clock gives NaN or Infinity.\n if (!(ms >= 0) || ms === Infinity) {\n this.badTokens++;\n return;\n }\n\n const { stats } = this;\n const row = slot * STATS_WIDTH;\n const count = stats[row + COUNT];\n stats[row + COUNT] = count + 1;\n stats[row + SUM] += ms;\n\n if (count === 0 || ms < stats[row + MIN]) {\n stats[row + MIN] = ms;\n }\n\n if (count === 0 || ms > stats[row + MAX]) {\n stats[row + MAX] = ms;\n }\n\n // Buckets include their upper bound, so round up or the value lands one bucket too low.\n this.hist[slot * PROFILE_BUCKETS + bucketOf(Math.ceil(ms * 1000))]++;\n\n // Slot 0 is the calibration slot, and calibration must not start an interval.\n if (this.timer === null && slot > 0 && this.sink !== null) {\n this.startedAt = Date.now();\n this.wait(this.sink);\n }\n }\n\n /**\n * Starts the interval timer, unref'd so a pending timer doesn't keep Node.js alive.\n * @param sink The runtime's sink.\n */\n private wait(sink: ProfilerSink): void {\n this.timer = setTimeout(() => {\n this.tick();\n }, sink.intervalMs());\n unrefTimer(this.timer);\n }\n\n /** Collects at the end of an interval, or waits another one if the runtime isn't ready. */\n private tick(): void {\n const { sink } = this;\n\n if (sink !== null && !sink.ready()) {\n this.wait(sink);\n return;\n }\n\n this.collect(true);\n }\n\n /** Stops the interval timer. */\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Reports that there are more probes than the limit allows. If the throttle drops the report,\n * the next collect tries again.\n * @param sink The runtime's sink.\n */\n private reportLimit(sink: ProfilerSink): void {\n // Clear the flag first, so a handler that collects can't kick off a second report.\n this.limitDue = false;\n const sent = sink.diagnostics.report(\n \"config.invalid\",\n `The app registered ${String(this.registry.size)} probes. The profiler.maxProbes limit is ${String(sink.capacity)}. The probes above the limit do nothing.`,\n );\n\n if (!sent) {\n this.limitDue = true;\n }\n }\n\n /**\n * Checks whether any probe recorded a value in this interval.\n * @returns True if a slot above 0 has a non-zero count.\n */\n private hasData(): boolean {\n for (let slot = 1; slot < this.limit; slot++) {\n if (this.stats[slot * STATS_WIDTH + COUNT] > 0) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Sends one slot's summary record and zeroes the slot. The sampling countdown is left alone.\n * @param sink The runtime's sink.\n * @param name Probe name.\n * @param entry The probe's registry entry.\n * @param start Interval start, in Unix nanoseconds.\n */\n private emitSlot(sink: ProfilerSink, name: string, entry: ProbeEntry, start: string): void {\n const { stats, hist } = this;\n const row = entry.slot * STATS_WIDTH;\n const base = entry.slot * PROFILE_BUCKETS;\n const count = stats[row + COUNT];\n const min = stats[row + MIN];\n const max = stats[row + MAX];\n\n // A bucket bound can be higher than the exact max, so clamp every percentile to [min, max].\n const quantile = (q: number): number =>\n Math.min(Math.max(percentileOf(hist, base, count, q) / 1000, min), max);\n\n const attributes: MetricAttributes = {\n [PROFILE_KEYS.probe]: name,\n [PROFILE_KEYS.sampleEvery]: entry.period,\n [PROFILE_KEYS.p50]: quantile(0.5),\n [PROFILE_KEYS.p90]: quantile(0.9),\n [PROFILE_KEYS.p99]: quantile(0.99),\n };\n if (this.overhead !== undefined) {\n attributes[PROFILE_KEYS.overhead] = this.overhead;\n }\n\n // Count the self times here, at collect, so the hot path has no second counter to write.\n const { selfHist } = this;\n let selfCount = 0;\n for (let at = base; at < base + PROFILE_BUCKETS; at++) {\n selfCount += selfHist[at];\n }\n\n if (selfCount > 0) {\n attributes[PROFILE_KEYS.selfP99] = Math.min(\n percentileOf(selfHist, base, selfCount, 0.99) / 1000,\n max,\n );\n }\n\n const { bounds, counts } = pointBuckets(hist, base);\n const fields: Record<string, unknown> = {\n \"metric.name\": PROFILE_METRIC_NAME,\n \"metric.unit\": \"ms\",\n \"metric.type\": \"histogram\",\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: [PROFILE_KEYS.probe, PROFILE_KEYS.sampleEvery],\n [METRIC_KEYS.count]: count,\n [METRIC_KEYS.sum]: stats[row + SUM],\n [METRIC_KEYS.min]: min,\n [METRIC_KEYS.max]: max,\n [METRIC_KEYS.bounds]: bounds,\n [METRIC_KEYS.buckets]: counts,\n };\n\n // Zero before emitting: an app processor can call end() from inside the emit.\n stats.fill(0, row, row + STATS_WIDTH);\n hist.fill(0, base, base + PROFILE_BUCKETS);\n selfHist.fill(0, base, base + PROFILE_BUCKETS);\n sink.emit(PROFILE_METRIC_NAME, attributes, fields);\n }\n\n /**\n * Measures what one sampled begin()/end() pair costs, on slot 0. Runs once. If the clock never\n * shows an edge or never ticks, no value is set.\n */\n private calibrate(): void {\n this.calibrated = true;\n const { probe } = this.makeProbe(\"\", 0, { period: 1, threshold: Infinity, loose: false });\n\n // Browsers round performance.now() to 5 us, 100 us or 1 ms. Measure from clock edge to clock\n // edge: a window that isn't aligned to an edge can be off by up to one tick.\n const first = performance.now();\n let edge = first;\n for (let reads = 0; reads < PROFILER_CALIBRATION_PAIRS && edge === first; reads++) {\n edge = performance.now();\n }\n\n // No edge within the read limit, so the clock is frozen or too coarse. Without a start edge\n // the result would come out too large.\n if (edge === first) {\n return;\n }\n\n // begin()'s token is the clock reading, so the loop doesn't need a third clock read.\n const until = edge + PROFILER_CALIBRATION_MS;\n let tick = edge;\n let pairsAtTick = 0;\n for (let pairs = 0; pairs < PROFILER_CALIBRATION_PAIRS; pairs++) {\n const token = probe.begin();\n probe.end(token);\n\n if (token !== tick) {\n tick = token;\n pairsAtTick = pairs;\n\n if (token >= until) {\n break;\n }\n }\n }\n\n // Whole nanoseconds. Hypothesis: the noise in a single 2 ms run is more than 1 ns anyway.\n if (pairsAtTick > 0) {\n this.overhead = Math.round(((tick - edge) * 1e6) / pairsAtTick);\n }\n }\n}\n\n/**\n * Returns the profiler core for this library version. Two copies of the same version share it.\n * @returns The core.\n */\nexport function profilerCore(): ProfilerCore {\n // Each copy has its own class, so instanceof fails across copies. Cast structurally instead.\n const store = globalThis as Record<symbol, unknown>;\n const pinned = store[CORE_KEY] as ProfilerCore | undefined;\n if (pinned) {\n return pinned;\n }\n\n const core = new ProfilerCore();\n store[CORE_KEY] = core;\n return core;\n}\n"],"mappings":"A,8EAaA,IAAMU,EAAY,GAGZC,EAAWD,EAAY,EAO7B,SAAgBE,EAAS,EAAoB,CAG3C,IAAMC,EAAQ,KAAK,IAAIC,EAAId,EAAAA,EAAc,EAEzC,GAAIa,EAAQH,EACV,OAAOG,EAKT,IAAME,EAAQ,GAAK,KAAK,MAAMF,CAAK,EAAA,EACnC,OAASE,EAAQ,GAAA,EAA4BF,IAAUE,EAASJ,CAClE,CAOA,SAAgBK,EAAQ,EAAuB,CAC7C,GAAIC,EAAQP,EACV,OAAOO,EAIT,IAAMF,GAASE,IAAA,GAA8B,EAC7C,OAASP,GAAa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c,EAClB,IAAK,IAAIC,EAAQ,EAAGA,EAAQpG,EAAAA,GAA4B,IAAS,CAC/D,IAAMgD,EAAQD,EAAM,MAAM,EAG1B,GAFAA,EAAM,IAAIC,CAAK,EAEXA,IAAUkD,IACZ,EAAOlD,EACP,EAAcoD,EAEVpD,GAASiD,GACX,KAGN,CAGIE,EAAc,IAChB,KAAK,SAAW,KAAK,OAAQD,EAAOH,GAAQ,IAAOI,CAAW,EAElE,CACF,EAMA,SAAgBE,GAA6B,CAE3C,IAAMC,EAAQ,WACRC,EAASD,EAAMlE,GACrB,GAAImE,EACF,OAAOA,EAGT,IAAMC,EAAO,IAAIlE,EAEjB,MADA,GAAMF,GAAYoE,EACXA,CACT,C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiler-frames-CLXlT_xL.js","names":["PROFILE_KEYS","PROFILE_FRAME_METRIC_NAME","PROFILE_FRAME_PROBE","profilerCore","allowInWindow","FRAME_TYPE","FramePhasesCapture","ctx","entry","list","once","start","end","names","capturePolicy","phaseStart","value","renderStart","layoutStart","forced","script","phases","name","phase","ms","FramePacingCapture","scope","request","probe","frame","time","error"],"sources":["../src/capture/profiler-frames.ts"],"sourcesContent":["// src/capture/profiler-frames.ts\n//\n// Ties the profiler to the browser's rendering work. The frame phases capture attributes the\n// phases of each long animation frame to the probes that ran in it. Frame pacing measures the\n// time between consecutive frames.\n\nimport {\n PROFILE_FRAME_METRIC_NAME,\n PROFILE_FRAME_PROBE,\n PROFILE_KEYS,\n PROFILER_LINK_MIN_MS,\n} from \"../constants\";\nimport { profilerCore } from \"../core/profiler\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Long animation frames, not long tasks: long tasks don't have phases. */\nconst FRAME_TYPE = \"long-animation-frame\";\n\n/** One script in a long animation frame. */\ninterface FrameScript {\n /** Style and layout time the script forced, in ms. */\n forcedStyleAndLayoutDuration?: number;\n}\n\n/** A long animation frame. Some versions of the DOM typings don't declare these fields. */\ninterface PhaseEntry extends PerformanceEntry {\n /** When the render callbacks started. 0 if the frame didn't render. */\n renderStart?: number;\n /** When style and layout started. 0 if the frame didn't render. */\n styleAndLayoutStart?: number;\n /** The scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/** The page globals frame pacing needs. A worker or Node.js may have none of them. */\ninterface FrameScope {\n /** Calls a function before the next paint, passing the frame's start time. */\n requestAnimationFrame?: (callback: (time: number) => void) => number;\n cancelAnimationFrame?: (handle: number) => void;\n document?: Pick<Document, \"addEventListener\" | \"removeEventListener\">;\n}\n\n/** Attributes the phases of each long animation frame to every probe with a span in it. */\nexport class FramePhasesCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"frame-phases\";\n\n /** The active observer. Undefined while the capture isn't installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit for this capture, so a frozen tab can't flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Starts observing long animation frames and turns on the recent-span ring. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Older browsers have no supportedEntryTypes. The capture just stays off there.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n\n if (!supported?.includes(FRAME_TYPE)) {\n // Report on the first install in a document only, not on every reinstall after configure().\n const { once } = this.ctx;\n\n if (!once.framePhases) {\n once.framePhases = true;\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long animation frames. profiler.framePhases is off.\",\n );\n }\n\n return;\n }\n\n profilerCore().link(PROFILER_LINK_MIN_MS);\n this.observer = new PerformanceObserver((list) => {\n // The browser calls this directly, so anything we throw is an uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a long animation frame of the profiler.\",\n () => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n },\n );\n });\n\n // Not buffered: a buffered frame is older than anything in the ring and would link to nothing.\n this.observer.observe({ type: FRAME_TYPE });\n }\n\n /** Disconnects the observer and turns the recent-span ring off. */\n uninstall(): void {\n if (!this.observer) {\n return;\n }\n\n this.observer.disconnect();\n this.observer = undefined;\n profilerCore().link(Infinity);\n }\n\n /**\n * Records one frame's phases for every probe that had a span in the frame.\n * @param entry Long animation frame entry.\n */\n private record(entry: PhaseEntry): void {\n const start = entry.startTime;\n const end = start + entry.duration;\n const names = profilerCore().linked(start, end);\n\n if (names.length === 0) {\n return;\n }\n\n const { capturePolicy } = this.ctx.config;\n\n if (\n !allowInWindow(\n this.window,\n capturePolicy.longFramesPerWindow,\n this.ctx.diagnostics,\n \"profiler frames\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n // A frame that didn't render has 0 in both fields. The whole frame then counts as script.\n const phaseStart = (value = 0): number => (value > 0 ? value : end);\n const renderStart = phaseStart(entry.renderStart);\n const layoutStart = phaseStart(entry.styleAndLayoutStart);\n let forced = 0;\n\n for (const script of entry.scripts ?? []) {\n forced += script.forcedStyleAndLayoutDuration ?? 0;\n }\n\n const phases: [string, number][] = [\n [\"script\", renderStart - start],\n [\"render\", layoutStart - renderStart],\n [\"style_layout\", end - layoutStart],\n [\"forced_layout\", forced],\n ];\n\n for (const name of names) {\n for (const [phase, ms] of phases) {\n this.ctx.logger.logMetric(PROFILE_FRAME_METRIC_NAME, ms, \"ms\", \"histogram\", {\n [PROFILE_KEYS.probe]: name,\n [PROFILE_KEYS.framePhase]: phase,\n });\n }\n }\n }\n}\n\n/** Measures the time between consecutive frames with the frame pacing probe. */\nexport class FramePacingCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"frame-pacing\";\n\n /** Handle of the pending frame callback. Undefined while the capture isn't installed. */\n private handle: number | undefined;\n\n /** Start time of the last frame. -1 before the first frame and after the page was hidden. */\n private last = -1;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** A hidden page gets no frame callbacks, so the first frame back isn't an interval. */\n private readonly onVisibility = (): void => {\n this.last = -1;\n };\n\n /** Starts the frame callback loop. */\n install(): void {\n const scope = globalThis as FrameScope;\n const { requestAnimationFrame: request } = scope;\n\n if (this.handle !== undefined) {\n return;\n }\n\n if (typeof request !== \"function\") {\n const { once } = this.ctx;\n\n if (!once.framePacing) {\n once.framePacing = true;\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"This context has no frame callback. The frame pacing of the profiler is off.\",\n );\n }\n\n return;\n }\n\n const probe = profilerCore().probe(PROFILE_FRAME_PROBE, undefined, this.ctx.diagnostics);\n const frame = (time: number): void => {\n // The browser calls this directly, so anything we throw is an uncaught error on the page.\n // It also runs every frame, which is why the try block allocates nothing.\n try {\n if (this.last >= 0) {\n probe.record(time - this.last);\n }\n } catch (error) {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The library could not record a frame interval of the profiler.\",\n undefined,\n error,\n );\n }\n\n this.last = time;\n this.handle = request(frame);\n };\n\n scope.document?.addEventListener(\"visibilitychange\", this.onVisibility);\n this.handle = request(frame);\n }\n\n /** Stops the frame callback loop. */\n uninstall(): void {\n const scope = globalThis as FrameScope;\n\n if (this.handle === undefined) {\n return;\n }\n\n scope.cancelAnimationFrame?.(this.handle);\n scope.document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.handle = undefined;\n this.last = -1;\n }\n}\n"],"mappings":";;;;AAiBA,IAAMK,IAAa,wBA2BNC,IAAb,MAAmD;CAapB;CAX7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,MAAK,UAUT;QAJE,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,oBAAA,EAEV,SAASF,CAAU,GA8BnC,AAfAF,EAAa,CAAC,CAAC,KAAA,CAAyB,GACxC,KAA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uB,GAAI,MAAM,aAAa;IACzExB,EAAa,QAAQsB;IACrBtB,EAAa,aAAauB;EAC7B,CAAC;CAGP;AACF,GAGaE,IAAb,MAAmD;CAapB;CAX7B,OAAgB;CAGhB;CAGA,OAAe;CAKf,YAAY,GAAsC;EAArB,KAAA,MAAAlB;CAAsB;CAGnD,qBAA4C;EAC1C,KAAK,OAAO;CACd;CAGA,UAAgB;EACd,IAAMmB,IAAQ,YACR,EAAE,uBAAuBC,MAAYD;EAE3C,IAAI,KAAK,WAAW,KAAA,GAClB;EAGF,IAAI,OAAOC,KAAY,YAAY;GACjC,IAAM,EAAE,YAAS,KAAK;GAEtB,AAAKjB,EAAK,gBACR,EAAK,cAAc,IACnB,KAAK,IAAI,YAAY,OACnB,0BACA,8EACF;GAGF;EACF;EAEA,IAAMkB,IAAQzB,EAAa,CAAC,CAAC,MAAMD,GAAqB,KAAA,GAAW,KAAK,IAAI,WAAW,GACjF2B,KAAS,MAAuB;GAGpC,IAAI;IACF,AAAI,KAAK,QAAQ,KACfD,EAAM,OAAOE,IAAO,KAAK,IAAI;GAEjC,SAASC,GAAO;IACd,KAAK,IAAI,YAAY,OACnB,yBACA,kEACA,KAAA,GACAA,CACF;GACF;GAGA,AADA,KAAK,OAAOD,GACZ,KAAK,SAASH,EAAQE,CAAK;EAC7B;EAGA,AADAH,EAAM,UAAU,iBAAiB,oBAAoB,KAAK,YAAY,GACtE,KAAK,SAASC,EAAQE,CAAK;CAC7B;CAGA,YAAkB;EAChB,IAAMH,IAAQ;EAEd,AAAI,KAAK,WAAW,KAAA,MAIpBA,EAAM,uBAAuB,KAAK,MAAM,GACxCA,EAAM,UAAU,oBAAoB,oBAAoB,KAAK,YAAY,GACzE,KAAK,SAAS,KAAA,GACd,KAAK,OAAO;CACd;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-DakMxVB2.cjs"),t=require("./profiler-eVCknCzS.cjs"),n=require("./storm-D0_qZOEg.cjs");var r=`long-animation-frame`,i=class{ctx;name=`frame-phases`;observer;window={start:0,count:0};constructor(e){this.ctx=e}install(){if(!this.observer){if((typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes)?.includes(r))t.t().link(1),this.observer=new PerformanceObserver(e=>{this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record a long animation frame of the profiler.`,()=>{for(let t of e.getEntries())this.record(t)})}),this.observer.observe({type:r});else{let{once:e}=this.ctx;e.framePhases||(e.framePhases=!0,this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long animation frames. profiler.framePhases is off.`))}}}uninstall(){this.observer&&(this.observer.disconnect(),this.observer=void 0,t.t().link(1/0))}record(r){let i=r.startTime,a=i+r.duration,o=t.t().linked(i,a);if(o.length===0)return;let{capturePolicy:s}=this.ctx.config;if(!n.t(this.window,s.longFramesPerWindow,this.ctx.diagnostics,`profiler frames`,s.windowMs))return;let c=(e=0)=>e>0?e:a,l=c(r.renderStart),u=c(r.styleAndLayoutStart),d=0;for(let e of r.scripts??[])d+=e.forcedStyleAndLayoutDuration??0;let f=[[`script`,l-i],[`render`,u-l],[`style_layout`,a-u],[`forced_layout`,d]];for(let t of o)for(let[n,r]of f)this.ctx.logger.logMetric(e.Kt,r,`ms`,`histogram`,{[e.Jt.probe]:t,[e.Jt.framePhase]:n})}},a=class{ctx;name=`frame-pacing`;handle;last=-1;constructor(e){this.ctx=e}onVisibility=()=>{this.last=-1};install(){let n=globalThis,{requestAnimationFrame:r}=n;if(this.handle!==void 0)return;if(typeof r!=`function`){let{once:e}=this.ctx;e.framePacing||(e.framePacing=!0,this.ctx.diagnostics.report(`capture.install_failed`,`This context has no frame callback. The frame pacing of the profiler is off.`));return}let i=t.t().probe(e.qt,void 0,this.ctx.diagnostics),a=e=>{try{this.last>=0&&i.record(e-this.last)}catch(e){this.ctx.diagnostics.report(`capture.record_failed`,`The library could not record a frame interval of the profiler.`,void 0,e)}this.last=e,this.handle=r(a)};n.document?.addEventListener(`visibilitychange`,this.onVisibility),this.handle=r(a)}uninstall(){let e=globalThis;this.handle!==void 0&&(e.cancelAnimationFrame?.(this.handle),e.document?.removeEventListener(`visibilitychange`,this.onVisibility),this.handle=void 0,this.last=-1)}};exports.FramePacingCapture=a,exports.FramePhasesCapture=i;
2
- //# sourceMappingURL=profiler-frames-Dg2OebB2.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiler-frames-Dg2OebB2.cjs","names":["profilerCore","allowInWindow","PROFILE_FRAME_METRIC_NAME","PROFILE_KEYS","PROFILE_FRAME_PROBE","require_constants","require_profiler","require_storm","FRAME_TYPE","FramePhasesCapture","ctx","entry","list","once","start","end","names","capturePolicy","phaseStart","value","renderStart","layoutStart","forced","script","phases","name","phase","ms","FramePacingCapture","scope","request","probe","frame","time","error"],"sources":["../src/capture/profiler-frames.ts"],"sourcesContent":["// src/capture/profiler-frames.ts\n//\n// Ties the profiler to the browser's rendering work. The frame phases capture attributes the\n// phases of each long animation frame to the probes that ran in it. Frame pacing measures the\n// time between consecutive frames.\n\nimport {\n PROFILE_FRAME_METRIC_NAME,\n PROFILE_FRAME_PROBE,\n PROFILE_KEYS,\n PROFILER_LINK_MIN_MS,\n} from \"../constants\";\nimport { profilerCore } from \"../core/profiler\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Long animation frames, not long tasks: long tasks don't have phases. */\nconst FRAME_TYPE = \"long-animation-frame\";\n\n/** One script in a long animation frame. */\ninterface FrameScript {\n /** Style and layout time the script forced, in ms. */\n forcedStyleAndLayoutDuration?: number;\n}\n\n/** A long animation frame. Some versions of the DOM typings don't declare these fields. */\ninterface PhaseEntry extends PerformanceEntry {\n /** When the render callbacks started. 0 if the frame didn't render. */\n renderStart?: number;\n /** When style and layout started. 0 if the frame didn't render. */\n styleAndLayoutStart?: number;\n /** The scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/** The page globals frame pacing needs. A worker or Node.js may have none of them. */\ninterface FrameScope {\n /** Calls a function before the next paint, passing the frame's start time. */\n requestAnimationFrame?: (callback: (time: number) => void) => number;\n cancelAnimationFrame?: (handle: number) => void;\n document?: Pick<Document, \"addEventListener\" | \"removeEventListener\">;\n}\n\n/** Attributes the phases of each long animation frame to every probe with a span in it. */\nexport class FramePhasesCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"frame-phases\";\n\n /** The active observer. Undefined while the capture isn't installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit for this capture, so a frozen tab can't flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Starts observing long animation frames and turns on the recent-span ring. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Older browsers have no supportedEntryTypes. The capture just stays off there.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n\n if (!supported?.includes(FRAME_TYPE)) {\n // Report on the first install in a document only, not on every reinstall after configure().\n const { once } = this.ctx;\n\n if (!once.framePhases) {\n once.framePhases = true;\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long animation frames. profiler.framePhases is off.\",\n );\n }\n\n return;\n }\n\n profilerCore().link(PROFILER_LINK_MIN_MS);\n this.observer = new PerformanceObserver((list) => {\n // The browser calls this directly, so anything we throw is an uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record a long animation frame of the profiler.\",\n () => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n },\n );\n });\n\n // Not buffered: a buffered frame is older than anything in the ring and would link to nothing.\n this.observer.observe({ type: FRAME_TYPE });\n }\n\n /** Disconnects the observer and turns the recent-span ring off. */\n uninstall(): void {\n if (!this.observer) {\n return;\n }\n\n this.observer.disconnect();\n this.observer = undefined;\n profilerCore().link(Infinity);\n }\n\n /**\n * Records one frame's phases for every probe that had a span in the frame.\n * @param entry Long animation frame entry.\n */\n private record(entry: PhaseEntry): void {\n const start = entry.startTime;\n const end = start + entry.duration;\n const names = profilerCore().linked(start, end);\n\n if (names.length === 0) {\n return;\n }\n\n const { capturePolicy } = this.ctx.config;\n\n if (\n !allowInWindow(\n this.window,\n capturePolicy.longFramesPerWindow,\n this.ctx.diagnostics,\n \"profiler frames\",\n capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n // A frame that didn't render has 0 in both fields. The whole frame then counts as script.\n const phaseStart = (value = 0): number => (value > 0 ? value : end);\n const renderStart = phaseStart(entry.renderStart);\n const layoutStart = phaseStart(entry.styleAndLayoutStart);\n let forced = 0;\n\n for (const script of entry.scripts ?? []) {\n forced += script.forcedStyleAndLayoutDuration ?? 0;\n }\n\n const phases: [string, number][] = [\n [\"script\", renderStart - start],\n [\"render\", layoutStart - renderStart],\n [\"style_layout\", end - layoutStart],\n [\"forced_layout\", forced],\n ];\n\n for (const name of names) {\n for (const [phase, ms] of phases) {\n this.ctx.logger.logMetric(PROFILE_FRAME_METRIC_NAME, ms, \"ms\", \"histogram\", {\n [PROFILE_KEYS.probe]: name,\n [PROFILE_KEYS.framePhase]: phase,\n });\n }\n }\n }\n}\n\n/** Measures the time between consecutive frames with the frame pacing probe. */\nexport class FramePacingCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"frame-pacing\";\n\n /** Handle of the pending frame callback. Undefined while the capture isn't installed. */\n private handle: number | undefined;\n\n /** Start time of the last frame. -1 before the first frame and after the page was hidden. */\n private last = -1;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and logger.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** A hidden page gets no frame callbacks, so the first frame back isn't an interval. */\n private readonly onVisibility = (): void => {\n this.last = -1;\n };\n\n /** Starts the frame callback loop. */\n install(): void {\n const scope = globalThis as FrameScope;\n const { requestAnimationFrame: request } = scope;\n\n if (this.handle !== undefined) {\n return;\n }\n\n if (typeof request !== \"function\") {\n const { once } = this.ctx;\n\n if (!once.framePacing) {\n once.framePacing = true;\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"This context has no frame callback. The frame pacing of the profiler is off.\",\n );\n }\n\n return;\n }\n\n const probe = profilerCore().probe(PROFILE_FRAME_PROBE, undefined, this.ctx.diagnostics);\n const frame = (time: number): void => {\n // The browser calls this directly, so anything we throw is an uncaught error on the page.\n // It also runs every frame, which is why the try block allocates nothing.\n try {\n if (this.last >= 0) {\n probe.record(time - this.last);\n }\n } catch (error) {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The library could not record a frame interval of the profiler.\",\n undefined,\n error,\n );\n }\n\n this.last = time;\n this.handle = request(frame);\n };\n\n scope.document?.addEventListener(\"visibilitychange\", this.onVisibility);\n this.handle = request(frame);\n }\n\n /** Stops the frame callback loop. */\n uninstall(): void {\n const scope = globalThis as FrameScope;\n\n if (this.handle === undefined) {\n return;\n }\n\n scope.cancelAnimationFrame?.(this.handle);\n scope.document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.handle = undefined;\n this.last = -1;\n }\n}\n"],"mappings":"A,mHAiBA,IAAMQ,EAAa,uBA2BNC,EAAb,KAAmD,CAapB,IAX7B,KAAgB,eAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,MAAK,SAUT,KAJE,OAAO,oBAAwB,IAC3B,IAAA,GACA,oBAAoB,oBAAA,EAEV,SAASF,CAAU,EAenCF,EAAA,EAAa,CAAC,CAAC,KAAA,CAAyB,EACxC,KAAK,SAAW,IAAI,oBAAqB,GAAS,CAEhD,KAAK,IAAI,YAAY,MACnB,wBACA,2EACM,CACJ,IAAK,IAAMK,KAASC,EAAK,WAAW,EAClC,KAAK,OAAOD,CAAK,CAErB,CACF,CACF,CAAC,EAGD,KAAK,SAAS,QAAQ,CAAE,KAAMH,CAAW,CAAC,MA9BJ,CAEpC,GAAM,CA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